mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
Compare commits
213 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dbf011f026 | |||
| 54c54d5e65 | |||
| 5c133bbf40 | |||
| f814b0000d | |||
| 69eacd5316 | |||
| d39d544297 | |||
| 32879dd528 | |||
| dc008ad7a5 | |||
| 06cd140bd3 | |||
| 33f6540ec3 | |||
| 9cbbbdb2e9 | |||
| 6dafbc6d05 | |||
| 0a72ed5e76 | |||
| d8a93af2f5 | |||
| b27b3f6563 | |||
| fdfc034a68 | |||
| 51dc0e6a82 | |||
| 6c68f6ebec | |||
| dbf808362d | |||
| dc645b1205 | |||
| 73e3ac2606 | |||
| f15b9e73a0 | |||
| 7f2c6638a8 | |||
| 07d54d6f6e | |||
| 51c45d0573 | |||
| 91bf941e4c | |||
| 2204e851fa | |||
| b36b83a32e | |||
| 101c4b5d7a | |||
| e90380e2b4 | |||
| 09ae971cc8 | |||
| 1435076cec | |||
| 501e4449ef | |||
| 7008427022 | |||
| 1997a49e3d | |||
| 8057688da3 | |||
| 29ae0de1ef | |||
| 1c9ac0b159 | |||
| 7104fa6dd4 | |||
| 71392ec9c1 | |||
| d6708f6ff2 | |||
| 20e3d2d9ae | |||
| d758f4c592 | |||
| 783c98f41e | |||
| c24c724861 | |||
| 2653f0cb07 | |||
| c944ef6de5 | |||
| d008331e5f | |||
| 9abd16b907 | |||
| 382ba79584 | |||
| ab7468f028 | |||
| b1c7bd0a33 | |||
| 2b0ef098fd | |||
| 587f5f6bb6 | |||
| 026d593c8d | |||
| f99c7f5421 | |||
| bacc6a29a7 | |||
| 62232ec87e | |||
| 7a06db393f | |||
| f69a4c1a24 | |||
| 01d327b502 | |||
| 0ecca2b46c | |||
| 82165855c7 | |||
| 177a0febe2 | |||
| 80853fcf03 | |||
| 67049c1065 | |||
| f89ebf6882 | |||
| 14443a17be | |||
| 00675c59b0 | |||
| 96976d3ece | |||
| ab0e6fda8b | |||
| 9018ee8980 | |||
| 10ad92574d | |||
| 5401728c41 | |||
| 467287f138 | |||
| 64697fdb7f | |||
| 7e3ce20e6b | |||
| f8a7d674f9 | |||
| c3935ff027 | |||
| ce2b521ae7 | |||
| 7eb2c9334b | |||
| cac5b5c501 | |||
| a3db6e93bf | |||
| e6ba039abc | |||
| 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 |
+15
-1
@@ -28,8 +28,10 @@ updates:
|
||||
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/*']
|
||||
patterns: ['@mikro-orm/*', better-sqlite3, kysely]
|
||||
update-types: [minor, patch]
|
||||
nestjs:
|
||||
patterns: ['@nestjs/*']
|
||||
@@ -54,6 +56,18 @@ updates:
|
||||
# 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.
|
||||
|
||||
+21
-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 && \
|
||||
|
||||
@@ -156,7 +156,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
|
||||
- **Your own model**: an API key for Anthropic, OpenAI, Gemini or OpenRouter, a ChatGPT plan, or any OpenAI-compatible endpoint, set for the instance or per user
|
||||
- **You stay in charge**: reads run at once, every change waits as a card to apply or discard and can be undone for 15 minutes. Nothing leaves before you agree to the provider, and a file's text only with your consent
|
||||
- **Attachments**: drop a booking confirmation, a GPX file or a photo into the chat, and the assistant offers what to do with it
|
||||
- **MCP server** (off by default): OAuth 2.1 with mandatory PKCE and dynamic client registration, 410 tools, 30 resources and 4 prompts, 35 scopes in 17 groups ticked on the consent screen, and every call in the audit log
|
||||
- **MCP server** (off by default): OAuth 2.1 with mandatory PKCE and dynamic client registration, 453 tools, 30 resources and 4 prompts, 35 scopes in 17 groups ticked on the consent screen, and every call in the audit log
|
||||
- **Addon-aware**: twelve addon gates decide which tools a session sees, and flipping one re-registers live sessions
|
||||
|
||||
</td>
|
||||
@@ -288,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.
|
||||
|
||||
@@ -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.2.1
|
||||
version: 5.2.2
|
||||
description: Minimal Helm chart for TREK app
|
||||
appVersion: "5.2.1"
|
||||
home: https://github.com/liketrek/TREK
|
||||
sources:
|
||||
- https://github.com/liketrek/TREK
|
||||
appVersion: "5.2.2"
|
||||
|
||||
@@ -136,6 +136,9 @@ data:
|
||||
{{- if .Values.env.AMAP_API_BASE }}
|
||||
AMAP_API_BASE: {{ .Values.env.AMAP_API_BASE | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.MAP_EXTRA_CONNECT_HOSTS }}
|
||||
MAP_EXTRA_CONNECT_HOSTS: {{ .Values.env.MAP_EXTRA_CONNECT_HOSTS | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.VAPID_PUBLIC_KEY }}
|
||||
VAPID_PUBLIC_KEY: {{ .Values.env.VAPID_PUBLIC_KEY | quote }}
|
||||
{{- end }}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{{- range .Values.extraObjects }}
|
||||
---
|
||||
{{- if kindIs "string" . }}
|
||||
{{ tpl . $ }}
|
||||
{{- else }}
|
||||
{{ tpl (toYaml .) $ }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
+29
-1
@@ -170,6 +170,11 @@ env:
|
||||
# Send the Amap (高德地图) calls through an egress proxy, a cache or a gateway that speaks the same API instead of
|
||||
# restapi.amap.com directly. The key itself is a credential and goes under secretEnv.AMAP_API_KEY, or into
|
||||
# Admin > Settings > API Keys. Defaults to https://restapi.amap.com.
|
||||
# MAP_EXTRA_CONNECT_HOSTS: ""
|
||||
# Hosts of your own map tiles or vector styles that the GL maps may load, comma-separated, e.g.
|
||||
# "tiles.example.com,*.maps.example.org:8443": a host name, optionally with a port or as a wildcard over
|
||||
# its subdomains; https is implied. They are added to the Content-Security-Policy and told to the app.
|
||||
# An entry that is not a plain host name aborts startup.
|
||||
# VAPID_PUBLIC_KEY: ""
|
||||
# Web Push key pair, public half (base64url, 65 bytes). Leave both halves empty and TREK generates a pair on
|
||||
# first start and keeps it in the database, so it travels with backups. To use your own pair, set this and
|
||||
@@ -190,7 +195,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 +343,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
-1
@@ -68,7 +68,7 @@ The offline core is flagship work surrounded by a periphery that ignores it. New
|
||||
|
||||
## Big-picture pieces
|
||||
|
||||
- **Maps** (`src/components/Map/`): two interchangeable renderers — Leaflet and Mapbox/MapLibre GL — chosen at runtime by `MapViewAuto.tsx`. Keep both in sync when changing map features, and keep `mapbox-gl` and `maplibre-gl` in separate chunks (`check:gl-split`). The raster prefetcher fetches tiles `no-cors` so custom tile providers without CORS headers keep working; the vector prefetcher deliberately uses `cors` because it has to read the responses — don't "align" one with the other.
|
||||
- **Maps** (`src/components/Map/`): two interchangeable renderers — Leaflet and Mapbox/MapLibre GL — chosen at runtime by `MapViewAuto.tsx`. Keep both in sync when changing map features, and keep `mapbox-gl` and `maplibre-gl` in separate chunks (`check:gl-split`). The raster prefetcher fetches tiles `no-cors` so custom tile providers without CORS headers keep working, except a template MapLibre draws (`trek:template`), whose tiles a GL map reads with CORS and the service worker keeps apart in `map-tiles-gl` (`src/sync/glTileCache.ts`); the vector prefetcher deliberately uses `cors` because it has to read the responses — don't "align" one with the other.
|
||||
- **i18n** (`src/i18n/TranslationContext.tsx`): `en` is bundled; every other locale is a dynamic `import('@trek/shared/i18n/<locale>')` so Vite emits one chunk per locale. Strings live in `shared/`, never here. `t()` returns an unknown key unchanged, so `lint:i18n-keys` (`scripts/i18n-keys.mjs`) resolves every literal key in `t()`, `tHtml()`, `tr()`, `<TransHtml html>`, `translateApiError` and `*Key` props against `shared/src/i18n/en`; a template whose interpolations only choose between string literals is expanded and each branch checked as a key; any other template key is read with each interpolation as one key segment and passes by itself only when it reaches between 1 and `MAX_IMPLICIT_MATCHES` (30) en keys; a wider one, or one with no fixed dotted prefix, needs a `DYNAMIC_ALLOWED` entry keyed by file and template that says what bounds the value, and an entry the check no longer needs fails. Pass counts as numbers, and let a plural group pick the wording instead of switching keys on the count.
|
||||
- **Mobile shell** (`src/mobile/`): below the phone breakpoint (`useIsPhone`) `App.tsx` wraps routes in `MobileShell` and the `M*` screens under `mobile/screens/` take over. A UI change to a domain with an `M*` twin usually needs both, and the logic change goes into the shared hook (see "Desktop and phone views" below).
|
||||
- **Plugins UI** (`src/components/Plugins/`): third-party surfaces render only inside the sandboxed `PluginFrame` iframe (postMessage bridge, live theme-token sync). Host-rendered contribution points (widgets, schedule rows, map layers, planner columns/actions) render server-normalized primitives only — plugin markup never runs inline. Authoring is covered by the `trek-plugin-dev` skill.
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -2,7 +2,8 @@ import { expect, test, type Locator } from '@playwright/test';
|
||||
|
||||
// #2981: labels, category and status took the whole row, so a place with two or
|
||||
// three long labels showed one letter of its name or none, and the status pill
|
||||
// ran out of the card. Measured in a real browser because the layout is the bug.
|
||||
// ran out of the card. The labels are tags now, shown as dots behind the name.
|
||||
// Measured in a real browser because the layout is the bug.
|
||||
const PLACES = [
|
||||
{ name: 'Oceanario de Lisboa', labels: ['Core shortlist', 'Heritage specialist', 'Pair with another stop'] },
|
||||
{ name: 'Cove of Ursa', labels: ['Heritage specialist', 'Pair with another stop'] },
|
||||
@@ -83,11 +84,14 @@ for (const viewport of [
|
||||
// The whole name fits: it is not cut to an ellipsis.
|
||||
expect(await name.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true);
|
||||
await expectInside(row);
|
||||
// Every label is either on the row or counted by its "+N" chip.
|
||||
const shown = await row.locator('.col-lrow-label:not(.is-over)').count();
|
||||
// Read without waiting: a row whose labels all fit has no "+N".
|
||||
const [more] = await row.locator('.col-lrow-more').allTextContents();
|
||||
expect(shown + (more ? Number(more.replace('+', '')) : 0)).toBe(place.labels.length);
|
||||
// The labels are the place's tags: dots behind the name, every name in their label.
|
||||
const dots = row.locator('.li .t [role="img"]:not(.col-lrow-caticon)');
|
||||
if (place.labels.length === 0) {
|
||||
await expect(dots).toHaveCount(0);
|
||||
} else {
|
||||
const named = ((await dots.getAttribute('aria-label')) ?? '').split(', ');
|
||||
expect([...named].sort()).toEqual([...place.labels].sort());
|
||||
}
|
||||
}
|
||||
// The map's label strip stays inside the map: whole, or folded into its button.
|
||||
const topbar = page.locator('.col-map-topbar');
|
||||
|
||||
@@ -31,7 +31,7 @@ test('#1432 iPad: the places list scrolls under a swipe', async ({ page }) => {
|
||||
|
||||
await page.getByText(title).first().click()
|
||||
await expect(page).toHaveURL(/\/trips\/\d+/)
|
||||
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 })
|
||||
await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({ timeout: 20_000 })
|
||||
|
||||
const tripId = page.url().match(/\/trips\/(\d+)/)![1]
|
||||
|
||||
@@ -43,7 +43,7 @@ test('#1432 iPad: the places list scrolls under a swipe', async ({ page }) => {
|
||||
expect(res.ok(), `seed place ${i}`).toBeTruthy()
|
||||
}
|
||||
await page.reload()
|
||||
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 })
|
||||
await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({ timeout: 20_000 })
|
||||
|
||||
// An iPad is inside the 768-1023px band, where only one side panel is open at a
|
||||
// time so the map keeps a usable width (#2247). The places list is one tap away.
|
||||
@@ -88,7 +88,7 @@ test('#1432 iPad: the places list scrolls under a swipe', async ({ page }) => {
|
||||
// 3. The iPad must still get the desktop shell — isMobile stayed width-based. One
|
||||
// panel at a time (#2247), so opening Places closed the day plan and left its
|
||||
// tab as the way back.
|
||||
await expect(page.locator('.leaflet-container')).toBeVisible()
|
||||
await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible()
|
||||
// The top tab bar has a button named Plan as well; the way back is the panel's
|
||||
// own tab, which is accented while its panel is closed.
|
||||
await expect(page.locator('button[aria-label="Plan"].bg-accent')).toBeVisible()
|
||||
|
||||
@@ -22,7 +22,7 @@ test('desktop: reorder arrows are hidden-and-inert until the row is hovered', as
|
||||
|
||||
await page.getByText(title).first().click()
|
||||
await expect(page).toHaveURL(/\/trips\/\d+/)
|
||||
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 })
|
||||
await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({ timeout: 20_000 })
|
||||
|
||||
// Two places on day 1, so the day plan renders rows carrying reorder arrows.
|
||||
const tripId = page.url().match(/\/trips\/(\d+)/)![1]
|
||||
@@ -38,7 +38,7 @@ test('desktop: reorder arrows are hidden-and-inert until the row is hovered', as
|
||||
})
|
||||
}
|
||||
await page.reload()
|
||||
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 })
|
||||
await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({ timeout: 20_000 })
|
||||
|
||||
const row = page.locator('.dp-row').filter({ hasText: 'Alpha' }).first()
|
||||
await expect(row).toBeVisible({ timeout: 20_000 })
|
||||
|
||||
@@ -58,7 +58,9 @@ test('desktop: a stay booked in another session shows in the day plan without a
|
||||
const hotel = `Mercure Hotel ${Date.now()}`;
|
||||
const { tripId, dayIds } = await seedTrip(page.request, `Stay live ${Date.now()}`);
|
||||
await openPlanner(page, tripId);
|
||||
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 });
|
||||
await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({
|
||||
timeout: 20_000,
|
||||
});
|
||||
|
||||
await bookElsewhere(browser, tripId, dayIds, hotel);
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -24,6 +24,6 @@ test('open a trip and land in the planner with a map', async ({ page }) => {
|
||||
await page.getByText(title).first().click()
|
||||
|
||||
await expect(page).toHaveURL(/\/trips\/\d+/)
|
||||
// The planner shows a Leaflet map once mounted (past the splash screen).
|
||||
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 })
|
||||
// The planner shows its configured map once mounted.
|
||||
await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({ timeout: 20_000 })
|
||||
})
|
||||
|
||||
@@ -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
-14
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@trek/client",
|
||||
"version": "5.2.1",
|
||||
"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,12 +102,13 @@
|
||||
"@fontsource/shrikhand": "^5.3.0",
|
||||
"@fontsource/yellowtail": "^5.3.0",
|
||||
"@maplibre/maplibre-gl-leaflet": "0.1.4",
|
||||
"@noble/hashes": "^1.8.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",
|
||||
@@ -118,7 +119,7 @@
|
||||
"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,20 @@
|
||||
"@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/geojson": "^7946.0.16",
|
||||
"@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",
|
||||
"@types/topojson-specification": "^1.0.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 +160,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.73.0",
|
||||
"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,28 +1,28 @@
|
||||
{
|
||||
"src": {
|
||||
"@typescript-eslint/no-non-null-assertion": 354,
|
||||
"@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": 810,
|
||||
"no-console": 85,
|
||||
"complexity": 214,
|
||||
"@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": 385,
|
||||
"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": 95,
|
||||
"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,
|
||||
"max-depth": 21,
|
||||
"max-depth": 19,
|
||||
"react-hooks/void-use-memo": 1,
|
||||
"@typescript-eslint/no-unused-expressions": 2,
|
||||
"react-hooks/purity": 1,
|
||||
@@ -30,22 +30,21 @@
|
||||
"no-useless-escape": 1
|
||||
},
|
||||
"suppressed": {
|
||||
"@typescript-eslint/no-explicit-any": 38,
|
||||
"@typescript-eslint/no-explicit-any": 37,
|
||||
"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",
|
||||
@@ -208,7 +208,7 @@
|
||||
"desktop": [
|
||||
"src/components/Planner/DayDetailPanel.tsx",
|
||||
"src/components/Planner/DayPlanSidebar.tsx",
|
||||
"src/components/Planner/PlaceInspector.tsx",
|
||||
"src/components/Planner/PlaceLinkedBookingCard.tsx",
|
||||
"src/components/Planner/ReservationModal.tsx",
|
||||
"src/components/Planner/ReservationsPanel.tsx",
|
||||
"src/components/Planner/TransportModal.tsx",
|
||||
@@ -287,10 +287,94 @@
|
||||
},
|
||||
{
|
||||
"feature": "Collection place detail",
|
||||
"hooks": ["src/components/Collections/useCollectionPlaceForm.ts"],
|
||||
"hooks": [
|
||||
"src/components/Collections/useCollectionPlaceForm.ts",
|
||||
"src/components/Collections/useLibraryPlace.ts",
|
||||
"src/components/Collections/usePlaceSheet.ts",
|
||||
"src/components/Collections/usePlaceTags.ts",
|
||||
"src/components/Collections/libraryPairs.ts"
|
||||
],
|
||||
"desktop": ["src/components/Collections/CollectionPlaceDetail.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MCollPlaceSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Collection place order",
|
||||
"hooks": ["src/components/Collections/usePlaceReorder.ts"],
|
||||
"desktop": ["src/components/Collections/CollectionList.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MCollections.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Collection place position search",
|
||||
"hooks": ["src/components/shared/useLocationSearch.ts"],
|
||||
"desktop": ["src/components/Collections/CollectionLocationSearch.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MCollLocationSearch.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Places: a place of all places",
|
||||
"hooks": [
|
||||
"src/components/Collections/libraryPairs.ts",
|
||||
"src/components/Collections/usePlaceSheet.ts",
|
||||
"src/components/Collections/usePlaceTags.ts",
|
||||
"src/components/Collections/usePlaceEdit.ts",
|
||||
"src/components/Collections/usePlaceRating.ts"
|
||||
],
|
||||
"desktop": ["src/components/Collections/LibraryPlaceDetail.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MLibraryPlaceSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Places: where a place is kept",
|
||||
"hooks": ["src/components/Collections/libraryDates.ts"],
|
||||
"desktop": ["src/components/Collections/PlaceOrigins.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MPlaceOrigins.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Places: the tabs of a place",
|
||||
"hooks": ["src/components/Collections/usePlaceSheet.ts"],
|
||||
"desktop": ["src/components/Collections/PlaceSheetTabs.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MPlaceSheetTabs.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Places: tours and bookings of a place",
|
||||
"hooks": ["src/components/Collections/usePlaceActivities.ts", "src/components/Collections/placeExtrasText.ts"],
|
||||
"desktop": ["src/components/Collections/PlaceActivitiesSection.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MPlaceActivitiesSection.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Places: changes of a place",
|
||||
"hooks": ["src/components/Collections/usePlaceHistory.ts", "src/components/Collections/placeExtrasText.ts"],
|
||||
"desktop": ["src/components/Collections/PlaceHistorySection.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MPlaceHistorySection.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Places: notes of a place",
|
||||
"hooks": ["src/components/Collections/useOriginNotes.ts"],
|
||||
"desktop": ["src/components/Collections/OriginNotesSection.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MOriginNotesSection.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Places: pictures and files of a place",
|
||||
"hooks": ["src/components/Collections/usePlaceMedia.ts", "src/components/Collections/mediaAdd.tsx"],
|
||||
"desktop": ["src/components/Collections/PlaceMediaSection.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MPlaceMediaSection.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Places: visits of a place",
|
||||
"hooks": ["src/components/Collections/usePlaceVisits.ts"],
|
||||
"desktop": ["src/components/Collections/VisitsSection.tsx", "src/components/Collections/TripPlaceVisits.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MVisitsSection.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Places: possible duplicates",
|
||||
"hooks": ["src/components/Collections/DuplicatePairCard.tsx"],
|
||||
"desktop": ["src/components/Collections/DuplicatesDialog.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MDuplicatesSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Places: all places",
|
||||
"hooks": ["src/components/Collections/usePlacesLibrary.ts", "src/components/Collections/usePlaceDuplicates.ts"],
|
||||
"desktop": ["src/components/Collections/PlacesLibraryView.tsx"],
|
||||
"mobile": ["src/mobile/screens/collections/MPlacesLibrary.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Collection sharing",
|
||||
"hooks": ["src/components/Collections/useCollectionSharing.ts"],
|
||||
@@ -1120,6 +1204,11 @@
|
||||
}
|
||||
],
|
||||
"mobileOnly": {
|
||||
"src/mobile/screens/collections/MPlaceCard.tsx": "The frame of a group in the phone's place view; the desktop twin is PlaceCard, plain markup with no logic to share.",
|
||||
"src/mobile/screens/collections/MPlaceEditForm.tsx": "Markup over the usePlaceEdit state MLibraryPlaceSheet passes in; the hook is in the \"a place of all places\" pair.",
|
||||
"src/mobile/screens/collections/MPlaceSheetShell.tsx": "The phone's frame of the one place view (cover, body, bottom row); the desktop frame is DialogShell.",
|
||||
"src/mobile/screens/collections/MPlaceTagsCard.tsx": "Markup over the usePlaceTags state the place sheets pass in; the hook is in their pairs.",
|
||||
"src/mobile/screens/collections/MCollFilterKit.tsx": "Markup only: the filter chips, dropdown rows and empty note the phone's lists and all-places screens share; the desktop draws its own filter row (FilterDropdown).",
|
||||
"src/mobile/screens/trip/sheets/MReviewNotice.tsx": "The transport sheet's row asking for a look at an imported booking; the desktop dialog folds the same \"looks right\" action into its review pill (ReviewPill in bookingParts.tsx), so there is no separate twin.",
|
||||
"src/mobile/screens/mail/MMailInboxHost.tsx": "Mounts the phone shell's one inbox sheet and reads the person's import settings; the desktop mounts its dialog from the Navbar, so there is no twin.",
|
||||
"src/mobile/screens/admin/MAdminOidcCard.tsx": "Markup only; the OIDC card of MAdminSettingsSection, with the form state from useAdmin and the save from its useAdminSettingsActions handed in through props.",
|
||||
@@ -1127,8 +1216,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 +1296,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",
|
||||
@@ -234,7 +233,6 @@
|
||||
"src/components/Collections/CollectionPicker.test.tsx",
|
||||
"src/components/Collections/CollectionPicker.tsx",
|
||||
"src/components/Collections/CollectionPlaceDetail.test.tsx",
|
||||
"src/components/Collections/CollectionPlaceDetail.tsx",
|
||||
"src/components/Collections/CopyToTripModal.test.tsx",
|
||||
"src/components/Collections/CopyToTripModal.tsx",
|
||||
"src/components/Collections/ImportCollectionModal.test.tsx",
|
||||
@@ -266,10 +264,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 +1140,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 +1277,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",
|
||||
@@ -1297,7 +1287,6 @@
|
||||
"src/mobile/screens/collections/MCollLinksEditor.tsx",
|
||||
"src/mobile/screens/collections/MCollListPickerSheet.tsx",
|
||||
"src/mobile/screens/collections/MCollPlaceRow.tsx",
|
||||
"src/mobile/screens/collections/MCollPlaceSheet.tsx",
|
||||
"src/mobile/screens/collections/MCollShareSheet.tsx",
|
||||
"src/mobile/screens/collections/MCollSheetKit.tsx",
|
||||
"src/mobile/screens/collections/MCollTripPickerSheet.tsx",
|
||||
@@ -1440,9 +1429,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 +1484,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 +1495,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 +1869,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 +2099,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. */
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"admin.ts": 112,
|
||||
"atlas.ts": 9,
|
||||
"atlas.ts": 7,
|
||||
"backup.ts": 10,
|
||||
"budget.ts": 35,
|
||||
"categories.ts": 1,
|
||||
"collab.ts": 9,
|
||||
"collection.ts": 35,
|
||||
"collection.ts": 29,
|
||||
"common.ts": 7,
|
||||
"dashboard.ts": 64,
|
||||
"dawarich.ts": 15,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
"components/Collab/CollabChatEmojiPicker.tsx": 3,
|
||||
"components/Collab/CollabChatReactionBadge.tsx": 3,
|
||||
"components/Collab/CollabChatReactionMenu.tsx": 1,
|
||||
"components/Collections/CollectionPlaceDetail.tsx": 2,
|
||||
"components/Files/FileManagerAvatarChip.tsx": 3,
|
||||
"components/Journey/JourneyDayJump.tsx": 1,
|
||||
"components/Journey/JourneyDetailPageDatePicker.tsx": 1,
|
||||
@@ -24,8 +23,8 @@
|
||||
"components/Map/DawarichTrailPill.tsx": 1,
|
||||
"components/Map/LocationButton.tsx": 1,
|
||||
"components/Map/MapTogglePill.tsx": 1,
|
||||
"components/Map/MapView.tsx": 5,
|
||||
"components/Map/MapViewGL.tsx": 7,
|
||||
"components/Map/MapView.tsx": 4,
|
||||
"components/Map/MapViewGL.tsx": 6,
|
||||
"components/Map/NightPauseTooltip.tsx": 1,
|
||||
"components/Map/PlaceHoverCard.tsx": 1,
|
||||
"components/Map/PoiCategoryPill.tsx": 1,
|
||||
@@ -82,7 +81,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 +88,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,
|
||||
@@ -7,6 +8,6 @@
|
||||
"mobile/components/trek3d/MascotClip.tsx": 1,
|
||||
"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
|
||||
}
|
||||
|
||||
@@ -5,22 +5,21 @@
|
||||
"src/components/Admin/AdminPluginsPanel.tsx": 1265,
|
||||
"src/components/Budget/CostsPanel.test.tsx": 2725,
|
||||
"src/components/Budget/CostsPanel.tsx": 1607,
|
||||
"src/components/Map/MapView.tsx": 1200,
|
||||
"src/components/Map/MapView.tsx": 1191,
|
||||
"src/components/Map/MapViewGL.test.tsx": 2919,
|
||||
"src/components/Map/MapViewGL.tsx": 2116,
|
||||
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
|
||||
"src/components/Map/MapViewGL.tsx": 2083,
|
||||
"src/components/Planner/DayDetailPanel.test.tsx": 2331,
|
||||
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 2908,
|
||||
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
|
||||
"src/components/Planner/PlaceInspector.tsx": 1128,
|
||||
"src/components/Planner/PlaceInspector.tsx": 1030,
|
||||
"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,
|
||||
@@ -60,8 +59,8 @@
|
||||
"components/Map/LocationButton.tsx": 1,
|
||||
"components/Map/MapPluginMarkers.tsx": 2,
|
||||
"components/Map/MapTogglePill.tsx": 1,
|
||||
"components/Map/MapView.tsx": 7,
|
||||
"components/Map/MapViewGL.tsx": 10,
|
||||
"components/Map/MapView.tsx": 5,
|
||||
"components/Map/MapViewGL.tsx": 8,
|
||||
"components/Map/NightPauseTooltip.tsx": 1,
|
||||
"components/Map/PlaceHoverCard.tsx": 1,
|
||||
"components/Map/ReservationOverlay.tsx": 5,
|
||||
@@ -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,
|
||||
@@ -175,11 +171,10 @@
|
||||
"mobile/screens/collections/MCollLinksEditor.tsx": 2,
|
||||
"mobile/screens/collections/MCollListPickerSheet.tsx": 3,
|
||||
"mobile/screens/collections/MCollPlaceRow.tsx": 3,
|
||||
"mobile/screens/collections/MCollPlaceSheet.tsx": 11,
|
||||
"mobile/screens/collections/MCollShareSheet.tsx": 14,
|
||||
"mobile/screens/collections/MCollSheetKit.tsx": 5,
|
||||
"mobile/screens/collections/MCollTripPickerSheet.tsx": 4,
|
||||
"mobile/screens/collections/MCollections.tsx": 13,
|
||||
"mobile/screens/collections/MCollections.tsx": 9,
|
||||
"mobile/screens/dashboard/MDashWidgets.tsx": 22,
|
||||
"mobile/screens/dashboard/MDashboard.tsx": 30,
|
||||
"mobile/screens/dashboard/MNewTripSheet.tsx": 12,
|
||||
@@ -262,7 +257,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 +277,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 +291,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,16 +2,16 @@
|
||||
"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,
|
||||
"components/Collections/AddPlaceToCollectionModal.tsx": 1,
|
||||
"components/Collections/BulkAssignLabelModal.tsx": 1,
|
||||
"components/Collections/CollectionPicker.tsx": 1,
|
||||
"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,11 +56,9 @@
|
||||
"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,
|
||||
"mobile/screens/collections/collectionsMobileModel.ts": 15,
|
||||
"mobile/screens/dashboard/MDashboard.tsx": 3,
|
||||
@@ -71,8 +69,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
|
||||
}
|
||||
|
||||
+41
-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))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -436,6 +456,19 @@ describe('App — on-mount effects', () => {
|
||||
await waitFor(() => expect(setManaged).toHaveBeenCalledWith(false))
|
||||
})
|
||||
|
||||
it("FE-COMP-APP-018d: the operator's map hosts reach the store the map engine reads", async () => {
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () => HttpResponse.json({ map_extra_connect_hosts: ['tiles.example.com'] }))
|
||||
)
|
||||
useAuthStore.setState({
|
||||
isLoading: false,
|
||||
isAuthenticated: false,
|
||||
loadUser: vi.fn().mockResolvedValue(undefined),
|
||||
})
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(useAuthStore.getState().mapExtraConnectHosts).toEqual(['tiles.example.com']))
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-018c: app-config is asked again after a failed answer, so managed is not lost', async () => {
|
||||
// A page opened while the server restarts got a 502 here and kept every
|
||||
// default for the session, which brought back the operator's settings.
|
||||
@@ -532,7 +565,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 +620,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 +642,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 +718,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()
|
||||
|
||||
+68
-22
@@ -1,7 +1,9 @@
|
||||
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 LegacyCollectionsRedirect from './components/Collections/LegacyCollectionsRedirect'
|
||||
import { useAuthStore } from './store/authStore'
|
||||
import { useSettingsStore } from './store/settingsStore'
|
||||
import { preloadTripMapRenderer } from './components/Map/glLazy'
|
||||
import { applyAppearance } from './theme/applyAppearance'
|
||||
import { useAddonStore } from './store/addonStore'
|
||||
import { usePluginStore } from './store/pluginStore'
|
||||
@@ -17,6 +19,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'
|
||||
@@ -95,6 +99,26 @@ const MJourneyDetailScreen = lazyWithRetry(() => import('./mobile/screens/journe
|
||||
const MCollectionsScreen = lazyWithRetry(() => import('./mobile/screens/collections/MCollections'))
|
||||
const MNotificationsScreen = lazyWithRetry(() => import('./mobile/screens/notifications/MNotifications'))
|
||||
|
||||
// The main sections, loaded ahead once signed in and settled, so the first
|
||||
// switch to one does not wait for its code. A load that fails here is no
|
||||
// error: the route loads it again when it is opened.
|
||||
const DESKTOP_SECTIONS = [
|
||||
() => import('./pages/DashboardPage'),
|
||||
() => import('./pages/VacayPage'),
|
||||
() => import('./pages/AtlasPage'),
|
||||
() => import('./pages/CollectionsPage'),
|
||||
() => import('./pages/JourneyPage'),
|
||||
]
|
||||
const PHONE_SECTIONS = [
|
||||
() => import('./mobile/screens/dashboard/MDashboard'),
|
||||
() => import('./mobile/screens/vacay/MVacay'),
|
||||
() => import('./mobile/screens/atlas/MAtlas'),
|
||||
() => import('./mobile/screens/collections/MCollections'),
|
||||
() => import('./mobile/screens/journey/MJourney'),
|
||||
]
|
||||
const SECTIONS_AHEAD_AFTER_MS = 1500
|
||||
function loadedOnOpenInstead(): void {}
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: ReactNode
|
||||
adminRequired?: boolean
|
||||
@@ -113,6 +137,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 +311,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,16 +332,17 @@ 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">
|
||||
<div data-route-fallback="" className="min-h-screen flex items-center justify-center bg-surface">
|
||||
<div className="w-10 h-10 border-4 border-edge border-t-content rounded-full animate-spin"></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 +373,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; map_extra_connect_hosts?: string[]; 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)
|
||||
@@ -354,10 +381,12 @@ export default function App() {
|
||||
if (config?.version) setAppVersion(config.version)
|
||||
if (config?.has_maps_key !== undefined) setHasMapsKey(config.has_maps_key)
|
||||
if (config?.has_amap_key !== undefined) setHasAmapKey(config.has_amap_key)
|
||||
if (Array.isArray(config?.map_extra_connect_hosts)) useAuthStore.getState().setMapExtraConnectHosts(config.map_extra_connect_hosts)
|
||||
if (config?.places_provider) setPlacesProvider(config.places_provider)
|
||||
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)
|
||||
@@ -378,6 +407,10 @@ export default function App() {
|
||||
|
||||
const { settings } = useSettingsStore()
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) preloadTripMapRenderer(settings.map_provider, settings.mapbox_access_token)
|
||||
}, [isAuthenticated, settings.map_provider, settings.mapbox_access_token])
|
||||
|
||||
useInAppNotificationListener()
|
||||
useRoadtripPreferencesSync()
|
||||
useTripAddonsSync()
|
||||
@@ -398,6 +431,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({
|
||||
@@ -416,9 +455,18 @@ export default function App() {
|
||||
}, [settings.dark_mode, settings.appearance, isSharedPage])
|
||||
|
||||
const isPhone = useIsPhone()
|
||||
// On the phone, pages slide like a native navigation stack (mobile/routeTransition.ts).
|
||||
// On the phone, pages slide like a native navigation stack; on the desktop they
|
||||
// cross-fade under a navbar that stands still (mobile/routeTransition.ts).
|
||||
const navigationType = useNavigationType()
|
||||
const routedLocation = useRouteTransition(location, navigationType, isPhone)
|
||||
const routedLocation = useRouteTransition(location, navigationType, isPhone ? 'phone' : 'desktop')
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) return
|
||||
const timer = window.setTimeout(() => {
|
||||
for (const load of isPhone ? PHONE_SECTIONS : DESKTOP_SECTIONS) load().catch(loadedOnOpenInstead)
|
||||
}, SECTIONS_AHEAD_AFTER_MS)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [isAuthenticated, isPhone])
|
||||
const keepingTour = useSaveToCollectionStore(s => s.tour !== null)
|
||||
const isAuthPage = location.pathname.startsWith('/login')
|
||||
|| location.pathname.startsWith('/register')
|
||||
@@ -596,22 +644,20 @@ export default function App() {
|
||||
journey, not navigated away to. */}
|
||||
<Route path="studio" element={<JourneyStudioPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
path="/collections"
|
||||
element={
|
||||
<ProtectedRoute addonId="collections">
|
||||
<ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/collections/:id"
|
||||
element={
|
||||
<ProtectedRoute addonId="collections">
|
||||
<ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
{['/places', '/places/saved', '/places/:id'].map(path => (
|
||||
<Route
|
||||
key={path}
|
||||
path={path}
|
||||
element={
|
||||
<ProtectedRoute addonId="collections">
|
||||
<ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{/* Collections became Places (PLC-07); the old links keep working. */}
|
||||
<Route path="/collections" element={<LegacyCollectionsRedirect />} />
|
||||
<Route path="/collections/:id" element={<LegacyCollectionsRedirect />} />
|
||||
<Route
|
||||
path="/notifications"
|
||||
element={
|
||||
|
||||
@@ -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'
|
||||
@@ -57,6 +56,10 @@ const ROUTES: [string, string, string][] = [
|
||||
['/atlas', 'm-atlas', 'd-atlas'],
|
||||
['/journey', 'm-journey', 'd-journey'],
|
||||
['/journey/1', 'm-journey-detail', 'd-journey-detail'],
|
||||
['/places', 'm-collections', 'd-collections'],
|
||||
['/places/saved', 'm-collections', 'd-collections'],
|
||||
['/places/1', 'm-collections', 'd-collections'],
|
||||
// The old Collections links land in Places (PLC-07).
|
||||
['/collections', 'm-collections', 'd-collections'],
|
||||
['/collections/1', 'm-collections', 'd-collections'],
|
||||
['/notifications', 'm-notifications', 'd-notifications'],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-035
|
||||
// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-038
|
||||
//
|
||||
// The Collections addon wrapper is thin, but every method encodes a URL, a verb and a
|
||||
// request-body shape that the server contract depends on. These tests drive each method
|
||||
@@ -370,4 +370,50 @@ describe('collectionsApi', () => {
|
||||
expect(requestBody).toEqual({ gpx: '<gpx/>', file_name: 'tokyo.gpx' })
|
||||
expect(res).toEqual({ file, skipped: 0, track_points: 12 })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-036: copyToTrip() passes the notes and tags a copy takes along (D9)', async () => {
|
||||
server.use(http.post(`${BASE}/copy-to-trip`, record({ copied: 1, skipped: [], created: [] })))
|
||||
|
||||
await collectionsApi.copyToTrip({ trip_id: 7, place_ids: [10], include_notes: true, tag_ids: [4] })
|
||||
|
||||
expect(requestBody).toEqual({ trip_id: 7, place_ids: [10], include_notes: true, tag_ids: [4] })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-037: reorderPlaces() puts the ordered ids of a list (PLC-03)', async () => {
|
||||
let method = ''
|
||||
server.use(
|
||||
http.put(`${BASE}/:id/places/reorder`, async (info) => {
|
||||
method = info.request.method
|
||||
return record({ success: true })(info)
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await collectionsApi.reorderPlaces(1, [11, 10])
|
||||
|
||||
expect(method).toBe('PUT')
|
||||
expect(requestUrl).toContain(`${BASE}/1/places/reorder`)
|
||||
expect(requestBody).toEqual({ orderedIds: [11, 10] })
|
||||
expect(res).toEqual({ success: true })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-038: readMap() uploads the map file as multipart and returns the list file (PLC-22)', async () => {
|
||||
const read = {
|
||||
file: { format: 'trek.collection', version: 1, name: 'Lisbon', places: [{ name: 'Miradouro' }] },
|
||||
folders: ['Views'],
|
||||
skipped: [{ name: 'Tram 28', folder: null, reason: 'line' }],
|
||||
}
|
||||
let contentType: string | null = null
|
||||
server.use(
|
||||
// jsdom cannot read a multipart body back, so the header says what was sent.
|
||||
http.post(`${BASE}/map/read`, ({ request }) => {
|
||||
contentType = request.headers.get('content-type')
|
||||
return HttpResponse.json(read)
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await collectionsApi.readMap(new File(['<kml/>'], 'lisbon.kml'))
|
||||
|
||||
expect(contentType).toMatch(/^multipart\/form-data/)
|
||||
expect(res).toEqual(read)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -18,6 +18,8 @@ import type {
|
||||
CollectionGpxReadRequest,
|
||||
CollectionGpxReadResult,
|
||||
CollectionKmlExport,
|
||||
CollectionMapReadResult,
|
||||
CollectionPlacesReorderRequest,
|
||||
CollectionPlaceUpdateRequest,
|
||||
CollectionCopyToTripRequest,
|
||||
CollectionInviteRequest,
|
||||
@@ -76,6 +78,12 @@ export const collectionsApi = {
|
||||
ax.get(`${base}/${id}/export/gpx`).then((r: AxiosResponse) => r.data),
|
||||
readGpx: (body: CollectionGpxReadRequest): Promise<CollectionGpxReadResult> =>
|
||||
ax.post(`${base}/gpx/read`, body satisfies CollectionGpxReadRequest).then((r: AxiosResponse) => r.data),
|
||||
/** A KML or KMZ map (PLC-22) read by the server into a list file; it writes nothing, importFile(Into) does. */
|
||||
readMap: (file: File): Promise<CollectionMapReadResult> => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return postMultipart(`${base}/map/read`, fd)
|
||||
},
|
||||
/** The same list as pins for Google My Maps (#1866). */
|
||||
exportKml: (id: number): Promise<CollectionKmlExport> =>
|
||||
ax.get(`${base}/${id}/export/kml`).then((r: AxiosResponse) => r.data),
|
||||
@@ -94,6 +102,10 @@ export const collectionsApi = {
|
||||
reorder: (orderedIds: number[]): Promise<unknown> =>
|
||||
ax.post(`${base}/reorder`, { orderedIds }).then((r: AxiosResponse) => r.data),
|
||||
|
||||
/** A list's places in a new order (PLC-03): every id a place of that list, the ones left out follow. */
|
||||
reorderPlaces: (id: number, orderedIds: number[]): Promise<{ success: true }> =>
|
||||
ax.put(`${base}/${id}/places/reorder`, { orderedIds } satisfies CollectionPlacesReorderRequest).then((r: AxiosResponse) => r.data),
|
||||
|
||||
savePlace: (body: CollectionSavePlaceRequest): Promise<CollectionSaveResult> =>
|
||||
ax.post(`${base}/places`, body satisfies CollectionSavePlaceRequest).then((r: AxiosResponse) => r.data),
|
||||
saveFromTrip: (body: CollectionSaveFromTripRequest): Promise<CollectionSaveResult> =>
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// FE-API-PLACE-ACTIVITIES-001
|
||||
//
|
||||
// PLC-18: each method pins its verb, its path and its body.
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { placeActivitiesApi } from './placeActivities';
|
||||
|
||||
const activities = { activities: [], can_link: true };
|
||||
const candidates = { candidates: [] };
|
||||
const entry = { activities: [], sources: [] };
|
||||
let calls: Array<[string, string, unknown]> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
});
|
||||
|
||||
function record(data: object) {
|
||||
return async ({ request }: { request: Request }) => {
|
||||
const text = request.method === 'POST' ? await request.text() : '';
|
||||
calls.push([request.method, new URL(request.url).pathname, text ? JSON.parse(text) : null]);
|
||||
return HttpResponse.json(data);
|
||||
};
|
||||
}
|
||||
|
||||
describe('placeActivitiesApi', () => {
|
||||
it('FE-API-PLACE-ACTIVITIES-001: reads, links and unlinks the activities of trip places, saved places and entries', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips/4/places/7/activities', record(activities)),
|
||||
http.get('/api/trips/4/places/7/activities/candidates', record(candidates)),
|
||||
http.post('/api/trips/4/places/7/activities', record(activities)),
|
||||
http.delete('/api/trips/4/places/7/activities/reservations/9', record(activities)),
|
||||
http.delete('/api/trips/4/places/7/activities/tours/11', record(activities)),
|
||||
http.get('/api/addons/collections/places/8/activities', record(activities)),
|
||||
http.get('/api/addons/collections/places/8/activities/candidates', record(candidates)),
|
||||
http.post('/api/addons/collections/places/8/activities', record(activities)),
|
||||
http.delete('/api/addons/collections/places/8/activities/tours/5', record(activities)),
|
||||
http.get('/api/addons/collections/library/places/list/8/activities', record(entry))
|
||||
);
|
||||
expect(await placeActivitiesApi.tripPlace(4, 7)).toEqual(activities);
|
||||
expect(await placeActivitiesApi.tripCandidates(4, 7)).toEqual(candidates);
|
||||
expect(await placeActivitiesApi.linkTrip(4, 7, { reservation_id: 9 })).toEqual(activities);
|
||||
expect(await placeActivitiesApi.unlinkTripBooking(4, 7, 9)).toEqual(activities);
|
||||
expect(await placeActivitiesApi.unlinkTripTour(4, 7, 11)).toEqual(activities);
|
||||
expect(await placeActivitiesApi.savedPlace(8)).toEqual(activities);
|
||||
expect(await placeActivitiesApi.savedCandidates(8)).toEqual(candidates);
|
||||
expect(await placeActivitiesApi.linkSaved(8, 5)).toEqual(activities);
|
||||
expect(await placeActivitiesApi.unlinkSaved(8, 5)).toEqual(activities);
|
||||
expect(await placeActivitiesApi.libraryEntry('list', 8)).toEqual(entry);
|
||||
expect(calls).toEqual([
|
||||
['GET', '/api/trips/4/places/7/activities', null],
|
||||
['GET', '/api/trips/4/places/7/activities/candidates', null],
|
||||
['POST', '/api/trips/4/places/7/activities', { reservation_id: 9 }],
|
||||
['DELETE', '/api/trips/4/places/7/activities/reservations/9', null],
|
||||
['DELETE', '/api/trips/4/places/7/activities/tours/11', null],
|
||||
['GET', '/api/addons/collections/places/8/activities', null],
|
||||
['GET', '/api/addons/collections/places/8/activities/candidates', null],
|
||||
['POST', '/api/addons/collections/places/8/activities', { collection_tour_id: 5 }],
|
||||
['DELETE', '/api/addons/collections/places/8/activities/tours/5', null],
|
||||
['GET', '/api/addons/collections/library/places/list/8/activities', null],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import type {
|
||||
PlaceActivitiesResponse,
|
||||
PlaceActivityCandidatesResponse,
|
||||
PlaceLibraryActivitiesResponse,
|
||||
PlacesLibraryKind,
|
||||
TripPlaceActivityLinkRequest,
|
||||
} from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
const tripBase = (tripId: number, placeId: number) => `/trips/${tripId}/places/${placeId}/activities`;
|
||||
const savedBase = (collectionPlaceId: number) => `/addons/collections/places/${collectionPlaceId}/activities`;
|
||||
|
||||
/**
|
||||
* PLC-18: the bookings and tours a place is about. A trip place links bookings
|
||||
* and tours of its trip, a saved place tours kept in its list; an entry of All
|
||||
* places reads them over every origin it has. Unlinking takes only the link off.
|
||||
*/
|
||||
export const placeActivitiesApi = {
|
||||
tripPlace: (tripId: number, placeId: number, signal?: AbortSignal): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.get(tripBase(tripId, placeId), { signal }).then((r) => r.data),
|
||||
tripCandidates: (tripId: number, placeId: number, signal?: AbortSignal): Promise<PlaceActivityCandidatesResponse> =>
|
||||
apiClient.get(`${tripBase(tripId, placeId)}/candidates`, { signal }).then((r) => r.data),
|
||||
linkTrip: (tripId: number, placeId: number, body: TripPlaceActivityLinkRequest): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.post(tripBase(tripId, placeId), body).then((r) => r.data),
|
||||
unlinkTripBooking: (tripId: number, placeId: number, reservationId: number): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.delete(`${tripBase(tripId, placeId)}/reservations/${reservationId}`).then((r) => r.data),
|
||||
unlinkTripTour: (tripId: number, placeId: number, tourId: number): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.delete(`${tripBase(tripId, placeId)}/tours/${tourId}`).then((r) => r.data),
|
||||
|
||||
savedPlace: (collectionPlaceId: number, signal?: AbortSignal): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.get(savedBase(collectionPlaceId), { signal }).then((r) => r.data),
|
||||
savedCandidates: (collectionPlaceId: number, signal?: AbortSignal): Promise<PlaceActivityCandidatesResponse> =>
|
||||
apiClient.get(`${savedBase(collectionPlaceId)}/candidates`, { signal }).then((r) => r.data),
|
||||
linkSaved: (collectionPlaceId: number, collectionTourId: number): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.post(savedBase(collectionPlaceId), { collection_tour_id: collectionTourId }).then((r) => r.data),
|
||||
unlinkSaved: (collectionPlaceId: number, collectionTourId: number): Promise<PlaceActivitiesResponse> =>
|
||||
apiClient.delete(`${savedBase(collectionPlaceId)}/tours/${collectionTourId}`).then((r) => r.data),
|
||||
|
||||
libraryEntry: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceLibraryActivitiesResponse> =>
|
||||
apiClient.get(`/addons/collections/library/places/${kind}/${id}/activities`, { signal }).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
// FE-API-PLACE-HISTORY-001
|
||||
//
|
||||
// PLC-14: the history pins its verb, its path and its query, and hands back
|
||||
// what the server answered.
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { placeHistoryApi } from './placeHistory';
|
||||
|
||||
const BASE = '/api/addons/collections/library/places';
|
||||
|
||||
describe('placeHistoryApi', () => {
|
||||
it('FE-API-PLACE-HISTORY-001: reads the history of the trip place or saved place it names, page by page', async () => {
|
||||
const calls: Array<{ path: string; query: Record<string, string> }> = [];
|
||||
const page = { entries: [], next_cursor: null };
|
||||
const record = ({ request }: { request: Request }) => {
|
||||
const url = new URL(request.url);
|
||||
calls.push({ path: url.pathname, query: Object.fromEntries(url.searchParams) });
|
||||
return HttpResponse.json(page);
|
||||
};
|
||||
server.use(http.get(`${BASE}/trip/4/history`, record), http.get(`${BASE}/list/9/history`, record));
|
||||
expect(await placeHistoryApi.history('trip', 4)).toEqual(page);
|
||||
expect(await placeHistoryApi.history('list', 9, { cursor: '12', limit: 20 })).toEqual(page);
|
||||
expect(calls).toEqual([
|
||||
{ path: `${BASE}/trip/4/history`, query: {} },
|
||||
{ path: `${BASE}/list/9/history`, query: { cursor: '12', limit: '20' } },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { PlaceHistoryPageResponse, PlaceHistoryQueryInput, PlacesLibraryKind } from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
const base = '/addons/collections/library/places';
|
||||
|
||||
/** PLC-14: what changed in the details of an entry of All places, opened from a trip place or a saved place. */
|
||||
export const placeHistoryApi = {
|
||||
history: (
|
||||
kind: PlacesLibraryKind,
|
||||
id: number,
|
||||
query: PlaceHistoryQueryInput = {},
|
||||
signal?: AbortSignal
|
||||
): Promise<PlaceHistoryPageResponse> =>
|
||||
apiClient.get(`${base}/${kind}/${id}/history`, { params: query, signal }).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
// FE-API-PLACE-IDENTITIES-001 to FE-API-PLACE-IDENTITIES-002
|
||||
//
|
||||
// D5/PLC-13: each method pins its verb, its path and its body or query, and
|
||||
// hands back what the server answered.
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { placeIdentitiesApi } from './placeIdentities';
|
||||
|
||||
const BASE = '/api/addons/collections/library';
|
||||
|
||||
let calls: Array<[string, string, Record<string, string>, unknown]> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
});
|
||||
|
||||
function record(data: object) {
|
||||
return async ({ request }: { request: Request }) => {
|
||||
const url = new URL(request.url);
|
||||
const text = request.method === 'GET' ? '' : await request.text();
|
||||
calls.push([request.method, url.pathname, Object.fromEntries(url.searchParams), text ? JSON.parse(text) : null]);
|
||||
return HttpResponse.json(data);
|
||||
};
|
||||
}
|
||||
|
||||
describe('placeIdentitiesApi', () => {
|
||||
it('FE-API-PLACE-IDENTITIES-001: links and unlinks uses of an own place', async () => {
|
||||
const answer = { entry: null };
|
||||
server.use(http.post(`${BASE}/places/link`, record(answer)), http.post(`${BASE}/places/unlink`, record(answer)));
|
||||
expect(await placeIdentitiesApi.link({ uses: [{ kind: 'trip', id: 3 }], identity_id: 2 })).toEqual(answer);
|
||||
expect(await placeIdentitiesApi.unlink({ kind: 'list', id: 4 })).toEqual(answer);
|
||||
expect(calls).toEqual([
|
||||
['POST', `${BASE}/places/link`, {}, { uses: [{ kind: 'trip', id: 3 }], identity_id: 2 }],
|
||||
['POST', `${BASE}/places/unlink`, {}, { kind: 'list', id: 4 }],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-API-PLACE-IDENTITIES-002: reads duplicates, dismisses, merges and undoes', async () => {
|
||||
server.use(
|
||||
http.get(`${BASE}/duplicates`, record({ duplicates: [], next_cursor: null })),
|
||||
http.post(`${BASE}/duplicates/dismiss`, record({ success: true })),
|
||||
http.post(`${BASE}/merges`, record({ merge_id: 5, entry: null })),
|
||||
http.post(`${BASE}/merges/5/undo`, record({ success: true }))
|
||||
);
|
||||
expect(await placeIdentitiesApi.duplicates({ limit: 10 })).toEqual({ duplicates: [], next_cursor: null });
|
||||
expect(await placeIdentitiesApi.dismiss('trip:1', 'list:2')).toEqual({ success: true });
|
||||
expect(await placeIdentitiesApi.merge('trip:1', 'list:2')).toEqual({ merge_id: 5, entry: null });
|
||||
expect(await placeIdentitiesApi.undoMerge(5)).toEqual({ success: true });
|
||||
expect(calls).toEqual([
|
||||
['GET', `${BASE}/duplicates`, { limit: '10' }, null],
|
||||
['POST', `${BASE}/duplicates/dismiss`, {}, { a: 'trip:1', b: 'list:2' }],
|
||||
['POST', `${BASE}/merges`, {}, { leading: 'trip:1', other: 'list:2' }],
|
||||
['POST', `${BASE}/merges/5/undo`, {}, null],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import type {
|
||||
PlacesLibraryDuplicatesQueryInput,
|
||||
PlacesLibraryDuplicatesResponse,
|
||||
PlacesLibraryEntryResponse,
|
||||
PlacesLibraryLinkRequest,
|
||||
PlacesLibraryMergeResponse,
|
||||
PlacesLibraryUse,
|
||||
SuccessResponse,
|
||||
} from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
const base = '/addons/collections/library';
|
||||
|
||||
/** D5/PLC-13: the user's own places in "All places", the duplicate suggestions and merges. */
|
||||
export const placeIdentitiesApi = {
|
||||
link: (body: PlacesLibraryLinkRequest): Promise<PlacesLibraryEntryResponse> =>
|
||||
apiClient.post(`${base}/places/link`, body).then((r) => r.data),
|
||||
unlink: (use: PlacesLibraryUse): Promise<PlacesLibraryEntryResponse> =>
|
||||
apiClient.post(`${base}/places/unlink`, use).then((r) => r.data),
|
||||
duplicates: (
|
||||
query: PlacesLibraryDuplicatesQueryInput = {},
|
||||
signal?: AbortSignal
|
||||
): Promise<PlacesLibraryDuplicatesResponse> =>
|
||||
apiClient.get(`${base}/duplicates`, { params: query, signal }).then((r) => r.data),
|
||||
dismiss: (a: string, b: string): Promise<SuccessResponse> =>
|
||||
apiClient.post(`${base}/duplicates/dismiss`, { a, b }).then((r) => r.data),
|
||||
merge: (leading: string, other: string): Promise<PlacesLibraryMergeResponse> =>
|
||||
apiClient.post(`${base}/merges`, { leading, other }).then((r) => r.data),
|
||||
undoMerge: (mergeId: number): Promise<SuccessResponse> =>
|
||||
apiClient.post(`${base}/merges/${mergeId}/undo`).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
// FE-API-PLACE-VISITS-001
|
||||
//
|
||||
// D7/PLC-10 to PLC-23: each read pins its verb, its path and its query; there is nothing to write.
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { placeVisitsApi } from './placeVisits';
|
||||
|
||||
let calls: Array<[string, string]> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
});
|
||||
|
||||
function record(data: object) {
|
||||
return ({ request }: { request: Request }) => {
|
||||
const url = new URL(request.url);
|
||||
calls.push([request.method, `${url.pathname}${url.search}`]);
|
||||
return HttpResponse.json(data);
|
||||
};
|
||||
}
|
||||
|
||||
describe('placeVisitsApi', () => {
|
||||
it('FE-API-PLACE-VISITS-001: reads the visits and the media at the routes the server serves', async () => {
|
||||
server.use(
|
||||
http.get('/api/place-visits', record({ visits: [], total: 0 })),
|
||||
http.get('/api/place-visits/place', record({ visits: [], visit_count: 0, last_visit: null })),
|
||||
http.get('/api/trips/4/place-visits/mine', record({ place_ids: [], places: [] })),
|
||||
http.get(
|
||||
'/api/addons/collections/library/places/trip/3/media',
|
||||
record({ images: [], journey_photos: [], files: [] })
|
||||
)
|
||||
);
|
||||
|
||||
expect(await placeVisitsApi.list({ trip_id: 4 })).toEqual({ visits: [], total: 0 });
|
||||
expect(await placeVisitsApi.forPlace('trip', 3)).toEqual({ visits: [], visit_count: 0, last_visit: null });
|
||||
expect(await placeVisitsApi.tripVisited(4)).toEqual({ place_ids: [], places: [] });
|
||||
expect(await placeVisitsApi.media('trip', 3)).toEqual({ images: [], journey_photos: [], files: [] });
|
||||
expect(Object.keys(placeVisitsApi).sort()).toEqual(['forPlace', 'list', 'media', 'tripVisited']);
|
||||
|
||||
expect(calls).toEqual([
|
||||
['GET', '/api/place-visits?trip_id=4'],
|
||||
['GET', '/api/place-visits/place?kind=trip&id=3'],
|
||||
['GET', '/api/trips/4/place-visits/mine'],
|
||||
['GET', '/api/addons/collections/library/places/trip/3/media'],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import type {
|
||||
PlaceMediaResponse,
|
||||
PlacesLibraryKind,
|
||||
PlaceVisitsForPlaceResponse,
|
||||
PlaceVisitsListQuery,
|
||||
PlaceVisitsListResponse,
|
||||
PlaceVisitTripVisitedResponse,
|
||||
} from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
/**
|
||||
* D7/PLC-10, PLC-19, PLC-20, PLC-23: the visits the server reads from the
|
||||
* trips (nothing to write: a visit comes from the trip's plan), the trip
|
||||
* places visited, and the photos and files of an entry of All places.
|
||||
*/
|
||||
export const placeVisitsApi = {
|
||||
list: (query: PlaceVisitsListQuery = {}, signal?: AbortSignal): Promise<PlaceVisitsListResponse> =>
|
||||
apiClient.get('/place-visits', { params: query, signal }).then((r) => r.data),
|
||||
forPlace: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceVisitsForPlaceResponse> =>
|
||||
apiClient.get('/place-visits/place', { params: { kind, id }, signal }).then((r) => r.data),
|
||||
tripVisited: (tripId: number, signal?: AbortSignal): Promise<PlaceVisitTripVisitedResponse> =>
|
||||
apiClient.get(`/trips/${tripId}/place-visits/mine`, { signal }).then((r) => r.data),
|
||||
media: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceMediaResponse> =>
|
||||
apiClient.get(`/addons/collections/library/places/${kind}/${id}/media`, { signal }).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
// FE-API-PLACES-LIBRARY-001 to FE-API-PLACES-LIBRARY-004
|
||||
//
|
||||
// PLC-07/PLC-08: each method pins its verb, its path and its query, and hands
|
||||
// back what the server answered.
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { placesLibraryApi } from './placesLibrary';
|
||||
|
||||
const BASE = '/api/addons/collections/library/places';
|
||||
const page = { entries: [], total: 0, counts: { all: 0, trip: 0, list: 0 }, next_cursor: null };
|
||||
|
||||
let calls: Array<{ path: string; query: Record<string, string> }> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
});
|
||||
|
||||
function record(data: object) {
|
||||
return ({ request }: { request: Request }) => {
|
||||
const url = new URL(request.url);
|
||||
calls.push({ path: url.pathname, query: Object.fromEntries(url.searchParams) });
|
||||
return HttpResponse.json(data);
|
||||
};
|
||||
}
|
||||
|
||||
describe('placesLibraryApi', () => {
|
||||
it('FE-API-PLACES-LIBRARY-001: lists a page with the filters as query parameters', async () => {
|
||||
server.use(http.get(BASE, record(page)));
|
||||
expect(await placesLibraryApi.list()).toEqual(page);
|
||||
expect(
|
||||
await placesLibraryApi.list({ q: 'cafe', kind: 'list', collection_id: 3, limit: 20, cursor: 'abc' })
|
||||
).toEqual(page);
|
||||
expect(calls).toEqual([
|
||||
{ path: BASE, query: {} },
|
||||
{ path: BASE, query: { q: 'cafe', kind: 'list', collection_id: '3', limit: '20', cursor: 'abc' } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-API-PLACES-LIBRARY-002: opens one entry by the trip place or the saved place it names', async () => {
|
||||
const answer = { entry: { key: 'trip:4' }, details: [] };
|
||||
server.use(http.get(`${BASE}/trip/4`, record(answer)), http.get(`${BASE}/list/9`, record(answer)));
|
||||
expect(await placesLibraryApi.detail('trip', 4)).toEqual(answer);
|
||||
expect(await placesLibraryApi.detail('list', 9)).toEqual(answer);
|
||||
expect(calls.map((call) => call.path)).toEqual([`${BASE}/trip/4`, `${BASE}/list/9`]);
|
||||
});
|
||||
|
||||
it('FE-API-PLACES-LIBRARY-003: sends a tag filter as its names joined by commas, a comma in a name escaped', async () => {
|
||||
server.use(http.get(BASE, record(page)));
|
||||
await placesLibraryApi.list({ tags: ['Coffee', 'Food, drinks'], q: 'x' });
|
||||
await placesLibraryApi.list({ tags: 'View' });
|
||||
await placesLibraryApi.list({ tags: [] });
|
||||
expect(calls.map((call) => call.query)).toEqual([{ q: 'x', tags: 'Coffee,Food\\, drinks' }, { tags: 'View' }, {}]);
|
||||
});
|
||||
|
||||
it('FE-API-PLACES-LIBRARY-004: votes by the entry key, PUT with the stars and DELETE with the key to take it back', async () => {
|
||||
const answer = { key: 'trip:4', rating: { average: 3, count: 1, mine: 3, votes: [] } };
|
||||
const sent: Array<{ method: string; query: Record<string, string>; body: unknown }> = [];
|
||||
const handle = async ({ request }: { request: Request }) => {
|
||||
const url = new URL(request.url);
|
||||
const body = request.method === 'PUT' ? await request.json() : null;
|
||||
sent.push({ method: request.method, query: Object.fromEntries(url.searchParams), body });
|
||||
return HttpResponse.json(answer);
|
||||
};
|
||||
server.use(http.put(`${BASE}/rating`, handle), http.delete(`${BASE}/rating`, handle));
|
||||
expect(await placesLibraryApi.rate('trip:4', 3)).toEqual(answer);
|
||||
expect(await placesLibraryApi.rate('trip:4', null)).toEqual(answer);
|
||||
expect(sent).toEqual([
|
||||
{ method: 'PUT', query: {}, body: { key: 'trip:4', rating: 3 } },
|
||||
{ method: 'DELETE', query: { key: 'trip:4' }, body: null },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
joinLibraryTagNames,
|
||||
type PlacesLibraryDetailResponse,
|
||||
type PlacesLibraryKind,
|
||||
type PlacesLibraryPageResponse,
|
||||
type PlacesLibraryQueryInput,
|
||||
type PlacesLibraryRateResponse,
|
||||
} from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
const base = '/addons/collections/library/places';
|
||||
|
||||
/**
|
||||
* The query as the server reads it: a tag filter (PLC-21) as its names joined by commas, a comma
|
||||
* inside a name escaped (`joinLibraryTagNames`), not `tags[]=`.
|
||||
*/
|
||||
function queryParams(query: PlacesLibraryQueryInput): Record<string, unknown> {
|
||||
const { tags, ...rest } = query;
|
||||
if (tags === undefined) return rest;
|
||||
const joined = Array.isArray(tags) ? joinLibraryTagNames(tags) : tags;
|
||||
return joined === '' ? rest : { ...rest, tags: joined };
|
||||
}
|
||||
|
||||
/** PLC-07/PLC-08 "All places": one page of entries, and one entry by the trip place or saved place it was opened from. */
|
||||
export const placesLibraryApi = {
|
||||
list: (query: PlacesLibraryQueryInput = {}, signal?: AbortSignal): Promise<PlacesLibraryPageResponse> =>
|
||||
apiClient.get(base, { params: queryParams(query), signal }).then((r) => r.data),
|
||||
detail: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlacesLibraryDetailResponse> =>
|
||||
apiClient.get(`${base}/${kind}/${id}`, { signal }).then((r) => r.data),
|
||||
/** The reader's vote on an entry, on every copy of it they may vote on; null takes it back. */
|
||||
rate: (key: string, rating: number | null): Promise<PlacesLibraryRateResponse> =>
|
||||
rating === null
|
||||
? apiClient.delete(`${base}/rating`, { params: { key } }).then((r) => r.data)
|
||||
: apiClient.put(`${base}/rating`, { key, rating }).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
// FE-API-TRIP-COLLECTIONS-001
|
||||
//
|
||||
// PLC-15/PLC-16: each method pins its verb, its path and its body.
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { tripCollectionsApi } from './tripCollections';
|
||||
|
||||
const links = { links: [], can_link: true };
|
||||
let calls: Array<[string, string, unknown]> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
});
|
||||
|
||||
function record(data: object) {
|
||||
return async ({ request }: { request: Request }) => {
|
||||
const text = request.method === 'POST' ? await request.text() : '';
|
||||
calls.push([request.method, new URL(request.url).pathname, text ? JSON.parse(text) : null]);
|
||||
return HttpResponse.json(data);
|
||||
};
|
||||
}
|
||||
|
||||
describe('tripCollectionsApi', () => {
|
||||
it('FE-API-TRIP-COLLECTIONS-001: lists, maps, links and unlinks the lists of a trip', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips/4/collections', record(links)),
|
||||
http.get('/api/trips/4/collections/places', record({ places: [] })),
|
||||
http.post('/api/trips/4/collections', record(links)),
|
||||
http.delete('/api/trips/4/collections/9', record(links))
|
||||
);
|
||||
expect(await tripCollectionsApi.list(4)).toEqual(links);
|
||||
expect(await tripCollectionsApi.layer(4)).toEqual({ places: [] });
|
||||
expect(await tripCollectionsApi.link(4, 9)).toEqual(links);
|
||||
expect(await tripCollectionsApi.unlink(4, 9)).toEqual(links);
|
||||
expect(calls).toEqual([
|
||||
['GET', '/api/trips/4/collections', null],
|
||||
['GET', '/api/trips/4/collections/places', null],
|
||||
['POST', '/api/trips/4/collections', { collection_id: 9 }],
|
||||
['DELETE', '/api/trips/4/collections/9', null],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { TripCollectionLayerResponse, TripCollectionLinksResponse } from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
/** PLC-15/PLC-16: the lists a trip draws on, and their saved places for the trip map. */
|
||||
export const tripCollectionsApi = {
|
||||
list: (tripId: number, signal?: AbortSignal): Promise<TripCollectionLinksResponse> =>
|
||||
apiClient.get(`/trips/${tripId}/collections`, { signal }).then((r) => r.data),
|
||||
layer: (tripId: number, signal?: AbortSignal): Promise<TripCollectionLayerResponse> =>
|
||||
apiClient.get(`/trips/${tripId}/collections/places`, { signal }).then((r) => r.data),
|
||||
link: (tripId: number, collectionId: number): Promise<TripCollectionLinksResponse> =>
|
||||
apiClient.post(`/trips/${tripId}/collections`, { collection_id: collectionId }).then((r) => r.data),
|
||||
unlink: (tripId: number, collectionId: number): Promise<TripCollectionLinksResponse> =>
|
||||
apiClient.delete(`/trips/${tripId}/collections/${collectionId}`).then((r) => r.data),
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
// vi.unmock must run before the module is imported (tests/setup.ts mocks it globally)
|
||||
vi.unmock('./websocket')
|
||||
|
||||
// FE-WSCORE-001 to FE-WSCORE-016
|
||||
// FE-WSCORE-001 to FE-WSCORE-018
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { server } from '../../tests/helpers/msw/server'
|
||||
@@ -135,18 +135,52 @@ describe('websocket > reconnect refetch hook', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('FE-WSCORE-005: with no joined trips onopen sends nothing and skips the refetch', async () => {
|
||||
it('FE-WSCORE-005: with no joined trips onopen sends only its presence and skips the refetch', async () => {
|
||||
const refetch = vi.fn((_tripId: string) => {})
|
||||
setRefetchCallback(refetch)
|
||||
|
||||
const sock = await openSocket()
|
||||
sock.onopen!()
|
||||
|
||||
expect(sock.send).not.toHaveBeenCalled()
|
||||
expect(sock.send.mock.calls.map(([raw]) => JSON.parse(raw).type)).toEqual(['presence'])
|
||||
expect(refetch).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('websocket > presence', () => {
|
||||
function presences(sock: MockWebSocket): unknown[] {
|
||||
return sock.send.mock.calls.map(([raw]) => JSON.parse(raw)).filter(m => m.type === 'presence').map(m => m.visible)
|
||||
}
|
||||
|
||||
function setVisibility(state: 'visible' | 'hidden'): void {
|
||||
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state })
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
delete (document as { visibilityState?: unknown }).visibilityState
|
||||
})
|
||||
|
||||
it('FE-WSCORE-017: tells the server on open and on every change whether the tab is in front', async () => {
|
||||
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' })
|
||||
const sock = await openSocket()
|
||||
sock.onopen?.()
|
||||
setVisibility('hidden')
|
||||
setVisibility('visible')
|
||||
|
||||
expect(presences(sock)).toEqual([true, false, true])
|
||||
})
|
||||
|
||||
it('FE-WSCORE-018: stops telling it once logged out', async () => {
|
||||
const sock = await openSocket()
|
||||
sock.onopen?.()
|
||||
disconnect()
|
||||
setVisibility('hidden')
|
||||
|
||||
expect(presences(sock)).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('websocket > connection lifecycle', () => {
|
||||
it('FE-WSCORE-006: connect() is a no-op while a socket is still CONNECTING', async () => {
|
||||
const sock = await openSocket()
|
||||
|
||||
@@ -129,6 +129,7 @@ async function connectInternal(_isReconnect = false): Promise<void> {
|
||||
|
||||
socket.onopen = () => {
|
||||
reconnectDelay = 1000
|
||||
sendPresence()
|
||||
activeBooks.forEach(journeyId => {
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: 'book:join', journeyId }))
|
||||
@@ -173,6 +174,17 @@ async function connectInternal(_isReconnect = false): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the server whether this tab is in front. Online, in the admin's user
|
||||
* list, means a tab someone is looking at, not one left open in the
|
||||
* background, and while one is in front the server keeps the account's
|
||||
* last activity current.
|
||||
*/
|
||||
function sendPresence(): void {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN || typeof document === 'undefined') return
|
||||
socket.send(JSON.stringify({ type: 'presence', visible: document.visibilityState === 'visible' }))
|
||||
}
|
||||
|
||||
/**
|
||||
* The network came back or the tab became visible: a socket waiting out its
|
||||
* backoff (up to 30 s) reconnects now. Does nothing while logged out or while
|
||||
@@ -186,6 +198,7 @@ export function reconnectNow(): void {
|
||||
|
||||
export function connect(): void {
|
||||
shouldReconnect = true
|
||||
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', sendPresence)
|
||||
reconnectDelay = 1000
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer)
|
||||
@@ -196,6 +209,7 @@ export function connect(): void {
|
||||
|
||||
export function disconnect(): void {
|
||||
shouldReconnect = false
|
||||
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', sendPresence)
|
||||
generation++
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer)
|
||||
|
||||
@@ -50,6 +50,12 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
|
||||
// hooks/useTripAddonsSync) puts the trip's list into the store and the device's copy, so the
|
||||
// tabs and panels a trip switched off disappear for every member at once.
|
||||
'tripAddons:changed',
|
||||
// Linked lists (PLC-15/PLC-16): store/tripCollectionsStore (watchTripCollections) reads the
|
||||
// trip's linked lists and map layer again; content-free because each member's answer differs.
|
||||
'tripCollections:changed',
|
||||
// Place activities (PLC-18): store/placeActivitiesStore (watchPlaceActivities) reads the
|
||||
// bookings and tours of the held trip place, and the All places entries it is an origin of, again.
|
||||
'placeActivities:changed',
|
||||
// components/Roadtrip/useDayBoundaries reloads the shared boundaries.
|
||||
'roadtripBoundary:changed',
|
||||
// In-app notifications: hooks/useInAppNotificationListener, which also keeps
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import AddonManager from './AddonManager';
|
||||
|
||||
// FE-ATLAS2-REST-040 to 042: the Atlas ranking row under the Atlas addon on the desktop admin page.
|
||||
|
||||
const RANKING = 'Ranking and profiles';
|
||||
|
||||
function atlasAddon(enabled: boolean) {
|
||||
return { id: 'atlas', name: 'Atlas', description: 'World map', icon: 'Globe', type: 'global', enabled };
|
||||
}
|
||||
|
||||
function isOn(toggle: HTMLElement): boolean {
|
||||
return toggle.getAttribute('aria-pressed') === 'true';
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })),
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useSettingsStore, { settings: { dark_mode: false } });
|
||||
useAuthStore.setState({ atlasCompareEnabled: true });
|
||||
vi.spyOn(useAddonStore.getState(), 'loadAddons').mockResolvedValue(undefined);
|
||||
server.use(
|
||||
http.get('/api/admin/tours-wanderer', () => HttpResponse.json({ enabled: false })),
|
||||
http.get('/api/admin/tours-hiking-map', () => HttpResponse.json({ enabled: false })),
|
||||
http.get('/api/admin/tours-cycle-map', () => HttpResponse.json({ enabled: false })),
|
||||
http.get('/api/admin/tours-ski-routing', () => HttpResponse.json({ enabled: false }))
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('AddonManager: Atlas ranking', () => {
|
||||
it('FE-ATLAS2-REST-040: an enabled Atlas shows the ranking row, on as the app config says', async () => {
|
||||
server.use(http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(true)] })));
|
||||
render(<AddonManager />);
|
||||
const toggle = await screen.findByRole('button', { name: RANKING });
|
||||
expect(isOn(toggle)).toBe(true);
|
||||
expect(screen.getByText(RANKING)).toHaveAttribute('title', expect.stringContaining('Atlas ranking'));
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-REST-041: the row stays away while Atlas itself is off', async () => {
|
||||
server.use(http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(false)] })));
|
||||
render(<AddonManager />);
|
||||
await screen.findByRole('button', { name: 'Atlas' });
|
||||
expect(screen.queryByRole('button', { name: RANKING })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-REST-042: flipping the row saves atlas_compare_enabled and shows it off', async () => {
|
||||
const user = userEvent.setup();
|
||||
const bodies: unknown[] = [];
|
||||
server.use(
|
||||
http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(true)] })),
|
||||
http.put('/api/auth/app-settings', async ({ request }) => {
|
||||
bodies.push(await request.json());
|
||||
return HttpResponse.json({ success: true });
|
||||
})
|
||||
);
|
||||
render(
|
||||
<>
|
||||
<ToastContainer />
|
||||
<AddonManager />
|
||||
</>
|
||||
);
|
||||
await user.click(await screen.findByRole('button', { name: RANKING }));
|
||||
await screen.findByText('Addon updated');
|
||||
expect(bodies).toEqual([{ atlas_compare_enabled: false }]);
|
||||
await waitFor(() => expect(isOn(screen.getByRole('button', { name: RANKING }))).toBe(false));
|
||||
expect(useAuthStore.getState().atlasCompareEnabled).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { adminApi, authApi } from '../../../api/client';
|
||||
import { cycleMapAdminApi, hikingMapAdminApi, skiRoutingAdminApi } from '../../../api/tourBaseMaps';
|
||||
import { wandererAdminApi } from '../../../api/wanderer';
|
||||
import { useAddonStore } from '../../../store/addonStore';
|
||||
import { useAuthStore } from '../../../store/authStore';
|
||||
import { useAddonManager } from './useAddonManager';
|
||||
|
||||
// FE-ATLAS2-REST-030 to 032: the Atlas ranking switch the admin flips under the Atlas addon.
|
||||
|
||||
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
|
||||
vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
|
||||
vi.mock('../../../i18n', () => ({ useTranslation: () => ({ t: (k: string) => k }) }));
|
||||
|
||||
let loadAddons: ReturnType<typeof vi.fn<() => Promise<void>>>;
|
||||
|
||||
beforeEach(() => {
|
||||
toast.success.mockReset();
|
||||
toast.error.mockReset();
|
||||
loadAddons = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
|
||||
useAddonStore.setState({ loadAddons });
|
||||
useAuthStore.setState({ atlasCompareEnabled: true });
|
||||
vi.spyOn(adminApi, 'addons').mockResolvedValue({ addons: [] });
|
||||
vi.spyOn(wandererAdminApi, 'get').mockResolvedValue({ enabled: false });
|
||||
vi.spyOn(hikingMapAdminApi, 'get').mockResolvedValue({ enabled: false });
|
||||
vi.spyOn(cycleMapAdminApi, 'get').mockResolvedValue({ enabled: false });
|
||||
vi.spyOn(skiRoutingAdminApi, 'get').mockResolvedValue({ enabled: false });
|
||||
});
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
async function loaded() {
|
||||
const hook = renderHook(() => useAddonManager());
|
||||
await waitFor(() => expect(hook.result.current.loading).toBe(false));
|
||||
return hook;
|
||||
}
|
||||
|
||||
describe('useAddonManager: Atlas ranking switch', () => {
|
||||
it('FE-ATLAS2-REST-030: reads the switch from the app config the auth store holds', async () => {
|
||||
useAuthStore.setState({ atlasCompareEnabled: false });
|
||||
const { result } = await loaded();
|
||||
expect(result.current.atlasCompare).toBe(false);
|
||||
act(() => {
|
||||
useAuthStore.setState({ atlasCompareEnabled: true });
|
||||
});
|
||||
expect(result.current.atlasCompare).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-REST-031: a flip turns it off at once, saves the app setting, refreshes the addons and toasts', async () => {
|
||||
const save = vi.spyOn(authApi, 'updateAppSettings').mockResolvedValue({});
|
||||
const { result } = await loaded();
|
||||
await act(() => result.current.toggleAtlasCompare());
|
||||
expect(save).toHaveBeenCalledWith({ atlas_compare_enabled: false });
|
||||
expect(useAuthStore.getState().atlasCompareEnabled).toBe(false);
|
||||
expect(result.current.atlasCompare).toBe(false);
|
||||
expect(loadAddons).toHaveBeenCalledTimes(1);
|
||||
expect(toast.success).toHaveBeenCalledWith('admin.addons.toast.updated');
|
||||
|
||||
// And on again from off.
|
||||
await act(() => result.current.toggleAtlasCompare());
|
||||
expect(save).toHaveBeenLastCalledWith({ atlas_compare_enabled: true });
|
||||
expect(useAuthStore.getState().atlasCompareEnabled).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-REST-032: a failed save puts the switch back and says so, without refreshing', async () => {
|
||||
vi.spyOn(authApi, 'updateAppSettings').mockRejectedValue(new Error('down'));
|
||||
const { result } = await loaded();
|
||||
await act(() => result.current.toggleAtlasCompare());
|
||||
expect(useAuthStore.getState().atlasCompareEnabled).toBe(true);
|
||||
expect(result.current.atlasCompare).toBe(true);
|
||||
expect(toast.error).toHaveBeenCalledWith('admin.addons.toast.error');
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
expect(loadAddons).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -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,65 @@ 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));
|
||||
});
|
||||
|
||||
it('FE-COMP-DEFAULTSETTINGS-007: a MapLibre keyword default survives loading, a switch, a pick and a typed commit', async () => {
|
||||
const update = stub({
|
||||
map_provider: 'maplibre-gl',
|
||||
maplibre_style: 'trek:template',
|
||||
mapbox_style: 'mapbox://styles/me/x',
|
||||
});
|
||||
const { result } = await loaded();
|
||||
expect(result.current.mapboxStyle).toBe('trek:template');
|
||||
// The picker names both keywords after the OpenFreeMap styles.
|
||||
expect(result.current.glStylePresets.slice(-2)).toEqual([
|
||||
{ name: 'settings.mapStyleFollowTheme', url: 'trek:ofm-auto', tags: ['OpenFreeMap'] },
|
||||
{ name: 'settings.mapStyleTemplate', url: 'trek:template' },
|
||||
]);
|
||||
|
||||
act(() => result.current.commitStyle());
|
||||
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'trek:template' }));
|
||||
|
||||
act(() => result.current.saveMapProvider('mapbox-gl'));
|
||||
await waitFor(() =>
|
||||
expect(update).toHaveBeenLastCalledWith({ map_provider: 'mapbox-gl', mapbox_style: 'mapbox://styles/me/x' })
|
||||
);
|
||||
act(() => result.current.saveMapProvider('maplibre-gl'));
|
||||
await waitFor(() =>
|
||||
expect(update).toHaveBeenLastCalledWith({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' })
|
||||
);
|
||||
expect(result.current.mapboxStyle).toBe('trek:template');
|
||||
|
||||
act(() => result.current.pickStylePreset('trek:ofm-auto'));
|
||||
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'trek:ofm-auto' }));
|
||||
});
|
||||
|
||||
it('FE-COMP-DEFAULTSETTINGS-008: a keyword typed for Mapbox is not kept, Mapbox draws neither', async () => {
|
||||
const update = stub({ map_provider: 'mapbox-gl', mapbox_style: 'trek:template' });
|
||||
const { result } = await loaded();
|
||||
expect(result.current.mapboxStyle).toBe(MAPBOX_DEFAULT_STYLE);
|
||||
expect(result.current.glStylePresets.map((p) => p.url)).not.toContain('trek:template');
|
||||
act(() => result.current.commitStyle());
|
||||
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ mapbox_style: MAPBOX_DEFAULT_STYLE }));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
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';
|
||||
import type { DateFormat, DistanceUnit, Place, WeekStart } from '../../types';
|
||||
import { normalizeTileUrl } from '../../utils/tileUrl';
|
||||
import {
|
||||
defaultStyleForProvider,
|
||||
getStylePresets,
|
||||
normalizeStyleForProvider,
|
||||
styleSettingKey,
|
||||
} from '../Map/glProviders';
|
||||
import { defaultStyleForProvider, styleSettingKey } from '../Map/glProviders';
|
||||
import {
|
||||
type MapProvider,
|
||||
glStylePresetsFor,
|
||||
mapboxOffered,
|
||||
mapPresetsFor,
|
||||
normalizeGlSelection,
|
||||
normalizeProvider,
|
||||
styleForProvider,
|
||||
} from '../Settings/mapSettingsModel';
|
||||
@@ -87,32 +85,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;
|
||||
|
||||
@@ -120,7 +124,8 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
|
||||
const [mapPreviewPlaces] = useState((): Place[] => [adminPreviewPlace(previewCreatedAt())]);
|
||||
|
||||
const mapProvider = normalizeProvider(defaults.map_provider);
|
||||
const glStylePresets = mapProvider === 'leaflet' ? [] : getStylePresets(mapProvider);
|
||||
// MapLibre also offers its keywords: a default that follows the colour scheme, or the template above.
|
||||
const glStylePresets = mapProvider === 'leaflet' ? [] : glStylePresetsFor(mapProvider, t);
|
||||
const styleKey: keyof Defaults = mapProvider === 'maplibre-gl' ? 'maplibre_style' : 'mapbox_style';
|
||||
|
||||
const saveMapProvider = (nextProvider: MapProvider) => {
|
||||
@@ -151,11 +156,11 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
|
||||
}
|
||||
};
|
||||
|
||||
/** A typed style is normalized for the provider before it is saved. */
|
||||
/** A typed style is normalized for the provider before it is saved; a MapLibre keyword stays. */
|
||||
const commitStyle = () => {
|
||||
// The style input never renders for leaflet; this only narrows the provider type.
|
||||
if (mapProvider === 'leaflet') return;
|
||||
const nextStyle = normalizeStyleForProvider(mapProvider, mapboxStyle);
|
||||
const nextStyle = normalizeGlSelection(mapProvider, mapboxStyle);
|
||||
setMapboxStyle(nextStyle);
|
||||
void save({ [styleKey]: nextStyle });
|
||||
};
|
||||
|
||||
@@ -50,7 +50,7 @@ describe('AssistantAskButton', () => {
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
renderAt('/collections/3');
|
||||
renderAt('/places/3');
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -54,7 +54,7 @@ describe('collection answer cards', () => {
|
||||
expect(within(card).getByText('Idea')).toBeInTheDocument();
|
||||
expect(within(card).getByText('3')).toBeInTheDocument();
|
||||
fireEvent.click(within(card).getByRole('button', { name: /Open list/ }));
|
||||
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12' });
|
||||
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12' });
|
||||
});
|
||||
|
||||
it('FE-AI-COLL-040: the places to revisit have a pill of their own in the head, in the visited tone (#2567)', () => {
|
||||
@@ -86,7 +86,7 @@ describe('collection answer cards', () => {
|
||||
expect(screen.getByText('Spot 4')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Spot 5')).toBeNull();
|
||||
fireEvent.click(screen.getByRole('button', { name: '7 more in this list' }));
|
||||
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12' });
|
||||
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12' });
|
||||
});
|
||||
|
||||
it('FE-AI-COLL-013: a roomy chat shows eight rows', () => {
|
||||
@@ -144,7 +144,7 @@ describe('collection answer cards', () => {
|
||||
expect(screen.queryByText('Paris food')).toBeNull();
|
||||
expect(screen.getByText('Invite from Maya')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: /Rome/ }));
|
||||
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/40' });
|
||||
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/40' });
|
||||
});
|
||||
|
||||
it('FE-AI-COLL-018: where a place is saved reads as its lists with its status in each', () => {
|
||||
|
||||
@@ -94,7 +94,7 @@ describe('collection change cards', () => {
|
||||
const view = draw([applied(pending('save_place_to_collection', 'Septime', card), 'collection_place', [77])]);
|
||||
expect(screen.queryByRole('button', { name: 'Show on map' })).toBeNull();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Open in Collections' }));
|
||||
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12?place=77' });
|
||||
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12?place=77' });
|
||||
});
|
||||
|
||||
it('FE-AI-COLL-023: a save the place matched already says where it is saved', () => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
TrekCard,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { placesPath } from '../../../../utils/placesRoutes';
|
||||
import type { EntityTarget } from '../cardTypes';
|
||||
|
||||
/**
|
||||
@@ -26,12 +27,12 @@ export const MAX_FACTS = 4;
|
||||
|
||||
/** Where a list opens in Collections. */
|
||||
export function listTarget(listId: number | null): EntityTarget {
|
||||
return { kind: 'page', path: listId === null ? '/collections' : `/collections/${listId}` };
|
||||
return { kind: 'page', path: placesPath(listId === null ? 'saved' : listId) };
|
||||
}
|
||||
|
||||
/** Where a saved place opens: its list, with the place selected. */
|
||||
function placeTarget(listId: number, placeId: number | null): EntityTarget {
|
||||
const path = `/collections/${listId}`;
|
||||
const path = placesPath(listId);
|
||||
return { kind: 'page', path: placeId === null ? path : `${path}?place=${placeId}` };
|
||||
}
|
||||
|
||||
|
||||
@@ -62,9 +62,9 @@ describe('collection look', () => {
|
||||
it('FE-AI-COLL-002: an applied list opens in Collections, unless the change deleted it or declined its invite', () => {
|
||||
const look = ENTITY_LOOK.collection;
|
||||
expect(look.openLabelKey).toBe('assistant.card.collection.openList');
|
||||
expect(look.open?.(applied('collection', [12]), null)).toEqual({ kind: 'page', path: '/collections/12' });
|
||||
expect(look.open?.(applied('collection', [12]), null)).toEqual({ kind: 'page', path: '/places/12' });
|
||||
const card = listsCard({ lists: [listRow({ id: 13 })] });
|
||||
expect(look.open?.(applied('collection', []), card)).toEqual({ kind: 'page', path: '/collections/13' });
|
||||
expect(look.open?.(applied('collection', []), card)).toEqual({ kind: 'page', path: '/places/13' });
|
||||
for (const change of ['remove', 'decline'] as const) {
|
||||
expect(look.open?.(applied('collection', [12]), listsCard({ lists: [listRow({ change })] }))).toBeNull();
|
||||
}
|
||||
@@ -76,10 +76,10 @@ describe('collection look', () => {
|
||||
const card = placesCard();
|
||||
expect(look.open?.(applied('collection_place', [34]), card)).toEqual({
|
||||
kind: 'page',
|
||||
path: '/collections/12?place=34',
|
||||
path: '/places/12?place=34',
|
||||
});
|
||||
const removed = placesCard({ places: [savedPlace({ delta: emptyDelta({ removed: true }) })] });
|
||||
expect(look.open?.(applied('collection_place', [34]), removed)).toEqual({ kind: 'page', path: '/collections/12' });
|
||||
expect(look.open?.(applied('collection_place', [34]), removed)).toEqual({ kind: 'page', path: '/places/12' });
|
||||
expect(look.open?.(applied('collection_place', [34]), null)).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// FE-ATLAS2-PAINT-301 to FE-ATLAS2-PAINT-318: the tours page figures of the Atlas hub
|
||||
// and the readings and labels the tour activity views share.
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import type { TourActivityStatsResponse, TourActivitySum, TourActivitySummary, TourActivityTotals } from '@trek/shared';
|
||||
import { Bike, Layers, Mountain, Route } from 'lucide-react';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import {
|
||||
distanceReading,
|
||||
heightReading,
|
||||
partialHint,
|
||||
periodLabel,
|
||||
typeIcon,
|
||||
typeLabel,
|
||||
useDistanceUnit,
|
||||
} from './tourActivityReading';
|
||||
import { tourHubFigures } from './tourHubFigures';
|
||||
|
||||
const echoT = (key: string, params?: Record<string, unknown>): string =>
|
||||
params ? `${key}:${JSON.stringify(params)}` : key;
|
||||
|
||||
function sum(value: number | null, known = 1, of = known): TourActivitySum {
|
||||
return { value, known, of };
|
||||
}
|
||||
|
||||
function totals(over: Partial<TourActivityTotals> = {}): TourActivityTotals {
|
||||
return {
|
||||
count: 3,
|
||||
distanceKm: sum(42.5, 3),
|
||||
ascentM: sum(1200, 3),
|
||||
descentM: sum(1100, 3),
|
||||
byBasis: { plan: 2, track: 1 },
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function summary(over: Partial<TourActivitySummary> = {}): TourActivitySummary {
|
||||
return { totals: totals(), types: [], done: [], upcoming: 0, ...over };
|
||||
}
|
||||
|
||||
const initialSettings = useSettingsStore.getState();
|
||||
|
||||
afterEach(() => {
|
||||
useSettingsStore.setState(initialSettings, true);
|
||||
});
|
||||
|
||||
describe('tourHubFigures', () => {
|
||||
it('FE-ATLAS2-PAINT-301: leads with the distance split into number and unit, with the climbs beside it', () => {
|
||||
const figures = tourHubFigures(summary(), null, 'metric');
|
||||
expect(figures.hero).toEqual({ value: '42.5', unit: 'km' });
|
||||
expect(figures.ascent).toEqual({ text: '1200 m', partial: false });
|
||||
expect(figures.descent).toEqual({ text: '1100 m', partial: false });
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-302: marks a distance some tours lack as at least that much', () => {
|
||||
const figures = tourHubFigures(summary({ totals: totals({ distanceKm: sum(10, 1, 3) }) }), null, 'metric');
|
||||
expect(figures.hero).toEqual({ value: '≥ 10', unit: 'km' });
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-303: leads with the tour count when no tour knows its distance', () => {
|
||||
const figures = tourHubFigures(
|
||||
summary({ totals: totals({ count: 7, distanceKm: sum(null, 0, 7), ascentM: sum(null, 0, 7) }) }),
|
||||
null,
|
||||
'metric'
|
||||
);
|
||||
expect(figures.hero).toEqual({ value: '7', unit: '' });
|
||||
expect(figures.ascent).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-304: reads in miles and feet for imperial', () => {
|
||||
const figures = tourHubFigures(summary(), null, 'imperial');
|
||||
expect(figures.hero).toEqual({ value: '26.4', unit: 'mi' });
|
||||
expect(figures.ascent?.text).toBe('3937 ft');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-305: scales the types to the longest one', () => {
|
||||
const types = [
|
||||
{ ...totals({ distanceKm: sum(30) }), type: 'hike' as const },
|
||||
{ ...totals({ distanceKm: sum(120) }), type: 'bike' as const },
|
||||
{ ...totals({ distanceKm: sum(null, 0, 1) }), type: 'kayak' as const },
|
||||
];
|
||||
const figures = tourHubFigures(summary({ types }), null, 'metric');
|
||||
expect(figures.types).toBe(types);
|
||||
expect(figures.maxKm).toBe(120);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-306: never scales against zero, with no types or none with a distance', () => {
|
||||
expect(tourHubFigures(summary(), null, 'metric').maxKm).toBe(1e-9);
|
||||
const types = [{ ...totals({ distanceKm: sum(null, 0, 2) }), type: 'run' as const }];
|
||||
expect(tourHubFigures(summary({ types }), null, 'metric').maxKm).toBe(1e-9);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-307: says which tours are left out of the sums, none before the data loads', () => {
|
||||
expect(tourHubFigures(summary(), null, 'metric').uncounted).toEqual({ unassigned: 0, undated: 0 });
|
||||
const data: TourActivityStatsResponse = { entries: [], uncounted: { unassigned: 2, undated: 1 } };
|
||||
expect(tourHubFigures(summary(), data, 'metric').uncounted).toEqual({ unassigned: 2, undated: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('tourActivityReading', () => {
|
||||
it('FE-ATLAS2-PAINT-308: reads the distance unit from the user settings', () => {
|
||||
useSettingsStore.setState({ settings: { ...initialSettings.settings, distance_unit: 'imperial' } });
|
||||
const { result } = renderHook(() => useDistanceUnit());
|
||||
expect(result.current).toBe('imperial');
|
||||
act(() => {
|
||||
useSettingsStore.setState({ settings: { ...initialSettings.settings, distance_unit: 'metric' } });
|
||||
});
|
||||
expect(result.current).toBe('metric');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-309: falls back to metric when the setting is missing', () => {
|
||||
useSettingsStore.setState({ settings: { ...initialSettings.settings, distance_unit: undefined } });
|
||||
const { result } = renderHook(() => useDistanceUnit());
|
||||
expect(result.current).toBe('metric');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-310: names every type at once apart from a single type', () => {
|
||||
expect(typeLabel('all', echoT)).toBe('tours.stats.allTypes');
|
||||
expect(typeLabel('hike', echoT)).toBe('tourTypes.hike');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-311: draws every type at once as a stack and a single type with its own icon', () => {
|
||||
expect(typeIcon('all')).toBe(Layers);
|
||||
expect(typeIcon('bike')).toBe(Bike);
|
||||
expect(typeIcon('hike')).toBe(Mountain);
|
||||
expect(typeIcon('food')).toBe(Route);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-312: reads a distance, short ones in metres, and none without a value', () => {
|
||||
expect(distanceReading({ distanceKm: sum(0.3) }, 'metric')).toEqual({ text: '300 m', partial: false });
|
||||
expect(distanceReading({ distanceKm: sum(5, 2, 4) }, 'metric')).toEqual({ text: '≥ 5 km', partial: true });
|
||||
expect(distanceReading({ distanceKm: sum(null, 0, 4) }, 'metric')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-313: reads a height sum in metres or feet', () => {
|
||||
expect(heightReading(sum(500), 'metric')).toEqual({ text: '500 m', partial: false });
|
||||
expect(heightReading(sum(500, 1, 2), 'imperial')).toEqual({ text: '≥ 1640 ft', partial: true });
|
||||
expect(heightReading(sum(null, 0, 2), 'imperial')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-314: explains a short sum with how many tours know their value', () => {
|
||||
expect(partialHint(sum(5, 2, 4), echoT)).toBe('tours.scope.partialBody:{"known":2,"of":4}');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-315: names each period of the filter, an earlier year by its number', () => {
|
||||
expect(periodLabel('all', echoT)).toBe('tours.stats.period.all');
|
||||
expect(periodLabel('thisYear', echoT)).toBe('tours.stats.period.thisYear');
|
||||
expect(periodLabel('last12', echoT)).toBe('tours.stats.period.last12');
|
||||
expect(periodLabel('year:2023', echoT)).toBe('2023');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { TourActivityStatsResponse, TourActivitySummary } from '@trek/shared';
|
||||
import type { DistanceUnit } from '../../../types';
|
||||
import { distanceReading, heightReading } from './tourActivityReading';
|
||||
import { splitMeasure } from './tourActivityStatsModel';
|
||||
|
||||
/**
|
||||
* What the tours page of the Atlas hub shows above its lists, for the desktop
|
||||
* and the phone view alike: the headline distance (or the tour count when no
|
||||
* distance is known), the climbs, the types scaled to the longest, and the
|
||||
* tours left out of the sums.
|
||||
*/
|
||||
export function tourHubFigures(
|
||||
summary: TourActivitySummary,
|
||||
data: TourActivityStatsResponse | null,
|
||||
unit: DistanceUnit
|
||||
) {
|
||||
const totals = summary.totals;
|
||||
const distance = distanceReading(totals, unit);
|
||||
return {
|
||||
hero: distance ? splitMeasure(distance.text) : { value: String(totals.count), unit: '' },
|
||||
ascent: heightReading(totals.ascentM, unit),
|
||||
descent: heightReading(totals.descentM, unit),
|
||||
types: summary.types,
|
||||
maxKm: Math.max(1e-9, ...summary.types.map((x) => x.distanceKm.value ?? 0)),
|
||||
uncounted: data?.uncounted ?? { unassigned: 0, undated: 0 },
|
||||
};
|
||||
}
|
||||
@@ -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,278 @@
|
||||
// FE-ATLAS2-RENDER-200 to FE-ATLAS2-RENDER-214: the AtlasGlobe component wiring a (faked) GlobeEngine
|
||||
// to its props: lifecycle, callbacks, painting, theme, inset and the label overlay.
|
||||
import { act, render } from '@testing-library/react';
|
||||
import { createRef, type ComponentProps } from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { AtlasMeshManifest, GlobeEngine, GlobeEngineOptions, GlobeHit } from './GlobeEngine';
|
||||
import type { GlobeTheme } from './GlobeRenderer';
|
||||
|
||||
const h = vi.hoisted(() => {
|
||||
const state = { engines: [] as FakeEngine[], failNext: null as unknown };
|
||||
class FakeEngine {
|
||||
opts: GlobeEngineOptions;
|
||||
manifest: AtlasMeshManifest | null = null;
|
||||
onRegionLoaded: ((a2: string) => void) | null = null;
|
||||
themes: GlobeTheme[] = [];
|
||||
insets: number[] = [];
|
||||
kicks = 0;
|
||||
disposed = false;
|
||||
constructor(opts: GlobeEngineOptions) {
|
||||
if (state.failNext !== null) {
|
||||
const err = state.failNext;
|
||||
state.failNext = null;
|
||||
throw err;
|
||||
}
|
||||
this.opts = opts;
|
||||
state.engines.push(this);
|
||||
}
|
||||
setTheme(theme: GlobeTheme): void {
|
||||
this.themes.push(theme);
|
||||
}
|
||||
setInsetBottom(px: number): void {
|
||||
this.insets.push(px);
|
||||
}
|
||||
kick(): void {
|
||||
this.kicks++;
|
||||
}
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
}
|
||||
}
|
||||
const placeLabels = vi.fn(
|
||||
(
|
||||
_host: HTMLDivElement,
|
||||
_pool: unknown[],
|
||||
_engine: GlobeEngine,
|
||||
_labelFor: (a2: string) => string | null,
|
||||
_labelRegionsOf?: (a2: string) => boolean
|
||||
) => undefined
|
||||
);
|
||||
return { FakeEngine, state, placeLabels };
|
||||
});
|
||||
|
||||
vi.mock('./GlobeEngine', () => ({ GlobeEngine: h.FakeEngine }));
|
||||
vi.mock('./globeLabels', () => ({ placeLabels: h.placeLabels }));
|
||||
|
||||
import AtlasGlobe, { type AtlasGlobeHandle } from './AtlasGlobe';
|
||||
|
||||
type Props = ComponentProps<typeof AtlasGlobe>;
|
||||
|
||||
const MANIFEST = {
|
||||
version: 1,
|
||||
lods: ['110m'],
|
||||
regionLods: [],
|
||||
world: {},
|
||||
countries: [],
|
||||
} as unknown as AtlasMeshManifest;
|
||||
|
||||
function baseProps(over: Partial<Props> = {}): Props {
|
||||
return {
|
||||
fetchJson: vi.fn(async (_path: string) => ({})),
|
||||
dark: true,
|
||||
labelFor: (a2: string) => a2,
|
||||
paint: vi.fn(),
|
||||
paintKey: 1,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function engine(i = 0): InstanceType<typeof h.FakeEngine> {
|
||||
const e = h.state.engines[i];
|
||||
if (!e) throw new Error(`no engine ${i}`);
|
||||
return e;
|
||||
}
|
||||
|
||||
/** The fake as the GlobeEngine the callbacks hand around. */
|
||||
function asEngine(e: InstanceType<typeof h.FakeEngine>): GlobeEngine {
|
||||
return e as unknown as GlobeEngine;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
h.state.engines.length = 0;
|
||||
h.state.failNext = null;
|
||||
h.placeLabels.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('AtlasGlobe', () => {
|
||||
it('FE-ATLAS2-RENDER-200: renders the canvas as an image named Atlas with a hidden label layer', () => {
|
||||
const { container, getByRole } = render(<AtlasGlobe {...baseProps({ className: 'globe-host' })} />);
|
||||
const canvas = getByRole('img', { name: 'Atlas' });
|
||||
expect(canvas.tagName).toBe('CANVAS');
|
||||
expect(container.firstElementChild).toHaveClass('globe-host');
|
||||
expect(container.querySelector('[aria-hidden="true"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-201: creates one engine on the canvas with the theme for the mode', () => {
|
||||
const { getByRole } = render(<AtlasGlobe {...baseProps({ dark: false })} />);
|
||||
expect(h.state.engines).toHaveLength(1);
|
||||
expect(engine().opts.canvas).toBe(getByRole('img', { name: 'Atlas' }));
|
||||
expect(engine().opts.theme.dark).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-202: exposes the engine through the ref and drops it on unmount', () => {
|
||||
const ref = createRef<AtlasGlobeHandle>();
|
||||
const { unmount } = render(<AtlasGlobe ref={ref} {...baseProps()} />);
|
||||
const e = engine();
|
||||
expect(ref.current?.engine).toBe(e);
|
||||
unmount();
|
||||
expect(e.disposed).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-203: reports an engine that cannot start to onError and keeps no engine', () => {
|
||||
const onError = vi.fn();
|
||||
const err = new Error('WebGL2 unavailable');
|
||||
h.state.failNext = err;
|
||||
const ref = createRef<AtlasGlobeHandle>();
|
||||
const { unmount } = render(<AtlasGlobe ref={ref} {...baseProps({ onError })} />);
|
||||
expect(onError).toHaveBeenCalledWith(err);
|
||||
expect(ref.current?.engine).toBeNull();
|
||||
expect(() => unmount()).not.toThrow();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-204: an engine failure without onError is swallowed quietly', () => {
|
||||
h.state.failNext = new Error('nope');
|
||||
expect(() => render(<AtlasGlobe {...baseProps()} />)).not.toThrow();
|
||||
expect(h.state.engines).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-205: fetches through the latest fetchJson prop', async () => {
|
||||
const first = vi.fn(async (_path: string) => 'first');
|
||||
const second = vi.fn(async (_path: string) => 'second');
|
||||
const { rerender } = render(<AtlasGlobe {...baseProps({ fetchJson: first })} />);
|
||||
rerender(<AtlasGlobe {...baseProps({ fetchJson: second })} />);
|
||||
await expect(engine().opts.fetchJson('manifest')).resolves.toBe('second');
|
||||
expect(second).toHaveBeenCalledWith('manifest');
|
||||
expect(first).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-206: forwards hover, select and error to the current callbacks', () => {
|
||||
const onHover = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
const onError = vi.fn();
|
||||
render(<AtlasGlobe {...baseProps({ onHover, onSelect, onError })} />);
|
||||
const hit: GlobeHit = { kind: 'country', index: 4, a2: 'DE' };
|
||||
const opts = engine().opts;
|
||||
opts.onHover?.(hit, 1, 2);
|
||||
opts.onSelect?.(null, 3, 4);
|
||||
opts.onError?.('boom');
|
||||
expect(onHover).toHaveBeenCalledWith(hit, 1, 2);
|
||||
expect(onSelect).toHaveBeenCalledWith(null, 3, 4);
|
||||
expect(onError).toHaveBeenCalledWith('boom');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-207: callbacks without handlers do nothing', () => {
|
||||
render(<AtlasGlobe {...baseProps()} />);
|
||||
const opts = engine().opts;
|
||||
expect(() => {
|
||||
opts.onHover?.(null, 0, 0);
|
||||
opts.onSelect?.(null, 0, 0);
|
||||
opts.onError?.(new Error('x'));
|
||||
opts.onFrame?.(asEngine(engine()));
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-208: when the engine is ready it reports the manifest and paints', () => {
|
||||
const paint = vi.fn();
|
||||
const onReady = vi.fn();
|
||||
render(<AtlasGlobe {...baseProps({ paint, onReady })} />);
|
||||
const e = engine();
|
||||
e.manifest = MANIFEST;
|
||||
act(() => e.opts.onReady?.());
|
||||
expect(onReady).toHaveBeenCalledWith(MANIFEST);
|
||||
// Once from onReady, once from the paint effect now that the globe is ready.
|
||||
expect(paint).toHaveBeenCalledTimes(2);
|
||||
expect(paint).toHaveBeenCalledWith(e);
|
||||
expect(e.kicks).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-209: a ready engine without a manifest still paints but reports nothing', () => {
|
||||
const paint = vi.fn();
|
||||
const onReady = vi.fn();
|
||||
render(<AtlasGlobe {...baseProps({ paint, onReady })} />);
|
||||
act(() => engine().opts.onReady?.());
|
||||
expect(onReady).not.toHaveBeenCalled();
|
||||
expect(paint).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-210: does not paint before the engine is ready, nor without a paint key', () => {
|
||||
const paint = vi.fn();
|
||||
const { rerender } = render(<AtlasGlobe {...baseProps({ paint, paintKey: undefined })} />);
|
||||
expect(paint).not.toHaveBeenCalled();
|
||||
act(() => engine().opts.onReady?.());
|
||||
// onReady paints; the effect stays quiet while paintKey is undefined.
|
||||
expect(paint).toHaveBeenCalledTimes(1);
|
||||
expect(engine().kicks).toBe(0);
|
||||
rerender(<AtlasGlobe {...baseProps({ paint, paintKey: 'k1' })} />);
|
||||
expect(paint).toHaveBeenCalledTimes(2);
|
||||
expect(engine().kicks).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-211: repaints and kicks the engine when the paint key changes', () => {
|
||||
const paint = vi.fn();
|
||||
const { rerender } = render(<AtlasGlobe {...baseProps({ paint, paintKey: 1 })} />);
|
||||
act(() => engine().opts.onReady?.());
|
||||
const before = paint.mock.calls.length;
|
||||
rerender(<AtlasGlobe {...baseProps({ paint, paintKey: 2 })} />);
|
||||
expect(paint.mock.calls.length).toBe(before + 1);
|
||||
rerender(<AtlasGlobe {...baseProps({ paint, paintKey: 2 })} />);
|
||||
expect(paint.mock.calls.length).toBe(before + 1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-212: a loaded region repaints through the latest paint prop', () => {
|
||||
const first = vi.fn();
|
||||
const second = vi.fn();
|
||||
const { rerender } = render(<AtlasGlobe {...baseProps({ paint: first })} />);
|
||||
rerender(<AtlasGlobe {...baseProps({ paint: second })} />);
|
||||
engine().onRegionLoaded?.('DE');
|
||||
expect(second).toHaveBeenCalledWith(engine());
|
||||
expect(first).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-213: switching dark mode hands the engine the other theme', () => {
|
||||
const { rerender } = render(<AtlasGlobe {...baseProps({ dark: true })} />);
|
||||
rerender(<AtlasGlobe {...baseProps({ dark: false })} />);
|
||||
const themes = engine().themes.map((t) => t.dark);
|
||||
expect(themes[themes.length - 1]).toBe(false);
|
||||
expect(themes[0]).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-214: passes the bottom inset on, zero when none is given', () => {
|
||||
const { rerender } = render(<AtlasGlobe {...baseProps()} />);
|
||||
expect(engine().insets).toEqual([0]);
|
||||
rerender(<AtlasGlobe {...baseProps({ insetBottom: 120 })} />);
|
||||
expect(engine().insets).toEqual([0, 120]);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-215: every frame places the labels with the current label props and reports it', () => {
|
||||
const onFrame = vi.fn();
|
||||
const labelFor = (a2: string) => `Land ${a2}`;
|
||||
const labelRegionsOf = (a2: string) => a2 === 'DE';
|
||||
const { container } = render(<AtlasGlobe {...baseProps({ onFrame, labelFor, labelRegionsOf })} />);
|
||||
const e = asEngine(engine());
|
||||
engine().opts.onFrame?.(e);
|
||||
engine().opts.onFrame?.(e);
|
||||
expect(h.placeLabels).toHaveBeenCalledTimes(2);
|
||||
const [host, pool, eng, lf, lr] = h.placeLabels.mock.calls[0];
|
||||
expect(host).toBe(container.querySelector('[aria-hidden="true"]'));
|
||||
expect(Array.isArray(pool)).toBe(true);
|
||||
// The pool is kept across frames, so labels are reused rather than rebuilt.
|
||||
expect(h.placeLabels.mock.calls[1][1]).toBe(pool);
|
||||
expect(eng).toBe(e);
|
||||
expect(lf).toBe(labelFor);
|
||||
expect(lr).toBe(labelRegionsOf);
|
||||
expect(onFrame).toHaveBeenCalledWith(e);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-216: a frame after unmount skips the labels', () => {
|
||||
const { unmount } = render(<AtlasGlobe {...baseProps()} />);
|
||||
const e = engine();
|
||||
unmount();
|
||||
e.opts.onFrame?.(asEngine(e));
|
||||
expect(h.placeLabels).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
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 = '#f4f4f5'; // theme-lint-disable: medal line art
|
||||
const ACCENT = '#d4d4d8'; // 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(255 255 255 / 0.22)" />
|
||||
<stop offset="0.55" stopColor="rgb(39 39 42 / 0.82)" />
|
||||
<stop offset="1" stopColor="rgb(14 14 16 / 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>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,863 @@
|
||||
/**
|
||||
* 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,
|
||||
latLimits,
|
||||
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. */
|
||||
const REGION_FADE_START = 5;
|
||||
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 };
|
||||
|
||||
/**
|
||||
* What one visit to the Atlas loaded and built, kept for the next one in this
|
||||
* tab: the manifest and the built world meshes, by file name (the name carries
|
||||
* the content hash). Coming back then puts the globe up at once, instead of
|
||||
* reading and triangulating the world again behind a loading notice. A new
|
||||
* page load starts empty, so a deploy's new geometry is read as before.
|
||||
*/
|
||||
let keptManifest: Promise<AtlasMeshManifest> | null = null;
|
||||
const keptWorlds = new Map<string, BuiltLayer>();
|
||||
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();
|
||||
/** Countries whose regions show at every zoom, not only once zoomed in (the regions view). */
|
||||
private pinned: 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 {
|
||||
keptManifest ??= this.fetchRetrying('manifest') as Promise<AtlasMeshManifest>;
|
||||
try {
|
||||
this.manifest = await keptManifest;
|
||||
} catch (err) {
|
||||
// A failed read is not kept: the next visit asks again.
|
||||
keptManifest = null;
|
||||
throw err;
|
||||
}
|
||||
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 file = this.manifest.world[lod];
|
||||
let layer = keptWorlds.get(file);
|
||||
if (!layer) {
|
||||
const topo = (await this.fetchRetrying(`world/${file}`)) as Topology;
|
||||
layer = await this.build(topo, 'countries', MAX_EDGE[lod], 0);
|
||||
keptWorlds.set(file, layer);
|
||||
}
|
||||
if (!this.alive) return;
|
||||
this.renderer.setWorld(lod, layer);
|
||||
this.kick();
|
||||
} finally {
|
||||
this.worldLoading.delete(lod);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows these countries' regions at every zoom instead of only once zoomed
|
||||
* in, so a country with a few visited regions reads as those regions rather
|
||||
* than as a whole visited country. An empty list goes back to the usual fade.
|
||||
*/
|
||||
setPinnedRegions(a2s: readonly string[]): void {
|
||||
this.pinned = new Set(a2s);
|
||||
this.kick();
|
||||
}
|
||||
|
||||
/** The region layers that must stay on the GPU: those in view and the pinned countries' coarse ones. */
|
||||
private regionsInUse(): ReadonlySet<string> {
|
||||
if (!this.pinned.size) return this.inViewRegionKeys;
|
||||
return new Set([...this.inViewRegionKeys, ...[...this.pinned].map((a2) => `${a2}:r0`)]);
|
||||
}
|
||||
|
||||
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.regionsInUse());
|
||||
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 = this.clampLat(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 = this.clampLat(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);
|
||||
}
|
||||
|
||||
/** A latitude for the view's centre, held where the map's edges stay off screen. */
|
||||
private clampLat(lat: number): number {
|
||||
const [south, north] = latLimits(this.cam.zoom, this.vp);
|
||||
return Math.max(south, Math.min(north, lat));
|
||||
}
|
||||
|
||||
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 = this.clampLat(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;
|
||||
// Zooming into the flat map narrows how far north and south it may look.
|
||||
this.cam.lat = this.clampLat(this.cam.lat);
|
||||
|
||||
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');
|
||||
}
|
||||
}
|
||||
// The pinned countries' coarse regions, wherever the camera is.
|
||||
for (const a2 of this.pinned) {
|
||||
if (!this.manifest?.regions[a2]) continue;
|
||||
this.renderer.touchRegion(`${a2}:r0`);
|
||||
void this.loadRegion(a2, 'r0');
|
||||
}
|
||||
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,
|
||||
pinnedRegions: this.pinned,
|
||||
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[] {
|
||||
const out: string[] = [];
|
||||
// Pinned countries draw their regions before the zoom brings the rest in.
|
||||
for (const a2 of this.pinned) {
|
||||
if (this.regionAlpha <= 0 && this.renderer.hasRegion(`${a2}:r0`)) out.push(`${a2}:r0`);
|
||||
}
|
||||
if (this.regionAlpha <= 0) return out;
|
||||
const fine = this.cam.zoom >= REGION_FINE_ZOOM;
|
||||
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,119 @@
|
||||
// FE-ATLAS2-RENDER-400 to FE-ATLAS2-RENDER-406: wishes pinned on the globe, placed per frame and hidden
|
||||
// behind the horizon or off screen.
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { createRef, type RefObject } from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { GlobeEngine } from './GlobeEngine';
|
||||
import GlobePins, { type GlobePin, type GlobePinsHandle } from './GlobePins';
|
||||
import type { ScreenPoint } from './globeMath';
|
||||
|
||||
/** An engine whose projection answers from a table keyed by "lon,lat". */
|
||||
function fakeEngine(points: Record<string, ScreenPoint>, width = 800, height = 600) {
|
||||
const project = vi.fn((lon: number, lat: number): ScreenPoint => {
|
||||
const p = points[`${lon},${lat}`];
|
||||
if (!p) throw new Error(`unexpected point ${lon},${lat}`);
|
||||
return p;
|
||||
});
|
||||
const engine = { vp: { width, height, baseRadius: 1, globeY: 0, flatY: 0 }, project } as unknown as GlobeEngine;
|
||||
return { engine, project };
|
||||
}
|
||||
|
||||
function handle(ref: RefObject<GlobePinsHandle | null>): GlobePinsHandle {
|
||||
if (!ref.current) throw new Error('GlobePins handle missing');
|
||||
return ref.current;
|
||||
}
|
||||
|
||||
const PARIS: GlobePin = { key: 'paris', lon: 2, lat: 49, title: 'Paris' };
|
||||
const KYOTO: GlobePin = { key: 'kyoto', lon: 136, lat: 35, title: 'Kyoto', reached: true };
|
||||
|
||||
describe('GlobePins', () => {
|
||||
it('FE-ATLAS2-RENDER-400: renders one labelled star button per pin, marking reached wishes', () => {
|
||||
render(<GlobePins pins={[PARIS, KYOTO]} />);
|
||||
const paris = screen.getByRole('button', { name: 'Paris' });
|
||||
const kyoto = screen.getByRole('button', { name: 'Kyoto' });
|
||||
expect(paris).toHaveAttribute('title', 'Paris');
|
||||
expect(paris).toHaveAttribute('data-reached', '0');
|
||||
expect(kyoto).toHaveAttribute('data-reached', '1');
|
||||
expect(paris).toHaveAttribute('data-no-press');
|
||||
expect(paris.querySelector('svg')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-401: clicking a pin runs its action', () => {
|
||||
const onClick = vi.fn();
|
||||
render(<GlobePins pins={[{ ...PARIS, onClick }]} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Paris' }));
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-402: moves a visible pin to its screen point and makes it clickable', () => {
|
||||
const ref = createRef<GlobePinsHandle>();
|
||||
render(<GlobePins ref={ref} pins={[PARIS]} />);
|
||||
const { engine, project } = fakeEngine({ '2,49': { x: 120.04, y: 80.36, visible: 0.5, shade: 1 } });
|
||||
act(() => handle(ref).layout(engine));
|
||||
expect(project).toHaveBeenCalledWith(2, 49);
|
||||
const pin = screen.getByRole('button', { name: 'Paris' });
|
||||
expect(pin.style.transform).toBe('translate3d(120.0px, 80.4px, 0) translate(-50%, -50%)');
|
||||
expect(pin.style.opacity).toBe('1');
|
||||
expect(pin.style.pointerEvents).toBe('auto');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-403: fades a pin in as it comes over the horizon', () => {
|
||||
const ref = createRef<GlobePinsHandle>();
|
||||
render(<GlobePins ref={ref} pins={[PARIS]} />);
|
||||
const { engine } = fakeEngine({ '2,49': { x: 10, y: 10, visible: 0.1, shade: 0.2 } });
|
||||
act(() => handle(ref).layout(engine));
|
||||
const pin = screen.getByRole('button', { name: 'Paris' });
|
||||
expect(Number(pin.style.opacity)).toBeCloseTo(0.6);
|
||||
expect(pin.style.pointerEvents).toBe('auto');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-404: hides a pin behind the globe', () => {
|
||||
const ref = createRef<GlobePinsHandle>();
|
||||
render(<GlobePins ref={ref} pins={[PARIS]} />);
|
||||
const { engine } = fakeEngine({ '2,49': { x: 100, y: 100, visible: 0.01, shade: 0 } });
|
||||
act(() => handle(ref).layout(engine));
|
||||
const pin = screen.getByRole('button', { name: 'Paris' });
|
||||
expect(pin.style.opacity).toBe('0');
|
||||
expect(pin.style.pointerEvents).toBe('none');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-405: hides pins more than 20 px off any edge of the screen', () => {
|
||||
const ref = createRef<GlobePinsHandle>();
|
||||
const pins: GlobePin[] = [
|
||||
{ key: 'l', lon: 1, lat: 0, title: 'Left' },
|
||||
{ key: 'r', lon: 2, lat: 0, title: 'Right' },
|
||||
{ key: 't', lon: 3, lat: 0, title: 'Top' },
|
||||
{ key: 'b', lon: 4, lat: 0, title: 'Bottom' },
|
||||
{ key: 'edge', lon: 5, lat: 0, title: 'Edge' },
|
||||
];
|
||||
render(<GlobePins ref={ref} pins={pins} />);
|
||||
const { engine } = fakeEngine(
|
||||
{
|
||||
'1,0': { x: -21, y: 100, visible: 1, shade: 1 },
|
||||
'2,0': { x: 821, y: 100, visible: 1, shade: 1 },
|
||||
'3,0': { x: 100, y: -21, visible: 1, shade: 1 },
|
||||
'4,0': { x: 100, y: 621, visible: 1, shade: 1 },
|
||||
'5,0': { x: -19, y: 619, visible: 1, shade: 1 },
|
||||
},
|
||||
800,
|
||||
600
|
||||
);
|
||||
act(() => handle(ref).layout(engine));
|
||||
for (const title of ['Left', 'Right', 'Top', 'Bottom']) {
|
||||
expect(screen.getByRole('button', { name: title }).style.opacity).toBe('0');
|
||||
}
|
||||
expect(screen.getByRole('button', { name: 'Edge' }).style.opacity).toBe('1');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-406: after the pin list changes, layout places the new pins', () => {
|
||||
const ref = createRef<GlobePinsHandle>();
|
||||
const { rerender } = render(<GlobePins ref={ref} pins={[PARIS]} />);
|
||||
rerender(<GlobePins ref={ref} pins={[KYOTO]} />);
|
||||
expect(screen.queryByRole('button', { name: 'Paris' })).toBeNull();
|
||||
const { engine, project } = fakeEngine({ '136,35': { x: 5, y: 5, visible: 1, shade: 1 } });
|
||||
act(() => handle(ref).layout(engine));
|
||||
expect(project).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByRole('button', { name: 'Kyoto' }).style.pointerEvents).toBe('auto');
|
||||
});
|
||||
});
|
||||
@@ -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,700 @@
|
||||
// FE-ATLAS2-RENDER-001 to FE-ATLAS2-RENDER-040: the WebGL2 renderer of the Atlas globe, driven
|
||||
// against a hand-written WebGL2 fake that records draws, uniforms and buffer lifetimes.
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { createFakeGl, GL, type FakeGl, type FakeGlOptions } from '../../../tests/helpers/fakeWebGl2';
|
||||
import { GlobeRenderer, MAX_FEATURES, type ArcLayer, type DrawState, type GlobeTheme } from './GlobeRenderer';
|
||||
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';
|
||||
|
||||
const DARK: GlobeTheme = {
|
||||
land: [0.19, 0.19, 0.2],
|
||||
ocean: [0.08, 0.08, 0.09],
|
||||
oceanDeep: [0.03, 0.03, 0.03],
|
||||
space0: [0.01, 0.01, 0.01],
|
||||
space1: [0.04, 0.04, 0.04],
|
||||
glow: [0.18, 0.18, 0.19],
|
||||
border: [0.05, 0.05, 0.06, 0.9],
|
||||
coast: [0.85, 0.85, 0.87, 0.14],
|
||||
regionBorder: [0.95, 0.95, 0.95, 0.5],
|
||||
selection: [1, 1, 1, 0.95],
|
||||
arc: [0.9, 0.9, 0.9, 0.8],
|
||||
dark: true,
|
||||
};
|
||||
const LIGHT: GlobeTheme = { ...DARK, dark: false };
|
||||
|
||||
function fill(tris: number): FillMesh {
|
||||
return {
|
||||
ll: new Float32Array(6),
|
||||
ref: new Float32Array(6),
|
||||
fid: new Float32Array(3),
|
||||
index: new Uint32Array(tris * 3),
|
||||
};
|
||||
}
|
||||
|
||||
function lines(count: number): LineMesh {
|
||||
return { seg: new Float32Array(count * 4), count };
|
||||
}
|
||||
|
||||
function layer(tris: number, coast: number, borders: number): BuiltLayer {
|
||||
return { fill: fill(tris), coast: lines(coast), borders: lines(borders) };
|
||||
}
|
||||
|
||||
function arc(count: number, width = 2): ArcLayer {
|
||||
return { data: new Float32Array(count * 8), count, width };
|
||||
}
|
||||
|
||||
function state(over: Partial<DrawState> = {}): DrawState {
|
||||
return {
|
||||
frame: { t: 0.25, k: 1, scale: 200, originX: 400, originY: 300, centerLon: 0.1, centerLat: 0.2 },
|
||||
dpr: 2,
|
||||
width: 800,
|
||||
height: 600,
|
||||
time: 1.5,
|
||||
revealStart: 0.75,
|
||||
hover: 3,
|
||||
selected: 7,
|
||||
ink: null,
|
||||
regionAlpha: 0,
|
||||
theme: DARK,
|
||||
arcs: [],
|
||||
arcProgress: 0.6,
|
||||
regionKeys: [],
|
||||
worldKey: 'w',
|
||||
selectedOutline: null,
|
||||
sun: [1, 0, 0],
|
||||
night: 0.5,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function setup(opts: FakeGlOptions = {}): { fake: FakeGl; r: GlobeRenderer } {
|
||||
const fake = createFakeGl(opts);
|
||||
const r = new GlobeRenderer(fake.canvas());
|
||||
return { fake, r };
|
||||
}
|
||||
|
||||
/** Fill draws with this triangle count. */
|
||||
function fillDraws(fake: FakeGl, count: number) {
|
||||
return fake.drawsWith(FILL_FS).filter((d) => d.call === 'drawElements' && d.count === count);
|
||||
}
|
||||
|
||||
function lineDraws(fake: FakeGl, instances: number) {
|
||||
return fake.drawsWith(LINE_FS).filter((d) => d.call === 'drawArraysInstanced' && d.instances === instances);
|
||||
}
|
||||
|
||||
function deletedBuffers(fake: FakeGl): unknown[] {
|
||||
return fake.gl.deleteBuffer.mock.calls.map((c) => c[0]);
|
||||
}
|
||||
|
||||
describe('GlobeRenderer setup', () => {
|
||||
it('FE-ATLAS2-RENDER-001: throws when the canvas has no WebGL2 context', () => {
|
||||
const canvas = { getContext: () => null } as unknown as HTMLCanvasElement;
|
||||
expect(() => new GlobeRenderer(canvas)).toThrow('WebGL2 unavailable');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-002: asks for an opaque, antialiased webgl2 context', () => {
|
||||
const fake = createFakeGl();
|
||||
const canvas = fake.canvas();
|
||||
const r = new GlobeRenderer(canvas);
|
||||
expect(r.gl).toBe(fake.gl);
|
||||
expect(canvas.getContext).toHaveBeenCalledWith('webgl2', {
|
||||
antialias: true,
|
||||
alpha: false,
|
||||
premultipliedAlpha: false,
|
||||
preserveDrawingBuffer: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-003: links the five programs from the right shader pairs', () => {
|
||||
const { fake } = setup();
|
||||
expect(fake.programs.map((p) => p.srcs)).toEqual([
|
||||
[FILL_VS, FILL_FS],
|
||||
[FILL_VS, PICK_FS],
|
||||
[LINE_VS, LINE_FS],
|
||||
[SKY_VS, SKY_FS],
|
||||
[SKY_VS, RIM_FS],
|
||||
]);
|
||||
expect(fake.gl.linkProgram).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-004: makes two 256x64 nearest-filtered status textures', () => {
|
||||
const { fake } = setup();
|
||||
expect(fake.textures).toHaveLength(2);
|
||||
const sizes = fake.gl.texImage2D.mock.calls.map((c) => [c[3], c[4]]);
|
||||
expect(sizes).toEqual([
|
||||
[256, 64],
|
||||
[256, 64],
|
||||
]);
|
||||
expect(fake.gl.texParameteri).toHaveBeenCalledWith(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST);
|
||||
expect(fake.gl.texParameteri).toHaveBeenCalledWith(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST);
|
||||
expect(MAX_FEATURES).toBe(256 * 64);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-005: a shader that fails to compile throws with its log and is deleted', () => {
|
||||
const fake = createFakeGl({ compileOk: (src) => src !== PICK_FS, shaderLog: 'syntax error at 3' });
|
||||
expect(() => new GlobeRenderer(fake.canvas())).toThrow('Atlas globe shader failed: syntax error at 3');
|
||||
expect(fake.gl.deleteShader).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-006: a compile failure without a log says unknown', () => {
|
||||
const fake = createFakeGl({ compileOk: () => false, shaderLog: null });
|
||||
expect(() => new GlobeRenderer(fake.canvas())).toThrow('Atlas globe shader failed: unknown');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-007: a program that fails to link throws with its log, or unknown', () => {
|
||||
const withLog = createFakeGl({ linkOk: false, programLog: 'varying mismatch' });
|
||||
expect(() => new GlobeRenderer(withLog.canvas())).toThrow('Atlas globe program failed: varying mismatch');
|
||||
const noLog = createFakeGl({ linkOk: false, programLog: null });
|
||||
expect(() => new GlobeRenderer(noLog.canvas())).toThrow('Atlas globe program failed: unknown');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-008: binds the full-screen quad for the sky and the rim', () => {
|
||||
const { fake } = setup();
|
||||
// a_pos is attribute 0 of both SKY_VS programs, set up once inside the quad VAO each.
|
||||
const quadAttr = fake.gl.vertexAttribPointer.mock.calls.filter((c) => c[0] === 0 && c[1] === 2 && c[4] === 0);
|
||||
expect(quadAttr.length).toBeGreaterThanOrEqual(2);
|
||||
const quadData = fake.buffers.find((b) => b.data instanceof Float32Array && b.data.length === 8);
|
||||
expect(Array.from(quadData?.data as Float32Array)).toEqual([-1, -1, 1, -1, -1, 1, 1, 1]);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-009: skips attributes a compiler dropped or placed at -1', () => {
|
||||
const { fake, r } = setup({
|
||||
attribLocation: (fs, name, i) => {
|
||||
if (fs === RIM_FS && name === 'a_pos') return null;
|
||||
if (fs === PICK_FS && name === 'a_ref') return -1;
|
||||
if (fs === LINE_FS && name === 'a_h') return null;
|
||||
if (fs === LINE_FS && name === 'a_s') return -1;
|
||||
return i;
|
||||
},
|
||||
});
|
||||
expect(fake.programWith(RIM_FS).attribs).toEqual([]);
|
||||
r.setWorld('w', layer(2, 1, 1));
|
||||
r.draw(state({ arcs: [arc(3)] }));
|
||||
expect(fake.gl.enableVertexAttribArray.mock.calls.some((c) => c[0] === -1)).toBe(false);
|
||||
expect(fake.gl.vertexAttribPointer.mock.calls.some((c) => c[0] === -1)).toBe(false);
|
||||
// Only a_a and a_b get a divisor once a_h and a_s are gone.
|
||||
const line = fake.programWith(LINE_FS);
|
||||
const divisorLocs = new Set(fake.gl.vertexAttribDivisor.mock.calls.map((c) => c[0]));
|
||||
expect(divisorLocs).toEqual(new Set([line.attribLoc.get('a_a'), line.attribLoc.get('a_b')]));
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobeRenderer draw', () => {
|
||||
it('FE-ATLAS2-RENDER-010: sets every uniform it uses on a location its shaders declare', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setOcean(fill(5));
|
||||
r.setWorld('w', layer(2, 1, 1));
|
||||
r.setRegion('DE', layer(4, 1, 1));
|
||||
r.draw(
|
||||
state({
|
||||
regionAlpha: 1,
|
||||
regionKeys: ['DE'],
|
||||
arcs: [arc(2)],
|
||||
selectedOutline: lines(2),
|
||||
ink: { id: 1, lon: 0, lat: 0, radius: 1 },
|
||||
})
|
||||
);
|
||||
const methods = [
|
||||
fake.gl.uniform1f,
|
||||
fake.gl.uniform1i,
|
||||
fake.gl.uniform2f,
|
||||
fake.gl.uniform4f,
|
||||
fake.gl.uniform3fv,
|
||||
fake.gl.uniform4fv,
|
||||
];
|
||||
for (const m of methods) {
|
||||
for (const call of m.mock.calls) expect(call[0]).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-011: sizes the viewport in device pixels and draws the sky first', () => {
|
||||
const { fake, r } = setup();
|
||||
r.draw(state({ width: 800.4, height: 600, dpr: 2 }));
|
||||
expect(fake.gl.viewport).toHaveBeenCalledWith(0, 0, 1601, 1200);
|
||||
expect(fake.enabled.has(GL.BLEND)).toBe(true);
|
||||
expect(fake.enabled.has(GL.DEPTH_TEST)).toBe(false);
|
||||
const first = fake.draws[0];
|
||||
expect(first.program?.srcs[1]).toBe(SKY_FS);
|
||||
expect(first.call).toBe('drawArrays');
|
||||
expect(first.mode).toBe(GL.TRIANGLE_STRIP);
|
||||
expect(first.count).toBe(4);
|
||||
expect(first.values.u_viewport).toEqual([1601, 1200]);
|
||||
expect(first.values.u_globe).toEqual([800, 600]);
|
||||
expect(first.values.u_radius).toBe(400);
|
||||
expect(first.values.u_t).toBe(0.25);
|
||||
expect(first.values.u_time).toBe(1.5);
|
||||
expect(first.values.u_space0).toEqual(DARK.space0);
|
||||
expect(first.values.u_space1).toEqual(DARK.space1);
|
||||
expect(first.values.u_dark).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-012: draws the rim last, over the limb, and unbinds the VAO', () => {
|
||||
const { fake, r } = setup();
|
||||
r.draw(state());
|
||||
const last = fake.draws[fake.draws.length - 1];
|
||||
expect(last.program?.srcs[1]).toBe(RIM_FS);
|
||||
expect(last.values.u_glow).toEqual(DARK.glow);
|
||||
expect(last.values.u_radius).toBe(400);
|
||||
expect(fake.gl.bindVertexArray).toHaveBeenLastCalledWith(null);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-013: passes the projection to the fill program in device pixels', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setOcean(fill(5));
|
||||
r.draw(state());
|
||||
const [ocean] = fillDraws(fake, 15);
|
||||
expect(ocean.values.u_center).toEqual([0.1, 0.2]);
|
||||
expect(ocean.values.u_scale).toBe(400);
|
||||
expect(ocean.values.u_origin).toEqual([800, 600]);
|
||||
expect(ocean.values.u_viewport).toEqual([1600, 1200]);
|
||||
expect(ocean.values.u_status).toBe(0);
|
||||
expect(ocean.values.u_fx).toBe(1);
|
||||
expect(ocean.values.u_hover).toBe(3);
|
||||
expect(ocean.values.u_selected).toBe(7);
|
||||
expect(ocean.values.u_revealStart).toBe(0.75);
|
||||
expect(ocean.values.u_sun).toEqual([1, 0, 0]);
|
||||
expect(ocean.values.u_night).toBe(0.5);
|
||||
expect(ocean.values.u_dpr).toBe(2);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-014: draws the ocean in mode 1 only once it is set', () => {
|
||||
const { fake, r } = setup();
|
||||
r.draw(state());
|
||||
expect(fake.drawsWith(FILL_FS)).toHaveLength(0);
|
||||
r.setOcean(fill(5));
|
||||
r.draw(state());
|
||||
const ocean = fillDraws(fake, 15);
|
||||
expect(ocean).toHaveLength(1);
|
||||
expect(ocean[0].values.u_mode).toBe(1);
|
||||
expect(ocean[0].mode).toBe(GL.TRIANGLES);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-015: dark mode lights a hovered country up and keeps the limb darker', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setOcean(fill(1));
|
||||
r.draw(state({ theme: DARK }));
|
||||
const [d] = fillDraws(fake, 3);
|
||||
expect(d.values.u_shadeMin).toBe(0.42);
|
||||
expect(d.values.u_hoverTint).toEqual([1, 1, 1, 0.09]);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-016: light mode tints a hovered country blue and keeps the limb bright', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setOcean(fill(1));
|
||||
r.draw(state({ theme: LIGHT }));
|
||||
const [d] = fillDraws(fake, 3);
|
||||
expect(d.values.u_shadeMin).toBe(0.82);
|
||||
expect(d.values.u_hoverTint).toEqual([0.42, 0.56, 0.82, 0.16]);
|
||||
expect(fake.drawsWith(SKY_FS)[0].values.u_dark).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-017: hands the ink spot over in radians, or a neutral one without ink', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setOcean(fill(1));
|
||||
r.draw(state({ ink: { id: 42, lon: 180, lat: -90, radius: 0.3 } }));
|
||||
r.draw(state({ ink: null }));
|
||||
const [withInk, without] = fillDraws(fake, 3);
|
||||
expect(withInk.values.u_inkId).toBe(42);
|
||||
const [inkLon, inkLat] = withInk.values.u_inkLL as number[];
|
||||
expect(inkLon).toBeCloseTo(Math.PI);
|
||||
expect(inkLat).toBeCloseTo(-Math.PI / 2);
|
||||
expect(withInk.values.u_inkR).toBe(0.3);
|
||||
expect(without.values.u_inkId).toBe(-1);
|
||||
expect(without.values.u_inkLL).toEqual([0, 0]);
|
||||
expect(without.values.u_inkR).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobeRenderer status textures', () => {
|
||||
it('FE-ATLAS2-RENDER-018: uploads status and fx once at the first draw, then only when dirty', () => {
|
||||
const { fake, r } = setup();
|
||||
r.draw(state());
|
||||
expect(fake.statusUploads).toHaveLength(2);
|
||||
r.draw(state());
|
||||
expect(fake.statusUploads).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-019: writes a feature colour and effects at its four bytes', () => {
|
||||
const { fake, r } = setup();
|
||||
r.draw(state());
|
||||
r.setStatus(3, [10, 20, 30, 40], [1, 2, 3, 4]);
|
||||
r.draw(state());
|
||||
const [status, fx] = fake.statusUploads.slice(2);
|
||||
expect(Array.from(status.slice(12, 16))).toEqual([10, 20, 30, 40]);
|
||||
expect(Array.from(fx.slice(12, 16))).toEqual([1, 2, 3, 4]);
|
||||
expect(status.length).toBe(MAX_FEATURES * 4);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-020: leaves the effects empty when only a colour is given', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setStatus(5, [9, 9, 9, 255], [7, 7, 7, 7]);
|
||||
r.setStatus(5, [1, 2, 3, 4]);
|
||||
r.draw(state());
|
||||
const [status, fx] = fake.statusUploads;
|
||||
expect(Array.from(status.slice(20, 24))).toEqual([1, 2, 3, 4]);
|
||||
expect(Array.from(fx.slice(20, 24))).toEqual([0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-021: ignores ids outside the texture without marking it dirty', () => {
|
||||
const { fake, r } = setup();
|
||||
r.draw(state());
|
||||
r.setStatus(-1, [1, 1, 1, 1]);
|
||||
r.setStatus(MAX_FEATURES, [1, 1, 1, 1]);
|
||||
r.draw(state());
|
||||
expect(fake.statusUploads).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-022: clearStatus zeroes a range of ids and re-uploads', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setStatus(1, [1, 1, 1, 1], [1, 1, 1, 1]);
|
||||
r.setStatus(2, [2, 2, 2, 2], [2, 2, 2, 2]);
|
||||
r.setStatus(4, [4, 4, 4, 4], [4, 4, 4, 4]);
|
||||
r.draw(state());
|
||||
r.clearStatus(1, 3);
|
||||
r.draw(state());
|
||||
const [status, fx] = fake.statusUploads.slice(2);
|
||||
expect(Array.from(status.slice(4, 12))).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
expect(Array.from(fx.slice(4, 12))).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
expect(Array.from(status.slice(16, 20))).toEqual([4, 4, 4, 4]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobeRenderer world layers', () => {
|
||||
it('FE-ATLAS2-RENDER-023: draws the world named by the frame, in mode 0 with its lines', () => {
|
||||
const { fake, r } = setup();
|
||||
expect(r.hasWorld('w')).toBe(false);
|
||||
r.setWorld('w', layer(2, 3, 4));
|
||||
expect(r.hasWorld('w')).toBe(true);
|
||||
r.draw(state({ regionAlpha: 0.4 }));
|
||||
const [world] = fillDraws(fake, 6);
|
||||
expect(world.values.u_mode).toBe(0);
|
||||
expect(world.values.u_dimBase).toBe(1);
|
||||
expect(world.values.u_regionFade).toBe(0.4);
|
||||
const [borders] = lineDraws(fake, 4);
|
||||
expect(borders.values.u_color).toEqual(DARK.border);
|
||||
expect(borders.values.u_width).toBeCloseTo(1.6);
|
||||
expect(borders.values.u_lift).toBe(0);
|
||||
expect(borders.values.u_progress).toBe(2);
|
||||
const [coast] = lineDraws(fake, 3);
|
||||
expect(coast.values.u_color).toEqual(DARK.coast);
|
||||
expect(coast.values.u_width).toBeCloseTo(1.8);
|
||||
expect(coast.count).toBe(6);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-024: draws no world when the frame names one that is not loaded', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setWorld('w', layer(2, 3, 4));
|
||||
r.draw(state({ worldKey: 'w-fine' }));
|
||||
expect(fillDraws(fake, 6)).toHaveLength(0);
|
||||
expect(fake.drawsWith(LINE_FS)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-025: skips a line mesh without segments', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setWorld('w', layer(2, 0, 4));
|
||||
r.draw(state());
|
||||
const instanced = fake.drawsWith(LINE_FS);
|
||||
expect(instanced).toHaveLength(1);
|
||||
expect(instanced[0].instances).toBe(4);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-026: replacing a world frees the old one after the new one is up', () => {
|
||||
const { fake, r } = setup();
|
||||
const first = layer(2, 3, 4);
|
||||
r.setWorld('w', first);
|
||||
const oldBuffers = [
|
||||
fake.bufferOf(first.fill.ll),
|
||||
fake.bufferOf(first.fill.index),
|
||||
fake.bufferOf(first.coast.seg),
|
||||
fake.bufferOf(first.borders.seg),
|
||||
];
|
||||
const second = layer(1, 1, 1);
|
||||
r.setWorld('w', second);
|
||||
const deleted = deletedBuffers(fake);
|
||||
for (const b of oldBuffers) expect(deleted).toContain(b);
|
||||
expect(deleted).not.toContain(fake.bufferOf(second.fill.ll));
|
||||
// fill, pick, coast and border VAOs of the old layer.
|
||||
expect(fake.gl.deleteVertexArray).toHaveBeenCalledTimes(4);
|
||||
r.draw(state());
|
||||
expect(fillDraws(fake, 3)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-027: uploads fill attributes with the element buffer bound to the VAO', () => {
|
||||
const { fake, r } = setup();
|
||||
const l = layer(2, 1, 1);
|
||||
r.setWorld('w', l);
|
||||
expect(fake.gl.bufferData).toHaveBeenCalledWith(GL.ELEMENT_ARRAY_BUFFER, l.fill.index, GL.STATIC_DRAW);
|
||||
expect(fake.gl.bufferData).toHaveBeenCalledWith(GL.ARRAY_BUFFER, l.fill.fid, GL.STATIC_DRAW);
|
||||
const fillProg = fake.programWith(FILL_FS);
|
||||
expect(fake.gl.vertexAttribPointer).toHaveBeenCalledWith(fillProg.attribLoc.get('a_fid'), 1, GL.FLOAT, false, 0, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobeRenderer region layers', () => {
|
||||
it('FE-ATLAS2-RENDER-028: draws loaded regions in mode 2 over the world with faded borders', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setWorld('w', layer(1, 0, 0));
|
||||
r.setRegion('DE', layer(4, 1, 5));
|
||||
expect(r.hasRegion('DE')).toBe(true);
|
||||
r.draw(state({ regionAlpha: 0.5, regionKeys: ['FR', 'DE'] }));
|
||||
const [region] = fillDraws(fake, 12);
|
||||
expect(region.values.u_mode).toBe(2);
|
||||
expect(region.values.u_layerAlpha).toBe(0.5);
|
||||
const [borders] = lineDraws(fake, 5);
|
||||
expect(borders.values.u_color).toEqual([0.95, 0.95, 0.95, 0.25]);
|
||||
expect(borders.values.u_width).toBeCloseTo(1.4);
|
||||
// The theme is not changed by the fade.
|
||||
expect(DARK.regionBorder[3]).toBe(0.5);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-049: a pinned country draws its regions in full while zoomed out, with faint inner borders', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setRegion('DE:r0', layer(4, 1, 5));
|
||||
r.draw(state({ regionAlpha: 0, regionKeys: ['DE:r0'], pinnedRegions: new Set(['DE']) }));
|
||||
const [region] = fillDraws(fake, 12);
|
||||
expect(region.values.u_mode).toBe(2);
|
||||
expect(region.values.u_layerAlpha).toBe(1);
|
||||
const [borders] = lineDraws(fake, 5);
|
||||
expect((borders.values.u_color as number[])[3]).toBeCloseTo(DARK.regionBorder[3] * 0.45);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-029: does not draw regions faded out below the threshold', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setRegion('DE', layer(4, 1, 5));
|
||||
r.draw(state({ regionAlpha: 0.0005, regionKeys: ['DE'] }));
|
||||
expect(fillDraws(fake, 12)).toHaveLength(0);
|
||||
expect(lineDraws(fake, 5)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-030: does not switch to region mode when none of the keys is loaded', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setOcean(fill(1));
|
||||
r.draw(state({ regionAlpha: 1, regionKeys: ['FR'] }));
|
||||
expect(fake.drawsWith(FILL_FS).every((d) => d.values.u_mode !== 2)).toBe(true);
|
||||
expect(fake.drawsWith(FILL_FS)[0].values.u_layerAlpha).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-031: replacing a region frees the old layer and keeps one entry', () => {
|
||||
const { fake, r } = setup();
|
||||
const first = layer(4, 1, 1);
|
||||
r.setRegion('DE', first);
|
||||
r.setRegion('DE', layer(2, 1, 1));
|
||||
expect(deletedBuffers(fake)).toContain(fake.bufferOf(first.fill.index));
|
||||
r.draw(state({ regionAlpha: 1, regionKeys: ['DE'] }));
|
||||
expect(fillDraws(fake, 12)).toHaveLength(0);
|
||||
expect(fillDraws(fake, 6)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-032: past 64 region layers drops the one held longest', () => {
|
||||
const { fake, r } = setup();
|
||||
const oldest = layer(1, 1, 1);
|
||||
r.setRegion('r0', oldest);
|
||||
for (let i = 1; i <= 64; i++) r.setRegion(`r${i}`, layer(1, 1, 1));
|
||||
expect(r.hasRegion('r0')).toBe(false);
|
||||
expect(r.hasRegion('r1')).toBe(true);
|
||||
expect(r.hasRegion('r64')).toBe(true);
|
||||
expect(deletedBuffers(fake)).toContain(fake.bufferOf(oldest.fill.ll));
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-033: never drops a region in use, the next oldest goes instead', () => {
|
||||
const { r } = setup();
|
||||
for (let i = 0; i < 64; i++) r.setRegion(`r${i}`, layer(1, 1, 1));
|
||||
r.setRegion('r64', layer(1, 1, 1), new Set(['r0']));
|
||||
expect(r.hasRegion('r0')).toBe(true);
|
||||
expect(r.hasRegion('r1')).toBe(false);
|
||||
expect(r.hasRegion('r64')).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-034: touching a region makes it the last to go; an unknown key is a no-op', () => {
|
||||
const { r } = setup();
|
||||
for (let i = 0; i < 64; i++) r.setRegion(`r${i}`, layer(1, 1, 1));
|
||||
r.touchRegion('r0');
|
||||
r.touchRegion('nope');
|
||||
expect(r.hasRegion('nope')).toBe(false);
|
||||
r.setRegion('r64', layer(1, 1, 1));
|
||||
expect(r.hasRegion('r0')).toBe(true);
|
||||
expect(r.hasRegion('r1')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobeRenderer outline and arcs', () => {
|
||||
it('FE-ATLAS2-RENDER-035: draws the selected outline glowing, uploading it once per mesh', () => {
|
||||
const { fake, r } = setup();
|
||||
const outline = lines(7);
|
||||
r.draw(state({ selectedOutline: outline }));
|
||||
r.draw(state({ selectedOutline: outline }));
|
||||
const uploads = fake.gl.bufferData.mock.calls.filter((c) => c[1] === outline.seg);
|
||||
expect(uploads).toHaveLength(1);
|
||||
const draws = lineDraws(fake, 7);
|
||||
expect(draws).toHaveLength(2);
|
||||
expect(draws[0].values.u_glow).toBe(0.55);
|
||||
expect(draws[0].values.u_color).toEqual(DARK.selection);
|
||||
expect(draws[0].values.u_width).toBeCloseTo(3.6);
|
||||
expect(fake.programWith(LINE_FS).values.u_glow).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-036: a new outline frees the buffer of the previous one', () => {
|
||||
const { fake, r } = setup();
|
||||
const a = lines(7);
|
||||
r.draw(state({ selectedOutline: a }));
|
||||
const aBuffer = fake.bufferOf(a.seg);
|
||||
expect(deletedBuffers(fake)).not.toContain(aBuffer);
|
||||
const b = lines(9);
|
||||
r.draw(state({ selectedOutline: b }));
|
||||
expect(deletedBuffers(fake)).toContain(aBuffer);
|
||||
expect(lineDraws(fake, 9)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-037: draws arcs lifted with their progress, width and glow', () => {
|
||||
const { fake, r } = setup();
|
||||
const a = arc(5, 3);
|
||||
r.draw(state({ arcs: [a], arcProgress: 0.6 }));
|
||||
const [d] = lineDraws(fake, 5);
|
||||
expect(d.values.u_lift).toBe(1);
|
||||
expect(d.values.u_progress).toBe(0.6);
|
||||
expect(d.values.u_glow).toBe(0.35);
|
||||
expect(d.values.u_width).toBe(6);
|
||||
expect(d.values.u_color).toEqual(DARK.arc);
|
||||
expect(fake.programWith(LINE_FS).values.u_lift).toBe(0);
|
||||
// An arc carries heights and progress too: stride of eight floats, four attributes per instance.
|
||||
const line = fake.programWith(LINE_FS);
|
||||
expect(fake.gl.vertexAttribPointer).toHaveBeenCalledWith(line.attribLoc.get('a_s'), 2, GL.FLOAT, false, 32, 24);
|
||||
expect(fake.gl.vertexAttribDivisor).toHaveBeenCalledWith(line.attribLoc.get('a_h'), 1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-038: keeps an arc on the GPU across frames and frees the ones no longer drawn', () => {
|
||||
const { fake, r } = setup();
|
||||
const keep = arc(5);
|
||||
const gone = arc(6);
|
||||
r.draw(state({ arcs: [keep, gone] }));
|
||||
r.draw(state({ arcs: [keep] }));
|
||||
r.draw(state({ arcs: [keep] }));
|
||||
expect(fake.gl.bufferData.mock.calls.filter((c) => c[1] === keep.data)).toHaveLength(1);
|
||||
const deleted = deletedBuffers(fake);
|
||||
expect(deleted).toContain(fake.bufferOf(gone.data));
|
||||
expect(deleted).not.toContain(fake.bufferOf(keep.data));
|
||||
expect(lineDraws(fake, 5)).toHaveLength(3);
|
||||
expect(lineDraws(fake, 6)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobeRenderer picking', () => {
|
||||
it('FE-ATLAS2-RENDER-039: returns -1 before any frame was drawn', () => {
|
||||
const { fake, r } = setup({ pixel: [9, 0, 0, 255] });
|
||||
expect(r.pick(10, 10, true)).toBe(-1);
|
||||
expect(fake.framebuffers).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-040: decodes the id under the pointer from the pick pass', () => {
|
||||
const { fake, r } = setup({ pixel: [5, 1, 0, 255] });
|
||||
r.setWorld('w', layer(2, 1, 1));
|
||||
r.draw(state());
|
||||
expect(r.pick(10.2, 20.4, false)).toBe(5 + 256 - 1);
|
||||
expect(fake.gl.readPixels).toHaveBeenCalledWith(
|
||||
20,
|
||||
1200 - 41 - 1,
|
||||
1,
|
||||
1,
|
||||
GL.RGBA,
|
||||
GL.UNSIGNED_BYTE,
|
||||
expect.any(Uint8Array)
|
||||
);
|
||||
const picks = fake.drawsWith(PICK_FS);
|
||||
expect(picks).toHaveLength(1);
|
||||
expect(picks[0].count).toBe(6);
|
||||
expect(picks[0].framebuffer).toBe(fake.framebuffers[0]);
|
||||
expect(picks[0].values.u_scale).toBe(400);
|
||||
expect(fake.gl.bindFramebuffer).toHaveBeenLastCalledWith(GL.FRAMEBUFFER, null);
|
||||
expect(fake.enabled.has(GL.BLEND)).toBe(true);
|
||||
expect(fake.gl.clearColor).toHaveBeenCalledWith(0, 0, 0, 0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-041: answers -1 on empty sea', () => {
|
||||
const { r } = setup();
|
||||
r.draw(state());
|
||||
expect(r.pick(1, 1, true)).toBe(-1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-042: reuses the pick target while the size holds and rebuilds it on resize', () => {
|
||||
const { fake, r } = setup();
|
||||
r.draw(state());
|
||||
r.pick(1, 1, false);
|
||||
r.pick(2, 2, false);
|
||||
expect(fake.framebuffers).toHaveLength(1);
|
||||
expect(fake.gl.deleteFramebuffer).not.toHaveBeenCalled();
|
||||
const firstTex = fake.textures[fake.textures.length - 1];
|
||||
r.draw(state({ width: 400 }));
|
||||
r.pick(1, 1, false);
|
||||
expect(fake.framebuffers).toHaveLength(2);
|
||||
expect(fake.gl.deleteFramebuffer).toHaveBeenCalledWith(fake.framebuffers[0]);
|
||||
expect(fake.gl.deleteTexture).toHaveBeenCalledWith(firstTex);
|
||||
const sized = fake.gl.texImage2D.mock.calls.map((c) => [c[3], c[4]]);
|
||||
expect(sized).toContainEqual([1600, 1200]);
|
||||
expect(sized).toContainEqual([800, 1200]);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-043: draws loaded regions into the pick pass only when asked to', () => {
|
||||
const { fake, r } = setup();
|
||||
r.setWorld('w', layer(2, 1, 1));
|
||||
r.setRegion('DE', layer(4, 1, 1));
|
||||
r.draw(state({ regionKeys: ['DE', 'FR'], regionAlpha: 1 }));
|
||||
r.pick(1, 1, false);
|
||||
expect(fake.drawsWith(PICK_FS).map((d) => d.count)).toEqual([6]);
|
||||
r.pick(1, 1, true);
|
||||
expect(fake.drawsWith(PICK_FS).map((d) => d.count)).toEqual([6, 6, 12]);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-044: picks without a world when the frame names none that is loaded', () => {
|
||||
const { fake, r } = setup({ pixel: [3, 0, 0, 255] });
|
||||
r.draw(state({ worldKey: 'none' }));
|
||||
expect(r.pick(1, 1, false)).toBe(2);
|
||||
expect(fake.drawsWith(PICK_FS)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobeRenderer dispose', () => {
|
||||
it('FE-ATLAS2-RENDER-045: frees every world and region layer and forgets them', () => {
|
||||
const { fake, r } = setup();
|
||||
const w = layer(2, 1, 1);
|
||||
const reg = layer(3, 1, 1);
|
||||
r.setWorld('w', w);
|
||||
r.setRegion('DE', reg);
|
||||
r.dispose();
|
||||
expect(r.hasWorld('w')).toBe(false);
|
||||
expect(r.hasRegion('DE')).toBe(false);
|
||||
const deleted = deletedBuffers(fake);
|
||||
expect(deleted).toContain(fake.bufferOf(w.fill.ll));
|
||||
expect(deleted).toContain(fake.bufferOf(reg.borders.seg));
|
||||
// World and region: fill, pick, coast and borders each; then the quad.
|
||||
expect(fake.gl.deleteVertexArray).toHaveBeenCalledTimes(9);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-048: gives back the programs, textures and shared buffers too, so a revisit leaks nothing', () => {
|
||||
const { fake, r } = setup();
|
||||
r.dispose();
|
||||
expect(fake.gl.deleteProgram).toHaveBeenCalledTimes(5);
|
||||
// The status and fx textures; no pick texture before the first pick.
|
||||
expect(fake.gl.deleteTexture).toHaveBeenCalledTimes(2);
|
||||
expect(fake.gl.deleteFramebuffer).not.toHaveBeenCalled();
|
||||
expect(fake.gl.deleteBuffer).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('globe shaders', () => {
|
||||
it('FE-ATLAS2-RENDER-046: every shader is GLSL ES 3.00 with high precision', () => {
|
||||
for (const src of [FILL_VS, FILL_FS, PICK_FS, LINE_VS, LINE_FS, SKY_VS, SKY_FS, RIM_FS]) {
|
||||
expect(src.startsWith('#version 300 es\n')).toBe(true);
|
||||
expect(src).toContain('precision highp float;');
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-047: the fill and line vertex shaders share the projection the picker relies on', () => {
|
||||
for (const src of [FILL_VS, LINE_VS]) {
|
||||
expect(src).toContain('vec4 project(vec2 ll, vec2 ref)');
|
||||
expect(src).toContain('uniform vec2 u_center;');
|
||||
}
|
||||
// pick() subtracts one again: id 0 stays "nothing here".
|
||||
expect(PICK_FS).toContain('int id = v_fid + 1;');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,626 @@
|
||||
/**
|
||||
* 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';
|
||||
|
||||
const STATUS_TEX_W = 256;
|
||||
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;
|
||||
/** Countries whose regions show at full strength at every zoom (the regions view). */
|
||||
pinnedRegions?: ReadonlySet<string>;
|
||||
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 quadBuf: WebGLBuffer | null = null;
|
||||
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();
|
||||
this.quadBuf = b;
|
||||
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), regions loaded, visited regions. */
|
||||
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.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);
|
||||
}
|
||||
// A pinned country's regions show whatever the zoom; the rest fade in with it.
|
||||
const pinnedKey = (k: string) => !!s.pinnedRegions?.has(k.slice(0, k.indexOf(':')));
|
||||
const fillAlpha = (k: string) => (pinnedKey(k) ? 1 : s.regionAlpha);
|
||||
const regionsOn = s.regionKeys.some((k) => this.regions.has(k) && fillAlpha(k) > 0.001);
|
||||
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);
|
||||
for (const k of s.regionKeys) {
|
||||
const r = this.regions.get(k);
|
||||
if (!r) continue;
|
||||
gl.uniform1f(p.u.u_layerAlpha, fillAlpha(k));
|
||||
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) {
|
||||
for (const k of s.regionKeys) {
|
||||
const r = this.regions.get(k);
|
||||
if (!r) continue;
|
||||
// Zoomed out, a pinned country's inner borders stay faint, so it does not turn into a web.
|
||||
const c = [...th.regionBorder];
|
||||
c[3] *= pinnedKey(k) ? Math.max(s.regionAlpha, 0.45) : s.regionAlpha;
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives back everything this renderer put on the GPU. The context itself is
|
||||
* left alive: React mounts twice in development and the second engine takes
|
||||
* over the same canvas, so whatever stayed behind here would pile up on it
|
||||
* with every visit to the Atlas.
|
||||
*/
|
||||
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();
|
||||
const freeLines = (l: GpuLines) => {
|
||||
for (const b of l.buffers) gl.deleteBuffer(b);
|
||||
gl.deleteVertexArray(l.vao);
|
||||
};
|
||||
if (this.ocean) {
|
||||
freeLines(this.ocean);
|
||||
gl.deleteVertexArray(this.ocean.pickVao);
|
||||
this.ocean = null;
|
||||
}
|
||||
for (const a of this.arcs.values()) freeLines(a);
|
||||
this.arcs.clear();
|
||||
if (this.outline) freeLines(this.outline.gpu);
|
||||
this.outline = null;
|
||||
if (this.pickTex) gl.deleteTexture(this.pickTex);
|
||||
if (this.pickFbo) gl.deleteFramebuffer(this.pickFbo);
|
||||
this.pickTex = null;
|
||||
this.pickFbo = null;
|
||||
gl.deleteTexture(this.statusTex);
|
||||
gl.deleteTexture(this.fxTex);
|
||||
gl.deleteVertexArray(this.quad);
|
||||
if (this.quadBuf) gl.deleteBuffer(this.quadBuf);
|
||||
gl.deleteBuffer(this.cornerBuf);
|
||||
for (const p of [this.fillP, this.pickP, this.lineP, this.skyP, this.rimP]) gl.deleteProgram(p.prog);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
// FE-ATLAS2-RENDER-300 to FE-ATLAS2-RENDER-312: the sky around the globe, the moon in its phase and the
|
||||
// shooting stars, on their own timer and on demand.
|
||||
import { act, render } from '@testing-library/react';
|
||||
import { createRef, type RefObject } from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { GlobeEngine } from './GlobeEngine';
|
||||
import GlobeSky, { type GlobeSkyHandle } from './GlobeSky';
|
||||
import { smoothstep } from './globeMath';
|
||||
|
||||
const SYNODIC_MS = 29.530588853 * 86400000;
|
||||
const NEW_MOON = Date.UTC(2000, 0, 6, 18, 14);
|
||||
|
||||
/** A moment at this share of a lunation after a known new moon. */
|
||||
function atPhase(phase: number): Date {
|
||||
return new Date(NEW_MOON + 300 * SYNODIC_MS + phase * SYNODIC_MS);
|
||||
}
|
||||
|
||||
interface AnimateCall {
|
||||
el: HTMLElement;
|
||||
keyframes: Keyframe[];
|
||||
options: KeyframeAnimationOptions;
|
||||
animation: { onfinish: (() => void) | null };
|
||||
}
|
||||
|
||||
let animations: AnimateCall[];
|
||||
let visibility: DocumentVisibilityState;
|
||||
|
||||
function fakeEngine(over: { t?: number; scale?: number; width?: number; height?: number } = {}): GlobeEngine {
|
||||
return {
|
||||
frame: { t: over.t ?? 0, k: 1, scale: over.scale ?? 100, originX: 400, originY: 300, centerLon: 0, centerLat: 0 },
|
||||
vp: { width: over.width ?? 800, height: over.height ?? 600, baseRadius: 1, globeY: 0, flatY: 0 },
|
||||
} as unknown as GlobeEngine;
|
||||
}
|
||||
|
||||
function mount(dark: boolean) {
|
||||
const ref = createRef<GlobeSkyHandle>();
|
||||
const utils = render(<GlobeSky ref={ref} dark={dark} />);
|
||||
const starHost = utils.container.children[0] as HTMLDivElement;
|
||||
const moon = utils.container.children[1] as HTMLDivElement;
|
||||
Object.defineProperty(starHost, 'clientWidth', { configurable: true, value: 1000 });
|
||||
Object.defineProperty(starHost, 'clientHeight', { configurable: true, value: 400 });
|
||||
return { ...utils, ref, starHost, moon };
|
||||
}
|
||||
|
||||
function handle(ref: RefObject<GlobeSkyHandle | null>): GlobeSkyHandle {
|
||||
if (!ref.current) throw new Error('GlobeSky handle missing');
|
||||
return ref.current;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ now: atPhase(0.2) });
|
||||
vi.spyOn(Math, 'random').mockReturnValue(0);
|
||||
animations = [];
|
||||
visibility = 'visible';
|
||||
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
|
||||
Object.defineProperty(HTMLElement.prototype, 'animate', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: function animate(this: HTMLElement, keyframes: Keyframe[], options: KeyframeAnimationOptions) {
|
||||
const animation = { onfinish: null as (() => void) | null };
|
||||
animations.push({ el: this, keyframes, options, animation });
|
||||
return animation;
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
Reflect.deleteProperty(document, 'visibilityState');
|
||||
Reflect.deleteProperty(HTMLElement.prototype, 'animate');
|
||||
});
|
||||
|
||||
describe('GlobeSky moon', () => {
|
||||
it('FE-ATLAS2-RENDER-300: draws a waxing crescent as a thin lit sliver', () => {
|
||||
const { container } = mount(true);
|
||||
const path = container.querySelector('path');
|
||||
expect(path?.getAttribute('d')).toBe('M 14 1 A 13 13 0 0 0 14 27 A 4.02 13 0 0 0 14 1 Z');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-301: mirrors the shadow for a waning crescent', () => {
|
||||
vi.setSystemTime(atPhase(0.8));
|
||||
const { container } = mount(true);
|
||||
expect(container.querySelector('path')?.getAttribute('d')).toBe(
|
||||
'M 14 1 A 13 13 0 0 1 14 27 A 4.02 13 0 0 1 14 1 Z'
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-302: bulges the shadow ellipse the other way for a gibbous moon', () => {
|
||||
vi.setSystemTime(atPhase(0.4));
|
||||
const { container } = mount(true);
|
||||
expect(container.querySelector('path')?.getAttribute('d')).toBe(
|
||||
'M 14 1 A 13 13 0 0 0 14 27 A 10.52 13 0 0 1 14 1 Z'
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-303: hides the moon in light mode', () => {
|
||||
const { ref, moon } = mount(false);
|
||||
act(() => handle(ref).layout(fakeEngine()));
|
||||
expect(moon.style.opacity).toBe('0');
|
||||
expect(moon.style.transform).toBe('');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-304: places the moon up and to the side of the globe, fully shown on the globe', () => {
|
||||
const { ref, moon } = mount(true);
|
||||
act(() => handle(ref).layout(fakeEngine({ t: 0, scale: 100, width: 800, height: 600 })));
|
||||
const d = Math.max(175, 600 * 0.42);
|
||||
const x = 400 + Math.cos(-0.65) * d * 1.25;
|
||||
const y = 300 + Math.sin(-0.65) * d * 0.62;
|
||||
expect(moon.style.transform).toBe(`translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -50%)`);
|
||||
expect(moon.style.opacity).toBe('0.95');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-305: keeps a zoomed-in globe clear of the moon and fades it as the map unrolls', () => {
|
||||
const { ref, moon } = mount(true);
|
||||
act(() => handle(ref).layout(fakeEngine({ t: 0.3, scale: 400 })));
|
||||
const d = 400 * 1.75;
|
||||
const x = 400 + Math.cos(-0.65) * d * 1.25;
|
||||
expect(moon.style.transform.startsWith(`translate3d(${x.toFixed(1)}px,`)).toBe(true);
|
||||
expect(Number(moon.style.opacity)).toBeCloseTo((1 - smoothstep(0.05, 0.6, 0.3)) * 0.95);
|
||||
act(() => handle(ref).layout(fakeEngine({ t: 1 })));
|
||||
expect(moon.style.opacity).toBe('0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobeSky shooting stars', () => {
|
||||
it('FE-ATLAS2-RENDER-306: a shooting star crosses the upper right of the sky and removes itself', () => {
|
||||
const { ref, starHost } = mount(true);
|
||||
act(() => handle(ref).shootingStar());
|
||||
const star = starHost.querySelector('.ag-shooting-star') as HTMLElement;
|
||||
expect(star).not.toBeNull();
|
||||
expect(star.style.left.endsWith('px')).toBe(true);
|
||||
expect(parseFloat(star.style.left)).toBeCloseTo(550);
|
||||
expect(parseFloat(star.style.top)).toBeCloseTo(20);
|
||||
expect(animations).toHaveLength(1);
|
||||
expect(animations[0].el).toBe(star);
|
||||
expect(animations[0].options.duration).toBe(1100);
|
||||
expect(animations[0].keyframes).toHaveLength(3);
|
||||
animations[0].animation.onfinish?.();
|
||||
expect(starHost.querySelector('.ag-shooting-star')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-307: there are no shooting stars in light mode', () => {
|
||||
const { ref, starHost } = mount(false);
|
||||
act(() => handle(ref).shootingStar());
|
||||
expect(starHost.children).toHaveLength(0);
|
||||
expect(animations).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-308: respects reduced motion', () => {
|
||||
// Once only: window.matchMedia is the setup's shared mock, and a lasting return value would
|
||||
// outlive this test (restoreAllMocks does not undo it) and silence every later star.
|
||||
vi.mocked(window.matchMedia).mockReturnValueOnce({ matches: true } as unknown as MediaQueryList);
|
||||
const { ref, starHost } = mount(true);
|
||||
act(() => handle(ref).shootingStar());
|
||||
expect(starHost.children).toHaveLength(0);
|
||||
});
|
||||
|
||||
/** Catches the sky's own schedule, so a test runs each planned star by hand. */
|
||||
function scheduled(): Array<{ run: () => void; ms: number }> {
|
||||
const plans: Array<{ run: () => void; ms: number }> = [];
|
||||
vi.spyOn(window, 'setTimeout').mockImplementation(((run: () => void, ms?: number) => {
|
||||
plans.push({ run, ms: ms ?? 0 });
|
||||
return plans.length;
|
||||
}) as unknown as typeof window.setTimeout);
|
||||
return plans;
|
||||
}
|
||||
|
||||
it('FE-ATLAS2-RENDER-309: sends a star of its own now and then while the page is in view', () => {
|
||||
const plans = scheduled();
|
||||
const { starHost } = mount(true);
|
||||
expect(plans).toHaveLength(1);
|
||||
// Math.random is 0 here: the shortest wait, forty seconds.
|
||||
expect(plans[0].ms).toBe(40_000);
|
||||
expect(starHost.children).toHaveLength(0);
|
||||
act(() => plans[0].run());
|
||||
expect(starHost.children).toHaveLength(1);
|
||||
// And the next one is planned right away.
|
||||
expect(plans).toHaveLength(2);
|
||||
act(() => plans[1].run());
|
||||
expect(starHost.children).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-310: skips its own star while the page is hidden but keeps the schedule', () => {
|
||||
const plans = scheduled();
|
||||
const { starHost } = mount(true);
|
||||
visibility = 'hidden';
|
||||
act(() => plans[0].run());
|
||||
expect(starHost.children).toHaveLength(0);
|
||||
expect(plans).toHaveLength(2);
|
||||
visibility = 'visible';
|
||||
act(() => plans[1].run());
|
||||
expect(starHost.children).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-311: schedules nothing in light mode', () => {
|
||||
mount(false);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-RENDER-312: stops its timer on unmount and when switching to light mode', () => {
|
||||
const { rerender, unmount } = mount(true);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
rerender(<GlobeSky dark={false} />);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
rerender(<GlobeSky dark />);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
unmount();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { forwardRef, useCallback, useEffect, 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;
|
||||
}
|
||||
|
||||
/** How long the sky waits between two shooting stars of its own, in ms. */
|
||||
const STAR_EVERY_MIN = 40_000;
|
||||
const STAR_EVERY_SPREAD = 60_000;
|
||||
|
||||
/**
|
||||
* What hangs in the sky around the globe: the moon in its real phase, and shooting
|
||||
* stars, now and then on their own and one whenever 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()), []);
|
||||
|
||||
const shootingStar = useCallback(() => {
|
||||
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]);
|
||||
|
||||
// Now and then a shooting star of its own, while the page is in view.
|
||||
useEffect(() => {
|
||||
if (!dark) return;
|
||||
let timer = 0;
|
||||
const next = () => {
|
||||
timer = window.setTimeout(
|
||||
() => {
|
||||
if (document.visibilityState === 'visible') shootingStar();
|
||||
next();
|
||||
},
|
||||
STAR_EVERY_MIN + Math.random() * STAR_EVERY_SPREAD
|
||||
);
|
||||
};
|
||||
next();
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [dark, shootingStar]);
|
||||
|
||||
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,
|
||||
}),
|
||||
[dark, shootingStar]
|
||||
);
|
||||
|
||||
// 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(235 235 237 / 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(245 245 245)" />
|
||||
<stop offset="1" stopColor="rgb(176 176 180)" />
|
||||
</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(8 8 9)" opacity="0.88" />
|
||||
</svg>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export default GlobeSky;
|
||||
@@ -0,0 +1,142 @@
|
||||
// FE-ATLAS2-VIEWB-020 to FE-ATLAS2-VIEWB-029: the globe's stat cards, the medal and the Dawarich mark.
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { BadgeMotif } from '@trek/shared';
|
||||
import { Flag, Globe } from 'lucide-react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import BadgeMedal from './BadgeMedal';
|
||||
import DawarichMark from './DawarichMark';
|
||||
import GlobeStatsBar from './GlobeStatsBar';
|
||||
|
||||
describe('GlobeStatsBar', () => {
|
||||
it('FE-ATLAS2-VIEWB-020: a stat with an action is a button, one without is plain', () => {
|
||||
const onClick = vi.fn();
|
||||
const { container } = render(
|
||||
<GlobeStatsBar
|
||||
stats={[
|
||||
{ key: 'countries', icon: Flag, value: 12, label: 'Countries', onClick },
|
||||
{ key: 'continents', icon: Globe, value: 3, label: 'Continents' },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
const btn = screen.getByRole('button');
|
||||
expect(btn).toHaveTextContent('12');
|
||||
expect(btn).toHaveTextContent('Countries');
|
||||
fireEvent.click(btn);
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByText('Continents').closest('button')).toBeNull();
|
||||
expect(screen.getByText('3')).toBeInTheDocument();
|
||||
expect(container.firstElementChild?.className).toContain('bottom-[22px]');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-VIEWB-021: the bar takes a caller position instead of the corner', () => {
|
||||
const { container } = render(<GlobeStatsBar stats={[]} className="end-0 top-0" />);
|
||||
expect(container.firstElementChild?.className).toContain('end-0 top-0');
|
||||
expect(container.firstElementChild?.className).not.toContain('bottom-[22px]');
|
||||
expect(container.firstElementChild?.children).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BadgeMedal', () => {
|
||||
it('FE-ATLAS2-VIEWB-022: an earned medal has a full ring and its gradients are named after its id', () => {
|
||||
const { container } = render(<BadgeMedal id="x1" motif="first" tier="gold" earned />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toHaveAttribute('width', '92');
|
||||
expect(svg).toHaveAttribute('height', '104');
|
||||
expect(container.querySelector('#bm-x1-r')).not.toBeNull();
|
||||
const hex = container.querySelector('polygon');
|
||||
expect(hex).toHaveAttribute('stroke-width', '5');
|
||||
expect(hex).toHaveAttribute('stroke-opacity', '1');
|
||||
expect(hex).not.toHaveAttribute('stroke-dasharray');
|
||||
// No progress ring on an earned medal.
|
||||
expect(container.querySelectorAll('polygon')).toHaveLength(2);
|
||||
expect(container.querySelector('g')).toHaveAttribute('opacity', '1');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-VIEWB-023: a medal not yet earned is dashed, dim and draws its progress', () => {
|
||||
const { container } = render(
|
||||
<BadgeMedal id="p" motif="countries" tier="bronze" earned={false} progress={0.42} size={46} />
|
||||
);
|
||||
const polys = container.querySelectorAll('polygon');
|
||||
expect(polys).toHaveLength(3);
|
||||
expect(polys[0]).toHaveAttribute('stroke-dasharray', '4 3');
|
||||
expect(polys[0]).toHaveAttribute('stroke-width', '2');
|
||||
expect(polys[2]).toHaveAttribute('stroke-dasharray', '42 100');
|
||||
expect(container.querySelector('g')).toHaveAttribute('opacity', '0.38');
|
||||
expect(container.querySelector('svg')).toHaveAttribute('width', '46');
|
||||
expect(container.querySelector('svg')).toHaveAttribute('height', '52');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-VIEWB-024: a medal not earned and without progress draws no progress ring', () => {
|
||||
const { container } = render(<BadgeMedal id="z" motif="moon" tier="silver" earned={false} />);
|
||||
expect(container.querySelectorAll('polygon')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-VIEWB-025: the seven-continents motif lights seven points', () => {
|
||||
const { container } = render(<BadgeMedal id="s" motif="seven" tier="aurora" earned />);
|
||||
expect(container.querySelectorAll('circle[r="2.4"]')).toHaveLength(7);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-VIEWB-026: a stepped medal carries its label, smaller the longer it is', () => {
|
||||
const sizes: Array<[string, string]> = [
|
||||
['5', '15'],
|
||||
['100', '13'],
|
||||
['3/12', '11'],
|
||||
];
|
||||
for (const [label, size] of sizes) {
|
||||
const { container, unmount } = render(<BadgeMedal id="l" motif="countries" tier="gold" earned label={label} />);
|
||||
const text = container.querySelector('text');
|
||||
expect(text).toHaveTextContent(label);
|
||||
expect(text).toHaveAttribute('font-size', size);
|
||||
unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-VIEWB-027: a back side replaces the motif', () => {
|
||||
const { container } = render(
|
||||
<BadgeMedal id="b" motif="countries" tier="gold" earned label="5" back={<text data-testid="back">B</text>} />
|
||||
);
|
||||
expect(screen.getByTestId('back')).toBeInTheDocument();
|
||||
expect(container.querySelectorAll('text')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-VIEWB-028: every motif draws a symbol', () => {
|
||||
const motifs: BadgeMotif[] = [
|
||||
'first',
|
||||
'countries',
|
||||
'continents',
|
||||
'region',
|
||||
'earth',
|
||||
'moon',
|
||||
'flights',
|
||||
'longhaul',
|
||||
'airports',
|
||||
'dateline',
|
||||
'equator',
|
||||
'hemispheres',
|
||||
'tropics',
|
||||
'polar',
|
||||
'streak',
|
||||
'burst',
|
||||
'wish',
|
||||
'islands',
|
||||
];
|
||||
for (const motif of motifs) {
|
||||
const { container, unmount } = render(<BadgeMedal id={motif} motif={motif} tier="bronze" earned />);
|
||||
// The lucide symbol is an svg nested in the medal's own.
|
||||
expect(container.querySelectorAll('svg').length).toBeGreaterThan(1);
|
||||
unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('DawarichMark', () => {
|
||||
it('FE-ATLAS2-VIEWB-029: the mark sits two pixels larger than the icon size it stands for', () => {
|
||||
const { container, rerender } = render(<DawarichMark />);
|
||||
const box = container.firstElementChild as HTMLElement;
|
||||
expect(box.style.width).toBe('18px');
|
||||
expect(container.querySelector('img')).toHaveAttribute('width', '18');
|
||||
rerender(<DawarichMark size={30} />);
|
||||
expect((container.firstElementChild as HTMLElement).style.height).toBe('32px');
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', '/brands/dawarich.svg');
|
||||
});
|
||||
});
|
||||
@@ -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(22 22 24 / 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(244 244 245);
|
||||
--ag-muted: rgb(161 161 170);
|
||||
--ag-faint: rgb(113 113 122);
|
||||
--ag-accent: rgb(244 244 245);
|
||||
--ag-mint: rgb(161 161 170);
|
||||
--ag-label: rgb(235 235 237 / 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(4 4 5);
|
||||
}
|
||||
|
||||
html:not(.dark) .ag-btn {
|
||||
background: rgb(24 24 27 / 0.04);
|
||||
}
|
||||
|
||||
html:not(.dark) .ag-btn[data-on='1'] {
|
||||
background: rgb(24 24 27 / 0.12);
|
||||
border-color: rgb(24 24 27 / 0.4);
|
||||
}
|
||||
|
||||
html:not(.dark) .ag-bar {
|
||||
background: rgb(24 24 27 / 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(255 255 255 / 0.16);
|
||||
border-color: rgb(255 255 255 / 0.45);
|
||||
}
|
||||
|
||||
.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(255 255 255 / 0.35);
|
||||
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(255 255 255 / 0) 30%,
|
||||
rgb(255 255 255 / 0.18) 45%,
|
||||
rgb(255 255 255 / 0.14) 55%,
|
||||
rgb(255 255 255 / 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(255 255 255 / 0.7);
|
||||
}
|
||||
|
||||
@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(255 255 255 / 0.3) 0%, rgb(255 255 255 / 0.12) 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,368 @@
|
||||
// FE-ATLAS2-PAINT-101 to FE-ATLAS2-PAINT-120: the country and region names placed
|
||||
// over the globe, their collision rules and how their elements are reused.
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import type { AtlasMeshManifest, GlobeEngine, RegionIndex } from './GlobeEngine';
|
||||
import { placeLabels, type GlobeLabel } from './globeLabels';
|
||||
|
||||
type ManifestCountry = AtlasMeshManifest['countries'][number];
|
||||
type Feature = RegionIndex['features'][number];
|
||||
|
||||
interface FakeLabelEngine {
|
||||
manifest: { countries: ManifestCountry[] } | null;
|
||||
zoom: number;
|
||||
vp: { width: number; height: number };
|
||||
regionIndex: Map<string, RegionIndex>;
|
||||
regionAlpha: number;
|
||||
focus: string | null;
|
||||
/** Visibility by "x,y" of the anchor; 1 when not listed. */
|
||||
visibility: Map<string, number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A globe engine whose projection is the identity: an anchor [x, y] lands on
|
||||
* screen at x, y, so a test places labels in pixels directly.
|
||||
*/
|
||||
function fakeEngine(over: Partial<FakeLabelEngine> = {}) {
|
||||
const state: FakeLabelEngine = {
|
||||
manifest: { countries: [] },
|
||||
zoom: 1,
|
||||
vp: { width: 1000, height: 800 },
|
||||
regionIndex: new Map(),
|
||||
regionAlpha: 0,
|
||||
focus: null,
|
||||
visibility: new Map(),
|
||||
...over,
|
||||
};
|
||||
const engine = {
|
||||
get manifest() {
|
||||
return state.manifest;
|
||||
},
|
||||
get zoom() {
|
||||
return state.zoom;
|
||||
},
|
||||
get vp() {
|
||||
return state.vp;
|
||||
},
|
||||
get regionIndex() {
|
||||
return state.regionIndex;
|
||||
},
|
||||
get regionAlpha() {
|
||||
return state.regionAlpha;
|
||||
},
|
||||
focusCountry: () => state.focus,
|
||||
project: (lon: number, lat: number) => ({
|
||||
x: lon,
|
||||
y: lat,
|
||||
visible: state.visibility.get(`${lon},${lat}`) ?? 1,
|
||||
shade: 1,
|
||||
}),
|
||||
} as unknown as GlobeEngine;
|
||||
return { engine, state };
|
||||
}
|
||||
|
||||
function mc(a2: string | null, x: number, y: number, area = 1000, anchor = true): ManifestCountry {
|
||||
return { a2, a3: a2 ?? 'XXX', name: a2 ?? '', anchor: anchor ? [x, y] : null, bbox: [], area };
|
||||
}
|
||||
|
||||
function feat(over: Partial<Feature> = {}): Feature {
|
||||
return { code: null, name: null, nameEn: null, anchor: null, counted: true, ...over };
|
||||
}
|
||||
|
||||
function index(features: Feature[]): RegionIndex {
|
||||
return { bbox: [], counted: features.length, features, files: {} };
|
||||
}
|
||||
|
||||
const nameOf = (a2: string) => `Name ${a2}`;
|
||||
|
||||
let host: HTMLDivElement;
|
||||
let pool: GlobeLabel[];
|
||||
|
||||
beforeEach(() => {
|
||||
host = document.createElement('div');
|
||||
pool = [];
|
||||
});
|
||||
|
||||
/** The labels that show, by text. */
|
||||
function shownTexts(): string[] {
|
||||
return pool
|
||||
.filter((l) => l.el.style.opacity !== '0')
|
||||
.map((l) => l.el.textContent ?? '')
|
||||
.sort();
|
||||
}
|
||||
|
||||
function labelOf(text: string): GlobeLabel | undefined {
|
||||
return pool.find((l) => l.el.textContent === text && l.el.style.opacity !== '0');
|
||||
}
|
||||
|
||||
describe('placeLabels: country names', () => {
|
||||
it('FE-ATLAS2-PAINT-101: places nothing before the manifest has loaded', () => {
|
||||
const { engine } = fakeEngine({ manifest: null });
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(host.children).toHaveLength(0);
|
||||
expect(pool).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-102: names a large country in view at its anchor, in a fresh element on the host', () => {
|
||||
const { engine } = fakeEngine({ manifest: { countries: [mc('FR', 100, 200)] } });
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(pool).toHaveLength(1);
|
||||
const el = pool[0].el;
|
||||
expect(host.firstChild).toBe(el);
|
||||
expect(pool[0].key).toBe('FR');
|
||||
expect(el.className).toBe('atlas-globe-label text-caption');
|
||||
expect(el.textContent).toBe('Name FR');
|
||||
expect(el.dataset.region).toBe('');
|
||||
expect(el.style.transform).toBe('translate3d(100.0px, 200.0px, 0) translate(-50%, -50%)');
|
||||
expect(el.style.opacity).toBe('1');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-103: leaves out countries too small for the zoom, unless they are the user own', () => {
|
||||
// At zoom 1 a country needs 700 square degrees; one of the user's own needs 30 % of that.
|
||||
const countries = [mc('BE', 100, 100, 300), mc('LU', 400, 100, 300), mc('MT', 700, 100, 100)];
|
||||
const { engine } = fakeEngine({ manifest: { countries } });
|
||||
placeLabels(host, pool, engine, nameOf, (a2) => a2 === 'BE' || a2 === 'MT');
|
||||
expect(shownTexts()).toEqual(['Name BE']);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-104: zooming in brings smaller countries in', () => {
|
||||
const { engine, state } = fakeEngine({ manifest: { countries: [mc('BE', 100, 100, 300)] } });
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(shownTexts()).toEqual([]);
|
||||
state.zoom = 2;
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Name BE']);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-105: skips countries without a code, an anchor, a name, or out of view', () => {
|
||||
const countries = [
|
||||
mc(null, 100, 100),
|
||||
mc('AQ', 200, 100, 1000, false),
|
||||
mc('NO', 300, 100),
|
||||
// Past the margin left, right, above and below the view.
|
||||
mc('W1', -50, 300),
|
||||
mc('E1', 1050, 300),
|
||||
mc('N1', 500, -30),
|
||||
mc('S1', 500, 830),
|
||||
// Behind the limb.
|
||||
mc('BK', 600, 600),
|
||||
// Inside the margin: still named.
|
||||
mc('IN', -30, 400),
|
||||
];
|
||||
const { engine } = fakeEngine({ manifest: { countries }, visibility: new Map([['600,600', 0.1]]) });
|
||||
placeLabels(host, pool, engine, (a2) => (a2 === 'NO' ? null : a2));
|
||||
expect(shownTexts()).toEqual(['IN']);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-106: fades a name in as it turns from the limb and as region fills take over', () => {
|
||||
const { engine } = fakeEngine({
|
||||
manifest: { countries: [mc('FR', 100, 100)] },
|
||||
visibility: new Map([['100,100', 0.15]]),
|
||||
regionAlpha: 0.5,
|
||||
});
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(Number(pool[0].el.style.opacity)).toBeCloseTo(0.6 * (1 - 0.5 * 0.55), 6);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-107: of two overlapping names the larger country wins', () => {
|
||||
const { engine } = fakeEngine({ manifest: { countries: [mc('SM', 100, 100, 800), mc('IT', 110, 104, 3000)] } });
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Name IT']);
|
||||
expect(pool).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-108: the user own country outranks a larger neighbour', () => {
|
||||
const { engine } = fakeEngine({ manifest: { countries: [mc('CH', 100, 100, 1000), mc('DE', 110, 104, 3000)] } });
|
||||
placeLabels(host, pool, engine, nameOf, (a2) => a2 === 'CH');
|
||||
expect(shownTexts()).toEqual(['Name CH']);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-109: a name on screen keeps its place against a slightly larger one, not a much larger one', () => {
|
||||
const { engine, state } = fakeEngine({ manifest: { countries: [mc('AA', 100, 100, 1000)] } });
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
const first = pool[0].el;
|
||||
|
||||
state.manifest = { countries: [mc('AA', 100, 100, 1000), mc('BB', 104, 100, 1400)] };
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Name AA']);
|
||||
expect(labelOf('Name AA')?.el).toBe(first);
|
||||
|
||||
state.manifest = { countries: [mc('AA', 100, 100, 1000), mc('BB', 104, 100, 1600)] };
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Name BB']);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-110: a name that stays keeps its element and only moves', () => {
|
||||
const { engine, state } = fakeEngine({ manifest: { countries: [mc('FR', 100, 100)] } });
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
const el = pool[0].el;
|
||||
state.manifest = { countries: [mc('FR', 150.04, 120)] };
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(pool).toHaveLength(1);
|
||||
expect(pool[0].el).toBe(el);
|
||||
expect(el.style.transform).toBe('translate3d(150.0px, 120.0px, 0) translate(-50%, -50%)');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-111: a name that goes hides its element, and the next new name reuses it', () => {
|
||||
const { engine, state } = fakeEngine({ manifest: { countries: [mc('FR', 100, 100)] } });
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
const el = pool[0].el;
|
||||
|
||||
state.manifest = { countries: [] };
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(el.style.opacity).toBe('0');
|
||||
expect(shownTexts()).toEqual([]);
|
||||
|
||||
state.manifest = { countries: [mc('ES', 300, 300)] };
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(pool).toHaveLength(1);
|
||||
expect(host.children).toHaveLength(1);
|
||||
expect(pool[0].key).toBe('ES');
|
||||
expect(el.textContent).toBe('Name ES');
|
||||
expect(el.style.opacity).toBe('1');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-112: shows at most 150 names at once', () => {
|
||||
const countries: ManifestCountry[] = [];
|
||||
for (let i = 0; i < 170; i++) {
|
||||
countries.push(mc(`C${i}`, 20 + (i % 20) * 48, 20 + Math.floor(i / 20) * 30, 1000 + i));
|
||||
}
|
||||
const { engine } = fakeEngine({ manifest: { countries } });
|
||||
placeLabels(host, pool, engine, (a2) => a2);
|
||||
expect(pool).toHaveLength(150);
|
||||
// The largest win the cut.
|
||||
expect(labelOf('C169')).toBeDefined();
|
||||
expect(labelOf('C0')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('placeLabels: region names', () => {
|
||||
const US = mc('US', 500, 400, 9000);
|
||||
const usRegions = () =>
|
||||
index([
|
||||
feat({ code: 'US-KS', name: 'Kansas', anchor: [300, 300] }),
|
||||
feat({ code: null, name: 'Texas', nameEn: 'Texas (en)', anchor: [600, 500] }),
|
||||
feat({ code: 'US-AK', name: 'Alaska', anchor: null }),
|
||||
feat({ code: 'US-HI', name: 'Hawaii', anchor: [1200, 300] }),
|
||||
feat({ code: 'US-GU', name: 'Guam', anchor: [-10, 300] }),
|
||||
feat({ code: 'US-VI', name: 'Virgin', anchor: [300, -5] }),
|
||||
feat({ code: 'US-AS', name: 'Samoa', anchor: [300, 900] }),
|
||||
feat({ code: 'US-ME', name: 'Maine', anchor: [800, 100] }),
|
||||
]);
|
||||
|
||||
it('FE-ATLAS2-PAINT-113: from the wide-screen region zoom on, a country with regions names them instead of itself', () => {
|
||||
const { engine } = fakeEngine({
|
||||
manifest: { countries: [US, mc('CA', 900, 700, 9000)] },
|
||||
zoom: 18,
|
||||
regionIndex: new Map([['US', usRegions()]]),
|
||||
regionAlpha: 0.8,
|
||||
visibility: new Map([['800,100', 0.05]]),
|
||||
});
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Kansas', 'Name CA', 'Texas (en)']);
|
||||
const kansas = labelOf('Kansas');
|
||||
expect(kansas?.key).toBe('US:US-KS');
|
||||
expect(kansas?.el.dataset.region).toBe('1');
|
||||
expect(kansas?.el.style.opacity).toBe('0.8');
|
||||
expect(labelOf('Texas (en)')?.key).toBe('US:Texas');
|
||||
expect(labelOf('Name CA')?.el.dataset.region).toBe('');
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-114: below the region zoom the country keeps its own name', () => {
|
||||
const { engine } = fakeEngine({
|
||||
manifest: { countries: [US] },
|
||||
zoom: 17,
|
||||
regionIndex: new Map([['US', usRegions()]]),
|
||||
});
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Name US']);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-115: on a phone-wide view region names start earlier', () => {
|
||||
const { engine } = fakeEngine({
|
||||
manifest: { countries: [US] },
|
||||
zoom: 14,
|
||||
vp: { width: 600, height: 800 },
|
||||
regionIndex: new Map([['US', usRegions()]]),
|
||||
regionAlpha: 1,
|
||||
});
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Kansas', 'Texas (en)']);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-116: a region named by its plain name falls back to it, and one without any name shows empty', () => {
|
||||
const { engine } = fakeEngine({
|
||||
manifest: { countries: [] },
|
||||
zoom: 20,
|
||||
regionIndex: new Map([
|
||||
[
|
||||
'FR',
|
||||
index([
|
||||
feat({ code: 'FR-IDF', name: 'Île-de-France', anchor: [100, 100] }),
|
||||
feat({ code: 'FR-X', anchor: [400, 400] }),
|
||||
]),
|
||||
],
|
||||
]),
|
||||
regionAlpha: 1,
|
||||
});
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(pool.map((l) => l.el.textContent).sort()).toEqual(['', 'Île-de-France']);
|
||||
});
|
||||
|
||||
/** Two countries with one region each at nearly the same spot: only one of them can be named. */
|
||||
function rivals(focus: string | null, countries: ManifestCountry[]) {
|
||||
return fakeEngine({
|
||||
manifest: { countries },
|
||||
zoom: 20,
|
||||
focus,
|
||||
regionIndex: new Map([
|
||||
// Mexico's region is right in the middle of the view.
|
||||
['MX', index([feat({ code: 'MX-SON', name: 'Sonora', anchor: [500, 400] })])],
|
||||
['US', index([feat({ code: 'US-AZ', name: 'Arizona', anchor: [510, 404] })])],
|
||||
]),
|
||||
regionAlpha: 1,
|
||||
});
|
||||
}
|
||||
|
||||
it('FE-ATLAS2-PAINT-117: the regions of the country under the middle of the view come first', () => {
|
||||
const { engine } = rivals('US', [mc('US', 520, 410), mc('MX', 480, 420)]);
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Arizona']);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-118: a country under the middle without regions puts no country first, so the nearest region wins', () => {
|
||||
const { engine } = rivals('ES', [mc('US', 520, 410), mc('MX', 480, 420)]);
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Sonora']);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-119: over open water the country with regions whose anchor is nearest the middle comes first', () => {
|
||||
// US's anchor is the nearer one; Mexico's lies behind the limb.
|
||||
const near = rivals(null, [mc('US', 520, 410), mc('MX', 501, 401)]);
|
||||
near.state.visibility.set('501,401', 0);
|
||||
placeLabels(host, pool, near.engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Arizona']);
|
||||
|
||||
// No anchor near enough the middle (or none at all): nobody comes first.
|
||||
pool = [];
|
||||
const far = rivals(null, [mc('US', 950, 750), mc('MX', 0, 0, 1000, false)]);
|
||||
placeLabels(host, pool, far.engine, nameOf);
|
||||
expect(shownTexts()).toEqual(['Sonora']);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-120: shows at most 120 region names, leaving room for country names', () => {
|
||||
const features: Feature[] = [];
|
||||
for (let i = 0; i < 130; i++) {
|
||||
features.push(feat({ code: `R${i}`, name: `R${i}`, anchor: [30 + (i % 13) * 70, 30 + Math.floor(i / 13) * 30] }));
|
||||
}
|
||||
const { engine } = fakeEngine({
|
||||
manifest: { countries: [mc('FR', 500, 700, 5000)] },
|
||||
zoom: 20,
|
||||
regionIndex: new Map([['XX', index(features)]]),
|
||||
regionAlpha: 1,
|
||||
});
|
||||
placeLabels(host, pool, engine, nameOf);
|
||||
const regions = pool.filter((l) => l.el.dataset.region === '1' && l.el.style.opacity !== '0');
|
||||
expect(regions).toHaveLength(120);
|
||||
expect(labelOf('Name FR')).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* 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);
|
||||
// A name on screen keeps its place against a near equal one, so two labels
|
||||
// that overlap while the globe turns do not take turns frame by frame.
|
||||
const shown = new Set(pool.filter((l) => l.key && l.el.style.opacity !== '0').map((l) => l.key));
|
||||
const held = (c: Candidate) => (shown.has(c.key) ? (c.region ? c.rank + 3e5 : c.rank * 1.5) : c.rank);
|
||||
cands.sort((a, b) => held(b) - held(a));
|
||||
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++;
|
||||
}
|
||||
|
||||
// Every name keeps its own element while it shows; an element only takes a
|
||||
// new name once its old one is gone, so no label jumps to another's place.
|
||||
const wanted = new Set(chosen.map((c) => c.key));
|
||||
const byKey = new Map(pool.filter((l) => wanted.has(l.key)).map((l) => [l.key, l]));
|
||||
const free = pool.filter((l) => !wanted.has(l.key));
|
||||
for (const l of free) {
|
||||
if (l.el.style.opacity !== '0') l.el.style.opacity = '0';
|
||||
}
|
||||
for (const c of chosen) {
|
||||
let l = byKey.get(c.key);
|
||||
if (!l) {
|
||||
l = free.pop();
|
||||
if (!l) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'atlas-globe-label text-caption';
|
||||
host.appendChild(el);
|
||||
l = { el, key: '' };
|
||||
pool.push(l);
|
||||
}
|
||||
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,131 @@
|
||||
// FE-ATLAS2-PAINT-401 to FE-ATLAS2-PAINT-412: the edges of the globe projection the
|
||||
// main globeMath tests leave out (clamps, the far side, degenerate arcs).
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
arcSegments,
|
||||
frameParams,
|
||||
interpolateGreatCircle,
|
||||
latLimits,
|
||||
moonPhase,
|
||||
MORPH_END,
|
||||
morphOf,
|
||||
projectPoint,
|
||||
RAD,
|
||||
smoothstep,
|
||||
wrapPi,
|
||||
xSqueeze,
|
||||
type GlobeViewport,
|
||||
} from './globeMath';
|
||||
|
||||
const VP: GlobeViewport = { width: 1000, height: 800, baseRadius: 300, globeY: 300, flatY: 500 };
|
||||
|
||||
describe('globeMath edges', () => {
|
||||
it('FE-ATLAS2-PAINT-401: smoothstep clamps below and above its range and eases in between', () => {
|
||||
expect(smoothstep(0, 1, -2)).toBe(0);
|
||||
expect(smoothstep(0, 1, 3)).toBe(1);
|
||||
expect(smoothstep(0, 1, 0.5)).toBe(0.5);
|
||||
expect(smoothstep(0, 1, 0.25)).toBeCloseTo(0.15625);
|
||||
expect(morphOf(MORPH_END * 4)).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-402: wraps exactly pi onto minus pi and leaves small angles alone', () => {
|
||||
expect(wrapPi(Math.PI)).toBeCloseTo(-Math.PI);
|
||||
expect(wrapPi(-Math.PI)).toBeCloseTo(-Math.PI);
|
||||
expect(wrapPi(1)).toBe(1);
|
||||
expect(wrapPi(Math.PI * 4 + 0.5)).toBeCloseTo(0.5);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-403: moves the origin from the globe centre to the map centre as it unrolls', () => {
|
||||
const globe = frameParams({ lon: 20, lat: 10, zoom: 1 }, VP);
|
||||
expect(globe.t).toBe(0);
|
||||
expect(globe.k).toBe(1);
|
||||
expect(globe.originX).toBe(500);
|
||||
expect(globe.originY).toBe(300);
|
||||
expect(globe.scale).toBe(300);
|
||||
expect(globe.centerLon).toBeCloseTo(20 * RAD);
|
||||
expect(globe.centerLat).toBeCloseTo(10 * RAD);
|
||||
|
||||
const flat = frameParams({ lon: 20, lat: 10, zoom: MORPH_END }, VP);
|
||||
expect(flat.t).toBe(1);
|
||||
expect(flat.k).toBeCloseTo(0.0005);
|
||||
expect(flat.originY).toBe(500);
|
||||
expect(flat.scale).toBeCloseTo(300 * MORPH_END);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-404: hides a point past the antimeridian of its reference on the far side', () => {
|
||||
const f = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP);
|
||||
const p = projectPoint(-179, 0, f, 179, 0);
|
||||
expect(p.visible).toBe(-1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-405: shades full in the middle, dark at the limb, and evenly once flat', () => {
|
||||
const globe = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP);
|
||||
expect(projectPoint(0, 0, globe).shade).toBeCloseTo(1);
|
||||
expect(projectPoint(89.9, 0, globe).shade).toBeLessThan(0.01);
|
||||
const flat = frameParams({ lon: 0, lat: 0, zoom: MORPH_END }, VP);
|
||||
expect(projectPoint(80, 30, flat).shade).toBeCloseTo(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-406: never squeezes longitude more than 0.3 near the poles', () => {
|
||||
const f = frameParams({ lon: 0, lat: 85, zoom: MORPH_END }, VP);
|
||||
expect(xSqueeze(f)).toBeCloseTo(0.3);
|
||||
const globe = frameParams({ lon: 0, lat: 85, zoom: 1 }, VP);
|
||||
expect(xSqueeze(globe)).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-407: a great circle between one point and itself stays on that point', () => {
|
||||
expect(interpolateGreatCircle(0, 0, 0, 0, 0.5)).toEqual([0, 0]);
|
||||
const [lon, lat] = interpolateGreatCircle(13.4, 52.5, 13.4, 52.5, 0.5);
|
||||
expect(lon).toBeCloseTo(13.4);
|
||||
expect(lat).toBeCloseTo(52.5);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-408: a great circle starts and ends on its airports', () => {
|
||||
const [lon0, lat0] = interpolateGreatCircle(8.57, 50.03, -73.78, 40.64, 0);
|
||||
const [lon1, lat1] = interpolateGreatCircle(8.57, 50.03, -73.78, 40.64, 1);
|
||||
expect(lon0).toBeCloseTo(8.57);
|
||||
expect(lat0).toBeCloseTo(50.03);
|
||||
expect(lon1).toBeCloseTo(-73.78);
|
||||
expect(lat1).toBeCloseTo(40.64);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-409: no routes give no segments, and the default cuts each arc in 48', () => {
|
||||
const none = arcSegments([]);
|
||||
expect(none.count).toBe(0);
|
||||
expect(none.data).toHaveLength(0);
|
||||
const two = arcSegments([
|
||||
{ a: [0, 0], b: [10, 0] },
|
||||
{ a: [20, 0], b: [30, 0] },
|
||||
]);
|
||||
expect(two.count).toBe(96);
|
||||
// The second arc starts at its own first airport.
|
||||
expect(two.data[48 * 8]).toBeCloseTo(20 * RAD);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-410: a route to the same airport still lifts by the minimum peak', () => {
|
||||
const { data, count } = arcSegments([{ a: [5, 5], b: [5, 5] }], 2);
|
||||
expect(count).toBe(2);
|
||||
// Lift at the middle of the arc is the minimum peak.
|
||||
expect(data[5]).toBeCloseTo(0.015);
|
||||
expect(data[0]).toBeCloseTo(5 * RAD);
|
||||
expect(data[2]).toBeCloseTo(5 * RAD);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-411: knows the moon phase before its reference new moon too', () => {
|
||||
const old = moonPhase(new Date(Date.UTC(1999, 0, 2)));
|
||||
expect(old.phase).toBeGreaterThanOrEqual(0);
|
||||
expect(old.phase).toBeLessThan(1);
|
||||
expect(old.lit).toBeGreaterThan(0.95);
|
||||
const ref = moonPhase(new Date(Date.UTC(2000, 0, 6, 18, 14)));
|
||||
expect(ref.phase).toBe(0);
|
||||
expect(ref.lit).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-ATLAS2-PAINT-412: an off-centre flat map gets different southern and northern limits', () => {
|
||||
const [south, north] = latLimits(MORPH_END, VP);
|
||||
const scale = VP.baseRadius * MORPH_END;
|
||||
expect(north).toBeCloseTo(90 - VP.flatY / scale / RAD);
|
||||
expect(south).toBeCloseTo(-90 + (VP.height - VP.flatY) / scale / RAD);
|
||||
expect(north - south).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
angularDistance,
|
||||
arcSegments,
|
||||
frameParams,
|
||||
interpolateGreatCircle,
|
||||
latLimits,
|
||||
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);
|
||||
});
|
||||
|
||||
describe('latLimits', () => {
|
||||
it('lets the globe tilt to 80 degrees either way', () => {
|
||||
expect(latLimits(1, VP)).toEqual([-80, 80]);
|
||||
});
|
||||
|
||||
it('keeps the cut edges of the flat map off the screen', () => {
|
||||
const zoom = MORPH_END * 2;
|
||||
const [south, north] = latLimits(zoom, VP);
|
||||
const scale = VP.baseRadius * zoom;
|
||||
// At the northern limit the top of the screen shows exactly the pole, and no further.
|
||||
expect(north + VP.flatY / scale / (Math.PI / 180)).toBeCloseTo(90);
|
||||
expect(south - (VP.height - VP.flatY) / scale / (Math.PI / 180)).toBeCloseTo(-90);
|
||||
});
|
||||
|
||||
it('holds a flat map lower than the screen in the middle', () => {
|
||||
const [south, north] = latLimits(MORPH_END, { ...VP, height: 4000, flatY: 2000 });
|
||||
expect(south).toBeCloseTo(0);
|
||||
expect(north).toBeCloseTo(0);
|
||||
});
|
||||
|
||||
it('narrows the range as the globe unrolls', () => {
|
||||
const half = (MORPH_START + MORPH_END) / 2;
|
||||
const [, mid] = latLimits(half, VP);
|
||||
const [, flat] = latLimits(MORPH_END, VP);
|
||||
expect(mid).toBeLessThan(80);
|
||||
expect(mid).toBeGreaterThan(flat);
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user