mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 03:50:30 +00:00
Compare commits
236 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 49b9ffc77d | |||
| 7006891ce0 | |||
| 4d01439c75 | |||
| adb6a2c80d | |||
| 1824cc77ec | |||
| 9e2805fc89 | |||
| 77380ea5cf | |||
| 9956c58dd5 | |||
| 3f38621024 | |||
| 2f7b8357ce | |||
| 6861687b1f | |||
| 8fc9fe7945 | |||
| f668eee227 | |||
| 711015d5fd | |||
| 6ebd5cf0c7 | |||
| 8ab7547edf | |||
| f599892a4b | |||
| 1436cec35c | |||
| fe90502955 | |||
| 0431741ad7 | |||
| fa99940945 | |||
| 09316025c3 | |||
| 100313cfa9 | |||
| 411ec4af59 | |||
| ec7f5e0585 | |||
| 8e38749bc3 | |||
| 2c17edd74c | |||
| c5e2afc21b | |||
| 502e6916d9 | |||
| 61674cf918 | |||
| ac01925be7 | |||
| 99465d04de | |||
| 73a7c4843b | |||
| 6e919696bb | |||
| d32cfb3635 | |||
| 31c9f40550 | |||
| 7ae4dcba51 | |||
| daa4e1dfcf | |||
| 9a7bce6fd8 | |||
| 0834d4f8fe | |||
| d8c28c9998 | |||
| 76ff6e15b1 | |||
| 3e0a2ef8ed | |||
| fd35f79c36 | |||
| 294a386d23 | |||
| ee79413653 | |||
| ec08915a16 | |||
| 40f9c020bb | |||
| 684a3bf5f5 | |||
| 26122a4208 | |||
| 9dc80760f7 | |||
| 090db8519d | |||
| efc55ac700 | |||
| 85b773420c | |||
| 771dab7c35 | |||
| ca7cdcebcc | |||
| 6bc27a259b | |||
| a2d9c2416d | |||
| fd1942afab | |||
| 23eabe1499 | |||
| bcc82db7bd | |||
| 26b220470a | |||
| cdc31967b2 | |||
| 4a435df6e4 | |||
| 21f4f7d5de | |||
| e3d195896c | |||
| 911bd825c1 | |||
| 81628d78ee | |||
| 69e791206e | |||
| e66330e226 | |||
| c970245e0d | |||
| cc0fe6ce2b | |||
| 39346ceca7 | |||
| 6dfba51f21 | |||
| 3973741509 | |||
| 3eac508baf | |||
| 7f6f2eb97c | |||
| f2cfbc4041 | |||
| 636fc7d0a6 | |||
| adcda60f7d | |||
| e8f808b67f | |||
| 70108e5694 | |||
| c75fb22289 | |||
| 621b2f17df | |||
| bc6728678b | |||
| 6040b60e86 | |||
| 2edf5f807a | |||
| fd864cc441 | |||
| b004d3b88e | |||
| 9b1bd6e435 | |||
| 73f3aa8309 | |||
| 82195c7418 | |||
| 9fd77b04fa | |||
| f1ea716305 | |||
| da1a02e7a8 | |||
| 9808e113e4 | |||
| 13e81c04ab | |||
| fd42d06d55 | |||
| e6f4f7a5f3 | |||
| 9497b586b7 | |||
| 77d90be4f8 | |||
| a884539a2b | |||
| 633df91bd6 | |||
| dd98469a02 | |||
| 223a7605ed | |||
| 0e04eeaf9a | |||
| aa77e21d4b | |||
| 8c8cfb5d5d | |||
| 9eeb59997e | |||
| 8179d7d707 | |||
| f211a1c614 | |||
| f42ef5246c | |||
| e1a5864406 | |||
| 62c03d71bf | |||
| f4ce2c2bd0 | |||
| d643f8c329 | |||
| 1b270806a1 | |||
| 2d7392c4c0 | |||
| a9cdb2f91c | |||
| 2983971c8b | |||
| e6a0a39a51 | |||
| 87612c0c79 | |||
| ff57883e3d | |||
| cd1a3fd433 | |||
| 377f22972b | |||
| fff7d123f6 | |||
| bedb70c479 | |||
| 3b8270edc3 | |||
| 6137aaf716 | |||
| 97a3389409 | |||
| 95ade9cbb2 | |||
| c4c278d2f3 | |||
| 2cb1964863 | |||
| 876cc5e0f0 | |||
| caae538056 | |||
| 1cebddac0e | |||
| 78bfa8183a | |||
| 43af349391 | |||
| 9c35343d9d | |||
| b0b1986377 | |||
| f11f021e15 | |||
| 6e7336b8d7 | |||
| 927fcab67f | |||
| c51f4f78bb | |||
| 12f4a40d7c | |||
| 3a6e91e26b | |||
| 680ce7324a | |||
| f5fbd60b5e | |||
| 8c1395c8f1 | |||
| 19bfa77ace | |||
| 2fb041a428 | |||
| be1983c9a4 | |||
| 2288487fe1 | |||
| b2384892a8 | |||
| 43e30ca28e | |||
| 42f0705f07 | |||
| e97dbc89c9 | |||
| 76dfbe0a00 | |||
| 424fa538e0 | |||
| 863ff62b6c | |||
| e2b0910e28 | |||
| cf9172f9e7 | |||
| 0e911608af | |||
| 95d067ad6d | |||
| ba043cb1c0 | |||
| 3a4c523509 | |||
| 057748c47a | |||
| e4457ed9eb | |||
| f430cbe59e | |||
| 5316362e9e | |||
| 900f2bfc30 | |||
| b7c8f0629c | |||
| 45fef1077a | |||
| ddb42ecf0a | |||
| 09295781f4 | |||
| 5938609f69 | |||
| d3cd484519 | |||
| 410d2393e0 | |||
| 44b6340be5 | |||
| 2f3dc4ea79 | |||
| af861e5816 | |||
| c1bbe27ac6 | |||
| 11f4373076 | |||
| f57fb7f9de | |||
| 96f2427518 | |||
| 3f51153dcc | |||
| fc37eb95d1 | |||
| 55607ff2f9 | |||
| 1ea08dcf0a | |||
| c6f6dd2d57 | |||
| 579df97bba | |||
| aa2f7ca8b4 | |||
| 17c9c0758f | |||
| 7340087353 | |||
| 910c98b971 | |||
| b144781e9f | |||
| a26db47cb6 | |||
| 9e5379d092 | |||
| 693acd5580 | |||
| c3f6177be1 | |||
| 60642cc18b | |||
| 54b843ae29 | |||
| 633e9bcdc1 | |||
| eab501925f | |||
| 2630d7e8ec | |||
| 116ba52fbb | |||
| e5fb6d9107 | |||
| 98529bc84c | |||
| 4a3ad562a7 | |||
| 518287ff12 | |||
| 0cdfb9eb42 | |||
| 4d0067a455 | |||
| 66d4431d26 | |||
| 293a48c26a | |||
| 80fca10784 | |||
| 830cd6e3b5 | |||
| 0f338d5484 | |||
| a99cd40f4d | |||
| f3ea50b17b | |||
| 2e3762afe1 | |||
| 17b47b38b9 | |||
| 494c848ec9 | |||
| c203b0a597 | |||
| b36fefdf5d | |||
| 8611359f7c | |||
| c8e48460b6 | |||
| 5ecf3001af | |||
| 2c5beee849 | |||
| a3f6635633 | |||
| 33d074c786 | |||
| e952586f60 | |||
| 35c0cd35ef | |||
| a1d753a975 | |||
| 35dbcc2103 | |||
| 3c054fffa0 | |||
| c1bad1204c |
@@ -0,0 +1,156 @@
|
||||
name: Set up Node and the workspaces
|
||||
description: >-
|
||||
Node from .nvmrc, the workspace dependencies from an exact cache or npm ci,
|
||||
and optionally shared/dist from a cache or a build. Runs after checkout.
|
||||
|
||||
# A local action, so it is versioned with the workflow that calls it and needs
|
||||
# no SHA pin. scripts/ci/changed-areas.mjs counts .github/actions/ like
|
||||
# test.yml: a change here runs everything.
|
||||
#
|
||||
# node_modules is restored only on an exact key: the runner image, the scope,
|
||||
# the Node ABI, the lockfile and every workspace package.json. There are no
|
||||
# restore-keys, so a hit is the tree npm ci would build and a miss is a plain
|
||||
# npm ci. The package.json files are in the key because npm ci is also the
|
||||
# check that they agree with the lockfile: an edited range without a fresh
|
||||
# lockfile misses the cache and fails the install, as it did when every job
|
||||
# ran npm ci. Only pushes to dev and main save, the npm download cache
|
||||
# included, so pull requests read what their base left and cannot evict it or
|
||||
# fill the repository's cache quota with entries of their own.
|
||||
|
||||
inputs:
|
||||
scope:
|
||||
description: >-
|
||||
Which workspaces to install: full (npm ci), client (shared and client)
|
||||
or shared (shared alone).
|
||||
required: true
|
||||
build-shared:
|
||||
description: "'true' to restore shared/dist, or build it on a miss."
|
||||
required: false
|
||||
default: 'false'
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
|
||||
# ImageOS and ImageVersion name the runner image, whose system libraries
|
||||
# the native modules were built against. They live in the runner's
|
||||
# environment, not in the env context, so the key is put together here. A
|
||||
# job in a container has neither; the container's OS release stands in,
|
||||
# and that job's tree is kept apart from the runner's.
|
||||
- name: Work out the cache keys
|
||||
id: keys
|
||||
shell: bash
|
||||
env:
|
||||
SCOPE: ${{ inputs.scope }}
|
||||
DEPS: ${{ hashFiles('.nvmrc', 'package-lock.json', 'package.json', 'client/package.json', 'server/package.json', 'shared/package.json') }}
|
||||
SHARED: ${{ hashFiles('shared/src/**', 'shared/package.json', 'shared/tsconfig*.json', 'shared/tsdown.config.ts', 'package-lock.json') }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
case "$SCOPE" in
|
||||
full | client | shared) ;;
|
||||
*) echo "::error::scope must be full, client or shared, not '$SCOPE'"; exit 1 ;;
|
||||
esac
|
||||
if [ -n "${ImageOS:-}" ]; then
|
||||
image="$ImageOS-${ImageVersion:-unknown}"
|
||||
else
|
||||
image="container-$(. /etc/os-release && echo "$ID$VERSION_ID")"
|
||||
fi
|
||||
abi="$(node -p process.versions.modules)"
|
||||
echo "nm=nm-$RUNNER_OS-$image-$SCOPE-node$abi-$DEPS" >> "$GITHUB_OUTPUT"
|
||||
echo "sd=sd-$RUNNER_OS-$SHARED" >> "$GITHUB_OUTPUT"
|
||||
echo "save=${{ github.event_name == 'push' && (github.ref == 'refs/heads/dev' || github.ref == 'refs/heads/main') }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Restore node_modules
|
||||
id: nm
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
server/node_modules
|
||||
client/node_modules
|
||||
shared/node_modules
|
||||
key: ${{ steps.keys.outputs.nm }}
|
||||
|
||||
# The npm download cache only matters when npm ci runs, so it is restored
|
||||
# only then. It may fall back to an older lockfile's cache: npm ci checks
|
||||
# every tarball against the lockfile's integrity hash and fetches what is
|
||||
# missing, so a stale entry only costs downloads.
|
||||
- name: Restore the npm download cache
|
||||
id: npm
|
||||
if: steps.nm.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
|
||||
restore-keys: npm-${{ runner.os }}-
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.nm.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
env:
|
||||
SCOPE: ${{ inputs.scope }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# better-sqlite3 ships no prebuilt binary and compiles on install. The
|
||||
# hosted runners carry a compiler; the Playwright container of the e2e
|
||||
# jobs does not, so on a cache miss there it gets one first. A hit,
|
||||
# the usual case once a push to dev has saved the container's key,
|
||||
# never reaches this step.
|
||||
if ! command -v make >/dev/null || ! command -v g++ >/dev/null; then
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
timeout 300 apt-get update -qq
|
||||
timeout 300 apt-get install -y -qq --no-install-recommends make g++
|
||||
fi
|
||||
case "$SCOPE" in
|
||||
full) npm ci ;;
|
||||
# The scoped install keeps @testing-library/dom (a peer of
|
||||
# @testing-library/react) in the tree.
|
||||
client) npm ci --workspace shared --workspace client ;;
|
||||
shared) npm ci --workspace shared ;;
|
||||
esac
|
||||
|
||||
- name: Save node_modules
|
||||
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
|
||||
uses: actions/cache/save@v6
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
server/node_modules
|
||||
client/node_modules
|
||||
shared/node_modules
|
||||
key: ${{ steps.keys.outputs.nm }}
|
||||
|
||||
# Only a full install saves the download cache, so the entry holds every
|
||||
# tarball; a scoped job that finished first would otherwise claim the key
|
||||
# with part of the tree and no later run would fill it.
|
||||
- name: Save the npm download cache
|
||||
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true' && steps.npm.outputs.cache-hit != 'true' && inputs.scope == 'full'
|
||||
uses: actions/cache/save@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
# The key holds every input of the build: the sources, the package and
|
||||
# build configs, and the lockfile that pins tsdown and zod.
|
||||
- name: Restore shared/dist
|
||||
id: sd
|
||||
if: inputs.build-shared == 'true'
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: shared/dist
|
||||
key: ${{ steps.keys.outputs.sd }}
|
||||
|
||||
- name: Build shared
|
||||
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
run: npm run build --workspace=shared
|
||||
|
||||
- name: Save shared/dist
|
||||
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
|
||||
uses: actions/cache/save@v6
|
||||
with:
|
||||
path: shared/dist
|
||||
key: ${{ steps.keys.outputs.sd }}
|
||||
+11
-1
@@ -7,8 +7,11 @@
|
||||
# enforce-target-branch.yml moves those onto dev.
|
||||
#
|
||||
# Every PR runs test.yml like any other, so ci-ok decides whether it can
|
||||
# merge. Dependabot runs get no Actions secrets, so s3-contract and the Sonar
|
||||
# merge. Dependabot runs get no Actions secrets, so server-s3 and the Sonar
|
||||
# scan skip themselves on these PRs and ci-ok counts the skip as passed.
|
||||
# A bump of @playwright/test also needs the Playwright container tag and
|
||||
# digest in test.yml's client-e2e moved by hand; workflow-jobs.test.mjs
|
||||
# fails the PR until they match.
|
||||
version: 2
|
||||
updates:
|
||||
# The root lockfile covers the client, server and shared workspaces.
|
||||
@@ -25,6 +28,13 @@ updates:
|
||||
groups:
|
||||
npm-minor-and-patch:
|
||||
update-types: [minor, patch]
|
||||
ignore:
|
||||
# TypeScript 7 is the native compiler and has no JavaScript API yet:
|
||||
# typescript-eslint, the coverage instrumenter and the Postgres probe all
|
||||
# call into it (readConfigFile, ScriptTarget). It moves by hand once the
|
||||
# tooling supports it.
|
||||
- dependency-name: typescript
|
||||
update-types: [version-update:semver-major]
|
||||
|
||||
# plugin-sdk is standalone with a lockfile of its own and ships to npm.
|
||||
- package-ecosystem: npm
|
||||
|
||||
@@ -18,9 +18,16 @@ jobs:
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
|
||||
# shared's ESLint and Prettier plugins are its own devDependencies, and
|
||||
# the format ratchet in scripts/lib/ resolves prettier from the root, so
|
||||
# shared plus the root is the whole tree these checks read. npm ci
|
||||
# installs exactly what the lockfile says, where npm install could
|
||||
# resolve anew.
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
run: npm ci --workspace shared --include-workspace-root
|
||||
|
||||
- name: Run lint & format check
|
||||
# Both are check-only: lint used to run eslint --fix, which rewrote the
|
||||
|
||||
@@ -10,6 +10,13 @@ permissions:
|
||||
#
|
||||
# Unsigned on purpose: signing and store uploads need secrets that fork PRs do
|
||||
# not get, and belong in a release workflow of their own.
|
||||
#
|
||||
# package-lock.json is not a trigger: every dependency bump touches it, and a
|
||||
# Mac build per bump only held the queue. The shells link nothing but the
|
||||
# @capacitor/* packages, all declared in client/package.json, and a Dependabot
|
||||
# bump of one of them raises the range there too, so it still runs. The client
|
||||
# typecheck and the watch and widget snapshot tests run in test.yml on every
|
||||
# change under client/.
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
@@ -24,7 +31,6 @@ on:
|
||||
- 'client/scripts/check-store-metadata.mjs'
|
||||
- 'client/fastlane/**'
|
||||
- 'client/package.json'
|
||||
- 'package-lock.json'
|
||||
- 'shared/src/i18n/*/native.ts'
|
||||
- '.github/workflows/native.yml'
|
||||
workflow_dispatch:
|
||||
@@ -182,34 +188,6 @@ jobs:
|
||||
path: client/ios/WidgetPreviews/out
|
||||
retention-days: 14
|
||||
|
||||
# The watch's half in the UI (client/src/native/watch.ts): the snapshot it
|
||||
# builds and the ticks it takes back, typechecked and tested here as well,
|
||||
# so a change to the bridge is checked next to the Swift that reads it.
|
||||
watch-bridge:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- name: Install
|
||||
run: npm ci --workspace=shared --workspace=client
|
||||
|
||||
- name: Build shared
|
||||
run: npm run build --workspace=shared
|
||||
|
||||
- name: Typecheck the client
|
||||
working-directory: client
|
||||
run: npm run typecheck
|
||||
|
||||
- name: Test the widget and watch snapshots
|
||||
working-directory: client
|
||||
run: npx vitest run src/native/watch.test.ts src/native/widgets.test.ts src/native/widgetExtras.test.ts
|
||||
|
||||
# The watch app on watchOS simulators in its screenshot mode (DemoMode.swift):
|
||||
# every screen on the largest and the smallest watch, the main ones in every
|
||||
# language, and the complications, as PNGs to look at without a watch.
|
||||
|
||||
@@ -13,7 +13,7 @@ name: Security Scan
|
||||
# - scout scans the built image, base image packages included. It needs
|
||||
# the Docker Hub login, so it runs on PRs and pushes into main only and
|
||||
# skips fork PRs. Whether the image builds at all is test.yml's
|
||||
# docker-image job, which a red scan cannot hide.
|
||||
# docker job, which a red scan cannot hide.
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main, dev]
|
||||
|
||||
+895
-718
File diff suppressed because it is too large
Load Diff
@@ -31,6 +31,7 @@ Tests:
|
||||
npm run test # all workspaces
|
||||
npm run test --workspace=server # vitest run (server); also test:unit / test:integration / test:ws
|
||||
npm run test:e2e # server e2e (boots Nest against a temp SQLite)
|
||||
npm run test:pg --workspace=server # the Postgres lane (vitest.pg.config.ts; needs TREK_TEST_DB_URL, e.g. postgres://postgres:trek@127.0.0.1:55432/postgres)
|
||||
npm run test:cov # coverage (lcov) for all four packages incl. plugin-sdk
|
||||
cd client && npm run test # client vitest run
|
||||
cd client && npm run e2e # Playwright (CI runs the public and app projects; the screenshot and help-media ones are local)
|
||||
@@ -51,7 +52,9 @@ cd client && npm run lint:skips # no .only; skipped tests may
|
||||
cd client && npm run lint:i18n-keys # every key the client names exists in en; unused en keys may only shrink (CI gate)
|
||||
cd server && npm run lint:boundaries # no new import cycles or cross-domain reach-ins (CI gate)
|
||||
cd server && npm run lint:dialect # SQLite-only SQL spellings may only shrink (CI gate; rules in server/CLAUDE.md)
|
||||
cd server && npm run lint:engine-dispatch # engine checks outside src/db/dialect/ and src/db/engine/ may only shrink (CI gate)
|
||||
cd server && npm run probe:pg # dialect helpers + the repository statements it reaches against Postgres (CI job; needs TREK_PG_PROBE_URL)
|
||||
cd server && npm run check:pg-baseline # the Postgres baseline in server/assets/postgres/ matches the entities and the migrations (CI gate)
|
||||
cd server && npm run lint:tx # no new method writing twice outside one transaction (CI gate)
|
||||
cd server && npm run lint:test-sql # raw SQL fixtures in tests/ may only shrink; seed through tests/helpers/factories (CI gate)
|
||||
cd server && npm run lint:test-mocks # vi.mock of config, realtime and db modules in tests/ may only shrink (CI gate)
|
||||
@@ -134,13 +137,18 @@ 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: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-checks), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, the Postgres probe (`postgres-probe`: every dialect helper on SQLite and Postgres, and the statements every repository method reaches with sample arguments against a Postgres service; the SQL errors per method and the list of methods it cannot measure are held to a baseline that only shrinks and fails while it is still unmeasured; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit), 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 (`docker-image`), and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (`deploy-manifests`). `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 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.
|
||||
|
||||
- **Job names read "package: what"** (`Server: Types`, `Client: Tests 3/7`), and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list, and the job-count note there says when a long job needs a slot freed first.
|
||||
- **Tests run beside the gates, in shards.** The client and server suites run in slices on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold.
|
||||
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`.
|
||||
- **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.
|
||||
- **Tests run beside the gates, in shards.** The client and server suites run in ten slices each on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), the Postgres lane in three per major, and the end-to-end flows in two, and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold. A sliced job states its slice count in its matrix's shard axis, the `i/n` in its name and its `--shard=i/n`; `scripts/ci/workflow-jobs.test.mjs` fails until all three agree, and on any job naming `matrix.shard` or `--shard` whose axis is not the one-line `shard: [1, ..., n]` it reads.
|
||||
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`, and `scripts/ci/workflow-jobs.test.mjs` (in `test:ci-scripts`) fails while a job other than the scan is missing there.
|
||||
- **The release pull request mirrors the push run.** On the pull request from `dev` into `main` (head branch in this repository), `changes` sets `mirror` and turns every area off (`scripts/ci/changed-areas.mjs`), so no test, gate or scan job runs, and `ci-ok` runs `scripts/ci/mirror-push-run.mjs`: it waits for the `ci-ok` of the push run of `test.yml` on `dev` for exactly the PR's head commit and passes or fails with it. No such push run, one that ended without a verdict, or a wait past 17 minutes fails with a re-run hint, never passes. A push to `dev` lists its changes against the merge base with `main`, not against the previous push, so the run it mirrors covers every area the pull request brings in, even when an earlier push's run was cancelled or red. Testing that commit twice doubled the jobs past the 60 slots.
|
||||
- **Guides name paths that exist**: the `changes` job runs `scripts/ci/doc-paths.mjs`, which resolves every backtick path in the CLAUDE.md files, `README.md`, `server/src/nest/README.md` and the wiki against the tracked files; the missing ones are listed in `scripts/ci/doc-paths-baseline.json`, which only shrinks (`--update` after a fix).
|
||||
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there.
|
||||
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there. A change to `test.yml`, to `scripts/ci/` or to a local action under `.github/actions/` runs everything.
|
||||
- **Setup goes through one local action.** Every job that installs dependencies uses `.github/actions/setup/action.yml` (`scope` full, client or shared; `build-shared`) instead of its own `npm ci`; `workflow-jobs.test.mjs` fails on a job that installs on its own (plugin-sdk's own install in its directory excepted). The action restores node_modules on an exact key (runner image, scope, Node ABI, `.nvmrc`, the lockfile and every workspace `package.json`, so npm ci still refuses a `package.json` out of step with the lockfile; no restore-keys) and shared/dist on a key over shared's sources and build config, and runs `npm ci` or the shared build on a miss. Only pushes to dev and main save, the npm download cache included; pull requests only read.
|
||||
- **End-to-end runs in the Playwright container**, `mcr.microsoft.com/playwright:v<version>-noble` pinned by digest, so no step installs browsers or system libraries. Dependabot bumps only the lockfile: on every Playwright PR move the tag and its digest in `client-e2e` by hand (`docker buildx imagetools inspect mcr.microsoft.com/playwright:v<version>-noble`); `workflow-jobs.test.mjs` fails until the tag names the lockfile's `@playwright/test` version.
|
||||
- **Budget: `ci-ok` within ten minutes.** One code run starts at most about 35 long jobs (gates, slices, Postgres, e2e, Docker), so two PR runs fit in the organisation's 60 concurrent jobs. Every job sets `timeout-minutes` of at most 20 (15 for the long ones, 10 for the short ones), which `workflow-jobs.test.mjs` holds. A new long job, slice or shard needs a reason that outweighs its slot; the job-count note at the top of `test.yml` has the numbers.
|
||||
- **Runners and Node**: jobs run on `ubuntu-24.04`, not `ubuntu-latest`, and every `setup-node` reads `.nvmrc`. Third-party actions (anything outside `actions/*`) are pinned by commit SHA with the tag in a comment; Dependabot keeps both current.
|
||||
- **Security scans are advisory.** `security.yml` runs `npm audit` (what the image installs, plus `plugin-sdk`) on every PR and push into dev and main, and Docker Scout on the built image for main. Neither is required: a newly published advisory would turn every open PR red at once. Fixes are held as floors in the root `package.json` `overrides`; npm ignores an `overrides` block in a workspace `package.json`, so never put one there.
|
||||
- **Releases** are dispatched by hand and refuse a commit whose `ci-ok` is not green. `docker-dev.yml` (any branch, usually dev) is the canary: it builds the dispatched commit as the next minor or major `-pre.N` and moves only `:latest-pre` and `:<major>-pre`. `docker.yml` (main only) bumps the version, commits and tags it, builds both platforms from exactly that commit and moves `:latest`, `:<major>`, `:<major>.<minor>` and `:<version>`. Its `bump=auto` only finalizes a prerelease in flight; without one it stops and asks for patch, minor or major. Ship a release that migrates or changes a lot as a prerelease first, and as a minor, so installs pinned to `:<major>.<minor>` can wait it out.
|
||||
|
||||
+24
-10
@@ -72,17 +72,30 @@ COPY server/package.json ./server/
|
||||
# package, and a telemetry ping.
|
||||
# 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).
|
||||
RUN apt-get update && \
|
||||
#
|
||||
# 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
|
||||
# (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).
|
||||
# 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.
|
||||
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' \
|
||||
> /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 && \
|
||||
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \
|
||||
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 && \
|
||||
chown -R node:node /app
|
||||
|
||||
# gosu rebuilt with a current Go toolchain (stage 0) — the entrypoint script uses
|
||||
# it to drop to node.
|
||||
# gosu rebuilt with a current Go toolchain (stage 0). The entrypoint drops to node
|
||||
# with setpriv since #3135; gosu stays in the image for anyone who calls it by hand.
|
||||
COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
|
||||
|
||||
ENV XDG_CACHE_HOME=/tmp/kf6-cache
|
||||
@@ -94,8 +107,9 @@ ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
|
||||
|
||||
COPY --chown=node:node --from=server-builder /app/server/dist ./server/dist
|
||||
# Runtime data assets read from server/assets at runtime: airports.json (flight
|
||||
# transport search) and atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
|
||||
# country/region map). The build
|
||||
# transport search), atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
|
||||
# country/region map) and postgres/baseline.* (the schema a fresh Postgres
|
||||
# database starts from). The build
|
||||
# only emits dist, so these must be copied explicitly or the features silently
|
||||
# degrade to empty in the image.
|
||||
COPY --chown=node:node --from=server-builder /app/server/assets ./server/assets
|
||||
@@ -106,9 +120,9 @@ COPY --chown=node:node wiki ./wiki
|
||||
# tsconfig-paths/register reads this at runtime to resolve MCP SDK paths.
|
||||
COPY --chown=node:node server/tsconfig.json ./server/
|
||||
# Encryption-key rotation is run on demand via tsx (a prod dep) straight from the
|
||||
# raw .ts source — it never enters dist, so it must be copied in explicitly or
|
||||
# raw .ts source (the command and its stores module). They never enter dist, so they must be copied in explicitly or
|
||||
# `node --import tsx scripts/migrate-encryption.ts` fails with module-not-found.
|
||||
COPY --chown=node:node server/scripts/migrate-encryption.ts ./server/scripts/migrate-encryption.ts
|
||||
COPY --chown=node:node server/scripts/migrate-encryption.ts server/scripts/migrate-encryption-stores.ts ./server/scripts/
|
||||
# Admin recovery script (node server/reset-admin.js) for locked-out installs.
|
||||
COPY --chown=node:node server/reset-admin.js ./server/reset-admin.js
|
||||
COPY --chown=node:node --from=shared-builder /app/shared/dist ./shared/dist
|
||||
@@ -159,8 +173,8 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
# carrying quotes does not survive that round-trip (the container then dies with
|
||||
# a shell syntax error before Node starts). A CMD of one bare token does.
|
||||
COPY server/scripts/entrypoint.sh /usr/local/bin/trek-entrypoint
|
||||
# Root-owned on purpose — this is what calls gosu, so it runs before the drop to
|
||||
# node. chmod is explicit because a checkout on Windows carries no exec bit.
|
||||
# Root-owned on purpose: it runs as root and drops to node itself, with setpriv.
|
||||
# chmod is explicit because a checkout on Windows carries no exec bit.
|
||||
RUN chmod 0755 /usr/local/bin/trek-entrypoint
|
||||
|
||||
ENTRYPOINT ["dumb-init", "--"]
|
||||
|
||||
@@ -321,6 +321,11 @@ 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
|
||||
[`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.
|
||||
|
||||
<br />
|
||||
|
||||
<h2 id="helm-kubernetes">Helm (Kubernetes)</h2>
|
||||
|
||||
@@ -46,6 +46,7 @@ See `values.yaml` for more options.
|
||||
- Both PVCs are `ReadWriteOnce`. Set `persistence.data.accessModes` and/or `persistence.uploads.accessModes` to override, for example `[ReadWriteMany]` so a backup pod can mount the volume. On the data volume such a pod may only read: SQLite corrupts `travel.db` when a second process writes it over a network filesystem.
|
||||
- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, accessModes, annotations) are then ignored.
|
||||
- With `persistence.enabled: false`, the data and uploads volumes use an `emptyDir` — storage is ephemeral and lost on pod restart. Intended for testing only.
|
||||
- `database.url` runs TREK on a PostgreSQL database instead of the SQLite file. The chart writes it into its Secret as `TREK_DB_URL`; `database.existingSecret` and `database.existingSecretKey` read it from a Secret you manage. Leave both empty for SQLite. Keep `replicas: 1` either way. See the wiki page `Database-Postgres`.
|
||||
- `JWT_SECRET` is managed entirely by the server — auto-generated into the data PVC on first start and rotatable via the admin panel (Settings → Danger Zone). No Helm configuration needed.
|
||||
- `ENCRYPTION_KEY` encrypts stored secrets (API keys, MFA, SMTP, OIDC) at rest. Recommended: set via `secretEnv.ENCRYPTION_KEY` or `existingSecret`. If left empty, the server falls back automatically: existing installs use `data/.jwt_secret` (no action needed on upgrade); fresh installs auto-generate a key persisted to the data PVC.
|
||||
- Liveness and readiness probes are configurable under `probes`. Overrides are merged over the defaults, so `--set probes.liveness.initialDelaySeconds=60` keeps the `httpGet` handler. When switching to `exec` or `tcpSocket`, clear `httpGet` in the same override. Set `probes.liveness: null` to remove a probe.
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
{{- if and .Values.database.url (not .Values.database.existingSecret) .Values.existingSecret }}
|
||||
{{- fail "database.url is written into the chart's own Secret, which existingSecret replaces. Put TREK_DB_URL in your Secret and set database.existingSecret instead." }}
|
||||
{{- end }}
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
@@ -5,11 +8,13 @@ metadata:
|
||||
labels:
|
||||
app: {{ include "trek.name" . }}
|
||||
spec:
|
||||
# One replica. Its rate limits, pending codes, permission cache and WebSocket
|
||||
# connections live in the process's memory, so a second pod would not share them. That
|
||||
# holds with database.url (PostgreSQL) too; see updateStrategy in values.yaml.
|
||||
replicas: 1
|
||||
# TREK is a single-writer SQLite app on a ReadWriteOnce PVC, so the default
|
||||
# RollingUpdate would start a second pod holding the same volume before the old one
|
||||
# exits — a Multi-Attach deadlock, or two processes on one travel.db. Recreate tears
|
||||
# the old pod down first. Keep it, see updateStrategy in values.yaml.
|
||||
# The default RollingUpdate would start a second pod on the same ReadWriteOnce PVC
|
||||
# before the old one exits: a Multi-Attach deadlock, or two processes on one travel.db.
|
||||
# Recreate tears the old pod down first. Keep it, see updateStrategy in values.yaml.
|
||||
strategy:
|
||||
type: {{ .Values.updateStrategy | default "Recreate" }}
|
||||
selector:
|
||||
@@ -61,6 +66,14 @@ spec:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: {{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}
|
||||
optional: true
|
||||
{{- if or .Values.database.url .Values.database.existingSecret }}
|
||||
# Required when set: a missing key stops the pod rather than starting it on SQLite.
|
||||
- name: TREK_DB_URL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.database.existingSecret }}
|
||||
key: {{ if .Values.database.existingSecret }}{{ .Values.database.existingSecretKey | default "TREK_DB_URL" }}{{ else }}TREK_DB_URL{{ end }}
|
||||
{{- end }}
|
||||
- name: ADMIN_EMAIL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
|
||||
@@ -8,6 +8,9 @@ metadata:
|
||||
type: Opaque
|
||||
data:
|
||||
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ .Values.secretEnv.ENCRYPTION_KEY | b64enc | quote }}
|
||||
{{- if .Values.database.url }}
|
||||
TREK_DB_URL: {{ .Values.database.url | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.ADMIN_EMAIL }}
|
||||
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | b64enc | quote }}
|
||||
{{- end }}
|
||||
@@ -65,6 +68,9 @@ stringData:
|
||||
{{- else }}
|
||||
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ randAlphaNum 32 | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.database.url }}
|
||||
TREK_DB_URL: {{ .Values.database.url | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.ADMIN_EMAIL }}
|
||||
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | quote }}
|
||||
{{- end }}
|
||||
|
||||
+23
-4
@@ -4,10 +4,13 @@ image:
|
||||
# tag: latest
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
# Deployment update strategy. Keep Recreate: TREK is a single-writer SQLite app, and
|
||||
# during a RollingUpdate the new pod migrates the database while the old one still
|
||||
# writes to it. A ReadWriteMany volume does not make that safe; SQLite's WAL needs both
|
||||
# processes on one host, which network filesystems do not provide.
|
||||
# Deployment update strategy. Keep Recreate. The new pod migrates the database when it
|
||||
# starts, and during a RollingUpdate it would do that while the old pod still writes to
|
||||
# it. Recreate stops the old pod first. On SQLite two processes on one travel.db are
|
||||
# unsafe, and a ReadWriteOnce volume cannot be attached to both pods at once.
|
||||
# With database.url the database is PostgreSQL, but the reason for one replica stays: TREK
|
||||
# keeps rate limits, pending codes, the permission cache and WebSocket connections in
|
||||
# memory, so a second pod would not share them. Postgres does not make more replicas safe.
|
||||
updateStrategy: Recreate
|
||||
|
||||
# Pod-level security context. fsGroup gives the node user (uid/gid 1000) group access
|
||||
@@ -178,6 +181,22 @@ env:
|
||||
# address is sent unless you set one here.
|
||||
|
||||
|
||||
# Database. Empty (the default) keeps TREK on its SQLite file in the data volume. Set url to
|
||||
# run TREK on a PostgreSQL database instead (see the wiki page Database-Postgres). The URL
|
||||
# carries the password, so it is never a plain env value: with url, the chart writes it into
|
||||
# its own Secret as TREK_DB_URL; with existingSecret, TREK reads TREK_DB_URL from that Secret
|
||||
# under existingSecretKey and the chart writes nothing. existingSecret wins over url. The
|
||||
# variable is required when either is set: a missing Secret key stops the pod instead of
|
||||
# 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.
|
||||
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
|
||||
database:
|
||||
url: ""
|
||||
existingSecret: ""
|
||||
existingSecretKey: TREK_DB_URL
|
||||
|
||||
# Secret environment variables stored in a Kubernetes Secret.
|
||||
# JWT_SECRET is managed entirely by the server (auto-generated into the data PVC,
|
||||
# rotatable via the admin panel) — it is not configured here.
|
||||
|
||||
@@ -82,10 +82,12 @@ abstract class TrekWidget : GlanceAppWidget() {
|
||||
// Read inside the composition: a session outlives one update, and every
|
||||
// write (the dashboard's, then each trip's) must reach it.
|
||||
val version by WidgetStore.version.collectAsState()
|
||||
val snapshot = remember(version) {
|
||||
val stored = remember(version) {
|
||||
val tripId = if (perTrip && appWidgetId >= 0) WidgetStore.tripFor(context, appWidgetId) else WidgetStore.AUTO
|
||||
WidgetStore.load(context, tripId)
|
||||
}
|
||||
// The day of the trip is today's on every update, not the one the app last wrote.
|
||||
val snapshot = stored?.on(LocalDate.now())
|
||||
TrekWidgetTheme.Themed { Content(snapshot) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,28 @@ data class WidgetSnapshot(
|
||||
val labels: Labels,
|
||||
/** The trip's next flight or the one in the air; last and defaulted, so older callers keep compiling. */
|
||||
val flight: Flight? = null,
|
||||
/**
|
||||
* The trip's days from the day the app wrote this on, each with its date, so
|
||||
* the widget turns to the next day itself (see [on]); empty from an app
|
||||
* that predates them.
|
||||
*/
|
||||
val days: List<Today> = emptyList(),
|
||||
) {
|
||||
/**
|
||||
* The snapshot as it reads on [date]: that date's trip day out of [days],
|
||||
* none before or after the trip, and only the bookings from that date on.
|
||||
* The app writes its snapshot only while it runs, so without this a widget
|
||||
* showed the day it last ran. A snapshot without [days] reads as written.
|
||||
*/
|
||||
fun on(date: LocalDate): WidgetSnapshot {
|
||||
if (days.isEmpty()) return this
|
||||
val key = date.toString()
|
||||
return copy(
|
||||
today = days.firstOrNull { it.date == key },
|
||||
bookings = bookings.filter { (it.date ?: key) >= key },
|
||||
)
|
||||
}
|
||||
|
||||
data class Trip(
|
||||
val title: String,
|
||||
val start: String,
|
||||
@@ -52,7 +73,8 @@ data class WidgetSnapshot(
|
||||
val symbol: String?,
|
||||
)
|
||||
|
||||
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?)
|
||||
/** A trip day; [date] (yyyy-MM-dd) is absent from an app that predates the days ahead. */
|
||||
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?, val date: String? = null)
|
||||
|
||||
data class Weather(
|
||||
val temp: Int,
|
||||
@@ -212,6 +234,16 @@ data class WidgetSnapshot(
|
||||
null
|
||||
}
|
||||
|
||||
private fun dayOf(t: JSONObject): Today = Today(
|
||||
dayLabel = t.optString("dayLabel"),
|
||||
stops = t.optJSONArray("stops").objects().map {
|
||||
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
|
||||
},
|
||||
index = t.int("index"),
|
||||
total = t.int("total"),
|
||||
date = t.str("date"),
|
||||
)
|
||||
|
||||
fun fromJson(o: JSONObject): WidgetSnapshot = WidgetSnapshot(
|
||||
trip = o.optJSONObject("trip")?.let {
|
||||
Trip(
|
||||
@@ -226,16 +258,8 @@ data class WidgetSnapshot(
|
||||
memberCount = it.int("memberCount"),
|
||||
)
|
||||
},
|
||||
today = o.optJSONObject("today")?.let { t ->
|
||||
Today(
|
||||
dayLabel = t.optString("dayLabel"),
|
||||
stops = t.optJSONArray("stops").objects().map {
|
||||
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
|
||||
},
|
||||
index = t.int("index"),
|
||||
total = t.int("total"),
|
||||
)
|
||||
},
|
||||
today = o.optJSONObject("today")?.let(::dayOf),
|
||||
days = o.optJSONArray("days").objects().map(::dayOf),
|
||||
weather = o.optJSONObject("weather")?.let {
|
||||
Weather(it.optInt("temp"), it.int("high"), it.int("low"), it.optString("main"), it.optString("label"), it.str("place"), it.int("rain"))
|
||||
},
|
||||
|
||||
@@ -99,4 +99,34 @@ class WidgetSnapshotTest {
|
||||
assertEquals("ferry.fill", TrekIcons.booking("cruise").first)
|
||||
assertEquals("bookmark.fill", TrekIcons.booking("something").first)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun turnsToTheDayOfTheDateItIsReadOn() {
|
||||
val json = """{"trip":{"title":"T","start":"2026-11-06","end":"2026-11-08","path":"/trips/1"},
|
||||
"today":{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
|
||||
"days":[
|
||||
{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
|
||||
{"date":"2026-11-07","dayLabel":"Day 2 of 3","stops":[{"time":"10:00","name":"Harbour","minutes":600}]}
|
||||
],
|
||||
"bookings":[
|
||||
{"title":"Hotel","kind":"hotel","date":"2026-11-06","confirmed":true,"path":"/trips/1"},
|
||||
{"title":"Train","kind":"train","date":"2026-11-07","confirmed":true,"path":"/trips/1"}
|
||||
],
|
||||
"labels":{}}"""
|
||||
val snapshot = WidgetSnapshot.parse(json)!!
|
||||
assertEquals("Day 1 of 3", snapshot.on(LocalDate.of(2026, 11, 6)).today!!.dayLabel)
|
||||
val second = snapshot.on(LocalDate.of(2026, 11, 7))
|
||||
assertEquals("Day 2 of 3", second.today!!.dayLabel)
|
||||
assertEquals("Harbour", second.today!!.stops.single().name)
|
||||
assertEquals(listOf("Train"), second.bookings.map { it.title })
|
||||
// A day the app wrote nothing for (the trip is over) shows no day.
|
||||
assertNull(snapshot.on(LocalDate.of(2026, 11, 9)).today)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSnapshotWithoutDaysReadsAsWritten() {
|
||||
val snapshot = WidgetSnapshot.parse(WidgetSamples.json(running = true, now = today))!!
|
||||
assertTrue(snapshot.days.isEmpty())
|
||||
assertEquals(snapshot, snapshot.on(today.plusDays(3)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -686,9 +686,8 @@ extension TrekShellPlugin {
|
||||
/// know are left out, so the shell offers only what can really be bought.
|
||||
@objc func storeProducts(_ call: CAPPluginCall) {
|
||||
let ids = call.getArray("ids", String.self) ?? []
|
||||
// TestFlight, App Review and Xcode builds buy in the sandbox; their receipt says so.
|
||||
let sandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
|
||||
Task {
|
||||
let sandbox = await Self.buysInSandbox()
|
||||
guard AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
|
||||
call.resolve(["products": [], "sandbox": sandbox])
|
||||
return
|
||||
@@ -697,6 +696,26 @@ extension TrekShellPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this build buys in the App Store sandbox: TestFlight, App Review and
|
||||
/// Xcode builds do, and while TREK Cloud's orders are closed only they may buy.
|
||||
/// The signed app transaction names its environment; the receipt's file name,
|
||||
/// which App Review builds do not always carry, is only the fallback where the
|
||||
/// app transaction is missing (iOS 15) or cannot be read.
|
||||
static func buysInSandbox() async -> Bool {
|
||||
let receiptSaysSandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
|
||||
guard #available(iOS 16.0, *), let result = try? await AppTransaction.shared else {
|
||||
return receiptSaysSandbox
|
||||
}
|
||||
// An unverified transaction still names the environment it was signed in;
|
||||
// it only decides whether the button shows, the cloud checks every purchase itself.
|
||||
let transaction: AppTransaction
|
||||
switch result {
|
||||
case .verified(let signed), .unverified(let signed, _):
|
||||
transaction = signed
|
||||
}
|
||||
return transaction.environment != .production || receiptSaysSandbox
|
||||
}
|
||||
|
||||
/// Feature storeKit: runs the App Store purchase sheet. Resolves with `kind`
|
||||
/// bought (with the signed transaction the control plane verifies), cancelled,
|
||||
/// pending (Ask to Buy, a payment the bank still has to approve) or failed.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 49 KiB |
@@ -21,12 +21,14 @@ struct TrekProvider: TimelineProvider {
|
||||
func getSnapshot(in context: Context, completion: @escaping (TrekEntry) -> Void) {
|
||||
let stored = WidgetSnapshot.load()
|
||||
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
|
||||
completion(TrekEntry(date: Date(), snapshot: snapshot))
|
||||
let now = Date()
|
||||
completion(TrekEntry(date: now, snapshot: snapshot?.on(now)))
|
||||
}
|
||||
|
||||
/// An entry every quarter hour for the next six hours, so the now line and
|
||||
/// the next stop move on without the app; the app reloads the timeline
|
||||
/// whenever it writes a new snapshot.
|
||||
/// the next stop move on without the app, each with the trip day of its own
|
||||
/// date: the one at midnight turns to the next day. The app reloads the
|
||||
/// timeline whenever it writes a new snapshot, WidgetKit when it runs out.
|
||||
func getTimeline(in context: Context, completion: @escaping (Timeline<TrekEntry>) -> Void) {
|
||||
completion(TrekProvider.timeline(WidgetSnapshot.load()))
|
||||
}
|
||||
@@ -36,10 +38,11 @@ struct TrekProvider: TimelineProvider {
|
||||
let calendar = Calendar.current
|
||||
let minute = calendar.component(.minute, from: now)
|
||||
let firstStep = calendar.date(byAdding: .minute, value: 15 - minute % 15, to: now) ?? now
|
||||
var entries = [TrekEntry(date: now, snapshot: snapshot)]
|
||||
var entries = [TrekEntry(date: now, snapshot: snapshot?.on(now))]
|
||||
for step in 0..<24 {
|
||||
if let date = calendar.date(byAdding: .minute, value: step * 15, to: firstStep) {
|
||||
entries.append(TrekEntry(date: calendar.date(bySetting: .second, value: 0, of: date) ?? date, snapshot: snapshot))
|
||||
let at = calendar.date(bySetting: .second, value: 0, of: date) ?? date
|
||||
entries.append(TrekEntry(date: at, snapshot: snapshot?.on(at)))
|
||||
}
|
||||
}
|
||||
return Timeline(entries: entries, policy: .atEnd)
|
||||
|
||||
@@ -512,8 +512,8 @@ struct StopList: View {
|
||||
ForEach(Array(window.enumerated()), id: \.offset) { offset, stop in
|
||||
let past = (stop.minutes ?? Int.max) < nowMinutes
|
||||
let isNext = !past && (offset == 0 || (window[offset - 1].minutes ?? Int.max) < nowMinutes)
|
||||
if isNext && offset > 0, let nowLabel { nowLine(nowLabel) }
|
||||
row(stop, past: past, isNext: isNext, last: offset == window.count - 1)
|
||||
if isNext && offset > 0, let nowLabel { nowLine(nowLabel, in: window) }
|
||||
row(stop, in: window, past: past, isNext: isNext, last: offset == window.count - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -528,13 +528,33 @@ struct StopList: View {
|
||||
|
||||
private var ink: Color { onPhoto ? .white : Trek.ink(scheme) }
|
||||
|
||||
private func row(_ stop: WidgetSnapshot.Stop, past: Bool, isNext: Bool, last: Bool) -> some View {
|
||||
/// The time column, as wide as the longest time in the window (and the now
|
||||
/// marker's label): every row lays all of them over each other, hidden, so
|
||||
/// "5:45 AM" fits as well as "09:30" and the dots still stand in one line.
|
||||
private func timeColumn<Label: View>(_ window: [WidgetSnapshot.Stop], @ViewBuilder label: () -> Label) -> some View {
|
||||
ZStack(alignment: .leading) {
|
||||
ForEach(Array(window.enumerated()), id: \.offset) { _, stop in
|
||||
Text(stop.time ?? "–").font(Trek.number(11.5, .heavy)).hidden()
|
||||
}
|
||||
if let nowLabel { nowText(nowLabel).hidden() }
|
||||
label()
|
||||
}
|
||||
.lineLimit(1)
|
||||
.fixedSize(horizontal: true, vertical: false)
|
||||
.frame(minWidth: 38, alignment: .leading)
|
||||
}
|
||||
|
||||
private func nowText(_ label: String) -> some View {
|
||||
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
|
||||
}
|
||||
|
||||
private func row(_ stop: WidgetSnapshot.Stop, in window: [WidgetSnapshot.Stop], past: Bool, isNext: Bool, last: Bool) -> some View {
|
||||
let color = Color(css: stop.color) ?? (onPhoto ? .white : Trek.info)
|
||||
return HStack(alignment: .top, spacing: 8) {
|
||||
Text(stop.time ?? "–")
|
||||
.font(Trek.number(11.5, isNext ? .heavy : .semibold))
|
||||
.frame(width: 38, alignment: .leading)
|
||||
.padding(.top, 1)
|
||||
timeColumn(window) {
|
||||
Text(stop.time ?? "–").font(Trek.number(11.5, isNext ? .heavy : .semibold))
|
||||
}
|
||||
.padding(.top, 1)
|
||||
VStack(spacing: 0) {
|
||||
ZStack {
|
||||
Circle().fill(color).frame(width: isNext ? 11 : 8, height: isNext ? 11 : 8)
|
||||
@@ -562,10 +582,9 @@ struct StopList: View {
|
||||
.frame(height: 24, alignment: .top)
|
||||
}
|
||||
|
||||
private func nowLine(_ label: String) -> some View {
|
||||
private func nowLine(_ label: String, in window: [WidgetSnapshot.Stop]) -> some View {
|
||||
HStack(spacing: 5) {
|
||||
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
|
||||
.frame(width: 38, alignment: .leading)
|
||||
timeColumn(window) { nowText(label) }
|
||||
Circle().fill(Trek.danger).frame(width: 5, height: 5).frame(width: 15)
|
||||
Rectangle().fill(Trek.danger).frame(height: 1.2)
|
||||
}
|
||||
|
||||
@@ -63,7 +63,8 @@ struct TrekTripProvider: AppIntentTimelineProvider {
|
||||
func snapshot(for configuration: SelectTripIntent, in context: Context) async -> TrekEntry {
|
||||
let stored = WidgetSnapshot.load(trip: configuration.trip?.id)
|
||||
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
|
||||
return TrekEntry(date: Date(), snapshot: snapshot)
|
||||
let now = Date()
|
||||
return TrekEntry(date: now, snapshot: snapshot?.on(now))
|
||||
}
|
||||
|
||||
func timeline(for configuration: SelectTripIntent, in context: Context) async -> Timeline<TrekEntry> {
|
||||
|
||||
@@ -35,6 +35,8 @@ struct WidgetSnapshot: Codable {
|
||||
}
|
||||
|
||||
struct Today: Codable {
|
||||
/// The calendar day it is, yyyy-MM-dd (absent from an app that predates `days`).
|
||||
var date: String?
|
||||
var dayLabel: String
|
||||
var stops: [Stop]
|
||||
/// 1-based position of today in the trip.
|
||||
@@ -245,6 +247,9 @@ struct WidgetSnapshot: Codable {
|
||||
|
||||
var trip: Trip?
|
||||
var today: Today?
|
||||
/// The trip's days from the day the app wrote this on, each with its date,
|
||||
/// so the widget turns to the next day itself (see `on(_:)`).
|
||||
var days: [Today]?
|
||||
var weather: Weather?
|
||||
var bookings: [Booking]?
|
||||
var todos: Todos?
|
||||
@@ -306,6 +311,26 @@ struct WidgetSnapshot: Codable {
|
||||
return days + 1
|
||||
}
|
||||
|
||||
/// The snapshot as it reads on `date`: that date's trip day out of `days`,
|
||||
/// none before or after the trip, and only the bookings from that date on.
|
||||
/// The app writes its snapshot only while it runs, so without this a widget
|
||||
/// showed the day it last ran (TestFlight feedback: "stuck on day 1"). A
|
||||
/// snapshot from an app without `days` reads as it was written.
|
||||
func on(_ date: Date) -> WidgetSnapshot {
|
||||
guard let days, !days.isEmpty else { return self }
|
||||
let key = WidgetSnapshot.key(date)
|
||||
var snapshot = self
|
||||
snapshot.today = days.first { $0.date == key }
|
||||
snapshot.bookings = bookings?.filter { ($0.date ?? key) >= key }
|
||||
return snapshot
|
||||
}
|
||||
|
||||
/// A date as the app writes one, yyyy-MM-dd in the device's calendar day.
|
||||
static func key(_ date: Date) -> String {
|
||||
let parts = Calendar.current.dateComponents([.year, .month, .day], from: date)
|
||||
return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)
|
||||
}
|
||||
|
||||
static func daysBetween(_ from: Date, _ to: Date) -> Int? {
|
||||
let calendar = Calendar.current
|
||||
return calendar.dateComponents([.day], from: calendar.startOfDay(for: from), to: calendar.startOfDay(for: to)).day
|
||||
|
||||
+10
-11
@@ -53,15 +53,15 @@
|
||||
"format:check": "prettier --check \"src/**/*.tsx\" \"src/**/*.css\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@assistant-ui/react": "0.15.32",
|
||||
"@assistant-ui/react": "0.15.36",
|
||||
"@capacitor/action-sheet": "^8.1.1",
|
||||
"@capacitor/android": "^8.6.0",
|
||||
"@capacitor/android": "^8.6.2",
|
||||
"@capacitor/app": "^8.1.1",
|
||||
"@capacitor/core": "^8.5.0",
|
||||
"@capacitor/core": "^8.6.2",
|
||||
"@capacitor/dialog": "^8.0.1",
|
||||
"@capacitor/filesystem": "^8.1.3",
|
||||
"@capacitor/haptics": "^8.0.2",
|
||||
"@capacitor/ios": "^8.6.0",
|
||||
"@capacitor/ios": "^8.6.2",
|
||||
"@capacitor/keyboard": "^8.0.5",
|
||||
"@capacitor/share": "^8.0.1",
|
||||
"@capacitor/splash-screen": "^8.0.2",
|
||||
@@ -101,7 +101,6 @@
|
||||
"@fontsource/satisfy": "^5.3.0",
|
||||
"@fontsource/shrikhand": "^5.3.0",
|
||||
"@fontsource/yellowtail": "^5.3.0",
|
||||
"@mapbox/mapbox-gl-rtl-text": "^0.4.0",
|
||||
"@maplibre/maplibre-gl-leaflet": "0.1.4",
|
||||
"@noble/hashes": "^1.8.0",
|
||||
"@simplewebauthn/browser": "^13.3.0",
|
||||
@@ -113,8 +112,8 @@
|
||||
"iso-3166-2": "^1.0.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-react": "^0.577.0",
|
||||
"mapbox-gl": "^3.31.0",
|
||||
"maplibre-gl": "6.16.0",
|
||||
"mapbox-gl": "^3.35.0",
|
||||
"maplibre-gl": "6.18.0",
|
||||
"modern-screenshot": "4.7.0",
|
||||
"plyr": "^3.8.5",
|
||||
"react": "^19.3.1",
|
||||
@@ -132,14 +131,14 @@
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@capacitor/cli": "^8.6.0",
|
||||
"@capacitor/cli": "^8.6.2",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@jscpd/core": "^4.2.5",
|
||||
"@jscpd/tokenizer": "^4.2.6",
|
||||
"@playwright/test": "^1.65.0",
|
||||
"@testing-library/jest-dom": "^6.10.0",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.8",
|
||||
"@testing-library/user-event": "^14.6.10",
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
||||
"@types/leaflet": "^1.9.22",
|
||||
"@types/node": "^25.9.8",
|
||||
@@ -157,7 +156,7 @@
|
||||
"jsdom": "^29.1.1",
|
||||
"msw": "^2.15.0",
|
||||
"postcss": "^8.5.28",
|
||||
"prettier": "^3.9.10",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
"rollup-plugin-visualizer": "^7.1.2",
|
||||
@@ -165,7 +164,7 @@
|
||||
"tailwindcss": "^3.4.19",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.72.1",
|
||||
"vite": "8.3.6",
|
||||
"vite": "8.3.8",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"vitest": "^4.1.12"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* Plyr's icon sprite. The package publishes its JS and CSS entries and nothing
|
||||
* else, so `plyr/dist/plyr.svg` is refused by the resolver although the file is
|
||||
* right there. Resolving the entry it does publish and stepping across keeps this
|
||||
* working wherever npm hoists the package.
|
||||
*
|
||||
* Shared by vite.config.js and vitest.config.ts: the build needs it to emit the
|
||||
* asset, and the test run needs it because a component reaches the same
|
||||
* specifier. The pattern is a regex so a `?url` suffix survives the rewrite. The player has to point at a copy on this origin
|
||||
* (#2341): its default is the sprite on cdn.plyr.io, which the CSP refuses.
|
||||
*/
|
||||
export const plyrSpriteAlias = {
|
||||
find: /^plyr\/dist\/plyr\.svg/,
|
||||
replacement: path.join(
|
||||
path.dirname(createRequire(import.meta.url).resolve('plyr')),
|
||||
'plyr.svg',
|
||||
),
|
||||
};
|
||||
@@ -1,39 +0,0 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* setRTLTextPlugin() takes the URL of a classic script that the GL worker pulls in
|
||||
* with importScripts. mapbox-gl-rtl-text ships exactly that as
|
||||
* dist/mapbox-gl-rtl-text.js, but its "exports" field publishes only the ESM/WASM
|
||||
* entry, so the resolver refuses the subpath. Resolving the entry it does publish
|
||||
* and stepping across to dist keeps this working wherever npm hoists the package.
|
||||
*
|
||||
* Shared by vite.config.js and vitest.config.ts: the build needs it to emit the
|
||||
* asset, and the test run needs it because a lazily imported engine module reaches
|
||||
* the same specifier.
|
||||
*
|
||||
* The pattern is a regex, not a string key: the import carries a `?url` suffix,
|
||||
* which a string alias will not match. It is left unanchored on purpose so the
|
||||
* query survives the rewrite and Vite still emits an asset URL.
|
||||
*/
|
||||
export const rtlTextAlias = {
|
||||
find: /^@mapbox\/mapbox-gl-rtl-text\/dist\/mapbox-gl-rtl-text\.js/,
|
||||
replacement: path.join(
|
||||
path.dirname(createRequire(import.meta.url).resolve('@mapbox/mapbox-gl-rtl-text')),
|
||||
'../dist/mapbox-gl-rtl-text.js',
|
||||
),
|
||||
};
|
||||
|
||||
/**
|
||||
* Same shape for Plyr's icon sprite. The package publishes its JS and CSS entries
|
||||
* and nothing else, so `plyr/dist/plyr.svg` is refused by the resolver although
|
||||
* the file is right there. The player has to point at a copy on this origin
|
||||
* (#2341): its default is the sprite on cdn.plyr.io, which the CSP refuses.
|
||||
*/
|
||||
export const plyrSpriteAlias = {
|
||||
find: /^plyr\/dist\/plyr\.svg/,
|
||||
replacement: path.join(
|
||||
path.dirname(createRequire(import.meta.url).resolve('plyr')),
|
||||
'plyr.svg',
|
||||
),
|
||||
};
|
||||
@@ -1,18 +1,18 @@
|
||||
{
|
||||
"src": {
|
||||
"@typescript-eslint/no-non-null-assertion": 368,
|
||||
"@typescript-eslint/no-non-null-assertion": 367,
|
||||
"@typescript-eslint/no-misused-promises": 820,
|
||||
"no-console": 88,
|
||||
"complexity": 217,
|
||||
"@typescript-eslint/no-explicit-any": 143,
|
||||
"trek/no-swallowed-catch": 128,
|
||||
"trek/no-swallowed-catch": 126,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 66,
|
||||
"react-hooks/refs": 534,
|
||||
"react-hooks/set-state-in-effect": 189,
|
||||
"@typescript-eslint/no-floating-promises": 162,
|
||||
"react-hooks/exhaustive-deps": 113,
|
||||
"@typescript-eslint/no-unused-vars": 122,
|
||||
"@typescript-eslint/no-unused-vars": 120,
|
||||
"react-hooks/immutability": 28,
|
||||
"max-lines-per-function": 127,
|
||||
"react-hooks/static-components": 50,
|
||||
@@ -35,7 +35,7 @@
|
||||
},
|
||||
"tests": {
|
||||
"@typescript-eslint/no-explicit-any": 489,
|
||||
"@typescript-eslint/no-non-null-assertion": 1876,
|
||||
"@typescript-eslint/no-non-null-assertion": 1875,
|
||||
"@typescript-eslint/no-misused-promises": 22,
|
||||
"@typescript-eslint/no-unused-vars": 51,
|
||||
"@typescript-eslint/no-floating-promises": 33,
|
||||
|
||||
@@ -190,7 +190,7 @@
|
||||
{
|
||||
"feature": "Booking mail import: admin card",
|
||||
"hooks": ["src/components/Admin/mailIngest/useMailIngestAdmin.ts", "src/components/Admin/mailIngest/mailIngestAdminModel.ts"],
|
||||
"desktop": ["src/components/Admin/mailIngest/MailIngestAdminCard.tsx"],
|
||||
"desktop": ["src/components/Admin/mailIngest/MailIngestAddonTile.tsx"],
|
||||
"mobile": ["src/mobile/screens/admin/MMailIngestAdminCard.tsx"]
|
||||
},
|
||||
{
|
||||
@@ -698,6 +698,24 @@
|
||||
"desktop": ["src/components/Planner/PlaceFormModal.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/sheets/PlPlaceSearch.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Place add/edit form: tags",
|
||||
"hooks": ["src/components/Planner/usePlaceTags.ts"],
|
||||
"desktop": ["src/components/Planner/PlaceFormModal.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Place add/edit form: description, notes and the day note as tabs",
|
||||
"hooks": ["src/components/Planner/usePlaceTextTabs.ts"],
|
||||
"desktop": ["src/components/Planner/PlaceFormTexts.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/sheets/PlPlaceTexts.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Place add/edit form: phone, e-mail and opening hours",
|
||||
"hooks": ["src/components/Planner/usePlaceHours.ts"],
|
||||
"desktop": ["src/components/Planner/PlaceContactFields.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/sheets/PlContactFields.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Place detail actions",
|
||||
"hooks": ["src/components/Planner/usePlaceActions.ts"],
|
||||
@@ -1095,8 +1113,8 @@
|
||||
"mobile": ["src/mobile/screens/admin/MAdminSchoolHolidayCatalog.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Trip settings: members, guests, public and invite link",
|
||||
"hooks": ["src/components/Trips/useTripShare.ts"],
|
||||
"feature": "Trip settings: members, guests, public and invite link, the trip's own addons",
|
||||
"hooks": ["src/components/Trips/useTripShare.ts", "src/components/Trips/useTripAddonRows.ts"],
|
||||
"desktop": ["src/components/Trips/TripShareDialog.tsx"],
|
||||
"mobile": ["src/mobile/screens/trip/sheets/MTripSettingsSheet.tsx"]
|
||||
}
|
||||
@@ -1172,6 +1190,7 @@
|
||||
"src/mobile/screens/trip/sheets/MTripSheetUi.tsx": "Phone sheet UI primitives (eyebrow, headers, stat boxes, action circles) and a time display helper.",
|
||||
"src/mobile/screens/trip/sheets/PlFileAttach.tsx": "Markup only; pending files and link actions come through props from the phone form sheets.",
|
||||
"src/mobile/screens/trip/sheets/PlSheetChrome.tsx": "Phone form sheet chrome primitives (header, footer, field classes).",
|
||||
"src/mobile/screens/trip/sheets/PlTags.tsx": "Markup only; the tag picker's state comes through props from MPlaceEditSheet, which runs usePlaceTags, and the chips of the place sheet draw the tags the place carries.",
|
||||
"src/mobile/screens/trip/sheets/PlTimeFields.tsx": "Phone time fields that already share timeCollisions with the desktop PlaceFormModal.",
|
||||
"src/mobile/screens/trip/sheets/tourSheetOpen.ts": "Phone only context for MTourDetailShell: whether the tour sheet is open and the name it carries.",
|
||||
"src/mobile/screens/trip/tabs/MCollabTab.tsx": "Phone collab sub tab router that reuses the desktop CollabLinks component.",
|
||||
|
||||
@@ -519,8 +519,6 @@
|
||||
"src/components/Map/reservationsMapbox.ts",
|
||||
"src/components/Map/routeUsageCounter.test.ts",
|
||||
"src/components/Map/routeUsageCounter.ts",
|
||||
"src/components/Map/rtlText.test.ts",
|
||||
"src/components/Map/rtlText.ts",
|
||||
"src/components/Map/selectedPlaceTarget.test.ts",
|
||||
"src/components/Map/selectedPlaceTarget.ts",
|
||||
"src/components/Map/trackColors.ts",
|
||||
@@ -1544,7 +1542,6 @@
|
||||
"src/pages/journeyDetail/useJourneyDetail.ts",
|
||||
"src/pages/journeyDetail/useProviderPhotoAdds.test.tsx",
|
||||
"src/pages/journeyDetail/useProviderPhotoAdds.ts",
|
||||
"src/pages/journeyPublic/journeyPublicModel.ts",
|
||||
"src/pages/journeyPublic/useJourneyPublic.ts",
|
||||
"src/pages/journeyStudio/useJourneyStudio.test.tsx",
|
||||
"src/pages/journeyStudio/useJourneyStudio.ts",
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
"pdf.ts": 1,
|
||||
"perm.ts": 4,
|
||||
"places.ts": 9,
|
||||
"planner.ts": 53,
|
||||
"planner.ts": 52,
|
||||
"reservations.ts": 21,
|
||||
"roadtrip.ts": 36,
|
||||
"settings.ts": 37,
|
||||
|
||||
@@ -22,6 +22,6 @@
|
||||
"src/pages/TripPlannerPage.tsx": 1128,
|
||||
"src/pages/atlas/useAtlas.ts": 1207,
|
||||
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
|
||||
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3269,
|
||||
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
|
||||
"src/styles/studio.css": 1918
|
||||
}
|
||||
|
||||
@@ -113,7 +113,6 @@
|
||||
"src/pages/AtlasPage.tsx": 6,
|
||||
"src/pages/FilesPage.tsx": 1,
|
||||
"src/pages/JourneyDetailPage.tsx": 1,
|
||||
"src/pages/JourneyPublicPage.test.tsx": 1,
|
||||
"src/pages/LoginPage.tsx": 1,
|
||||
"src/pages/VacayPage.tsx": 1,
|
||||
"src/pages/admin/useAdmin.ts": 4,
|
||||
@@ -130,7 +129,7 @@
|
||||
"src/pages/tripPlanner/usePlaceEdits.ts": 2,
|
||||
"src/pages/tripPlanner/usePlaceFormOpeners.test.ts": 2,
|
||||
"src/pages/tripPlanner/usePlaceFormOpeners.ts": 1,
|
||||
"src/pages/tripPlanner/useTripPlanner.ts": 2,
|
||||
"src/pages/tripPlanner/useTripPlanner.ts": 1,
|
||||
"src/repo/tripRepo.ts": 2,
|
||||
"src/store/slices/budgetSlice.test.ts": 1,
|
||||
"src/utils/formatters.test.ts": 1,
|
||||
|
||||
@@ -146,7 +146,7 @@
|
||||
"mobile/components/MToastHost.tsx": 2,
|
||||
"mobile/components/MUserPickerList.tsx": 1,
|
||||
"mobile/screens/admin/MAdmin.tsx": 8,
|
||||
"mobile/screens/admin/MAdminAddonManager.tsx": 4,
|
||||
"mobile/screens/admin/MAdminAddonManager.tsx": 3,
|
||||
"mobile/screens/admin/MAdminAuditLogPanel.tsx": 15,
|
||||
"mobile/screens/admin/MAdminBackupPanel.tsx": 7,
|
||||
"mobile/screens/admin/MAdminCategoryManager.tsx": 8,
|
||||
@@ -241,7 +241,7 @@
|
||||
"mobile/screens/trip/sheets/MDaysSheet.tsx": 4,
|
||||
"mobile/screens/trip/sheets/MExportSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MImportSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MLinkedCosts.tsx": 9,
|
||||
"mobile/screens/trip/sheets/MLinkedCosts.tsx": 8,
|
||||
"mobile/screens/trip/sheets/MMehrSheet.tsx": 3,
|
||||
"mobile/screens/trip/sheets/MNoteSheet.tsx": 1,
|
||||
"mobile/screens/trip/sheets/MPlaceEditSheet.tsx": 2,
|
||||
@@ -250,8 +250,8 @@
|
||||
"mobile/screens/trip/sheets/MTransportFormSheet.tsx": 9,
|
||||
"mobile/screens/trip/sheets/MTransportSheet.tsx": 9,
|
||||
"mobile/screens/trip/sheets/MTripSheetUi.tsx": 5,
|
||||
"mobile/screens/trip/sheets/PlCategoryPicker.tsx": 2,
|
||||
"mobile/screens/trip/sheets/PlFileAttach.tsx": 7,
|
||||
"mobile/screens/trip/sheets/PlCategoryPicker.tsx": 1,
|
||||
"mobile/screens/trip/sheets/PlFileAttach.tsx": 3,
|
||||
"mobile/screens/trip/sheets/PlPlaceSearch.tsx": 6,
|
||||
"mobile/screens/trip/sheets/PlSheetChrome.tsx": 5,
|
||||
"mobile/screens/trip/sheets/PlTimeFields.tsx": 3,
|
||||
|
||||
@@ -30,6 +30,7 @@ import { takeResumeRoute, useRememberRoute } from './utils/resumeRoute'
|
||||
import { usePermissionsStore, PermissionLevel } from './store/permissionsStore'
|
||||
import { useInAppNotificationListener } from './hooks/useInAppNotificationListener.ts'
|
||||
import { useRoadtripPreferencesSync } from './hooks/useRoadtripPreferencesSync'
|
||||
import { useTripAddonsSync } from './hooks/useTripAddonsSync'
|
||||
import { registerSyncTriggers, unregisterSyncTriggers } from './sync/syncTriggers'
|
||||
import OfflineBanner from './components/Layout/OfflineBanner'
|
||||
import NewVersionNotice from './components/Layout/NewVersionNotice'
|
||||
@@ -379,6 +380,7 @@ export default function App() {
|
||||
|
||||
useInAppNotificationListener()
|
||||
useRoadtripPreferencesSync()
|
||||
useTripAddonsSync()
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { TripAddonsResponse, TripAddonUpdateRequest } from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
/** The trip addons of one trip, each on or off for it: every member reads them, only the owner switches one. */
|
||||
export const tripAddonsApi = {
|
||||
list: (tripId: number): Promise<TripAddonsResponse> => apiClient.get(`/trips/${tripId}/addons`).then((r) => r.data),
|
||||
/** `enabled: null` drops the trip's own choice, so the instance setting applies again. */
|
||||
update: (tripId: number, addonId: string, body: TripAddonUpdateRequest): Promise<TripAddonsResponse> =>
|
||||
apiClient.put(`/trips/${tripId}/addons/${encodeURIComponent(addonId)}`, body).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { TripTagCreateRequest, TripTagListResponse, TripTagResponse, TripTagUpdateRequest } from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
/** The tags a trip owns: every member reads them, and whoever may edit its places adds one. */
|
||||
export const tripTagsApi = {
|
||||
list: (tripId: number | string): Promise<TripTagListResponse> =>
|
||||
apiClient.get(`/trips/${tripId}/tags`).then((r) => r.data),
|
||||
/** Answers the trip's existing tag when it already has one of that name. */
|
||||
create: (tripId: number | string, body: TripTagCreateRequest): Promise<TripTagResponse> =>
|
||||
apiClient.post(`/trips/${tripId}/tags`, body).then((r) => r.data),
|
||||
/** A new name or colour for one of the trip's tags; every place carrying it shows the change. */
|
||||
update: (tripId: number | string, tagId: number, body: TripTagUpdateRequest): Promise<TripTagResponse> =>
|
||||
apiClient.put(`/trips/${tripId}/tags/${tagId}`, body).then((r) => r.data),
|
||||
};
|
||||
@@ -46,6 +46,10 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
|
||||
'roadtripVia:changed',
|
||||
'roadtripTrack:changed',
|
||||
'roadtripPreferences:changed',
|
||||
// Per-trip addons: store/tripAddonsStore (watchTripAddons, mounted by App through
|
||||
// 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',
|
||||
// components/Roadtrip/useDayBoundaries reloads the shared boundaries.
|
||||
'roadtripBoundary:changed',
|
||||
// In-app notifications: hooks/useInAppNotificationListener, which also keeps
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import { mailIngestRepo } from '../../repo/mailIngestRepo';
|
||||
import AddonManager from './AddonManager';
|
||||
|
||||
function buildAddon(overrides = {}) {
|
||||
@@ -691,4 +692,40 @@ describe('AddonManager', () => {
|
||||
expect(roadtrip.querySelector('svg.lucide-car-front')).toBeInTheDocument();
|
||||
expect(tours.querySelector('svg.lucide-puzzle')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-045: live flight status is a row of the trip card, switched there and locked by the environment', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'packing', name: 'Lists', icon: 'ListChecks', type: 'trip', enabled: true })]));
|
||||
const onToggle = vi.fn();
|
||||
const { unmount } = render(<AddonManager flightLive={{ on: false, locked: false, managed: false, onToggle }} />);
|
||||
const trip = (await screen.findByRole('heading', { name: 'Trip' })).closest('section') as HTMLElement;
|
||||
await userEvent.click(within(trip).getByRole('button', { name: 'Follow booked flights live' }));
|
||||
expect(onToggle).toHaveBeenCalledTimes(1);
|
||||
// The count stays the addons': the flight row is an instance option beside them.
|
||||
expect(within(trip).getByText('1/1')).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
render(<AddonManager flightLive={{ on: true, locked: true, managed: false, onToggle }} />);
|
||||
expect(await screen.findByRole('button', { name: 'Follow booked flights live' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-046: the booking mail import is a row of the integration card whose setup opens in a dialog', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
|
||||
vi.spyOn(mailIngestRepo, 'adminSettings').mockResolvedValue({ mail_ingest_enabled: 'true' });
|
||||
vi.spyOn(mailIngestRepo, 'adminStatus').mockRejectedValue(new Error('no status'));
|
||||
render(<AddonManager mailImport />);
|
||||
const integration = (await screen.findByRole('heading', { name: 'Integration' })).closest('section') as HTMLElement;
|
||||
expect(within(integration).getByText('Booking mail import')).toBeInTheDocument();
|
||||
await userEvent.click(await within(integration).findByRole('button', { name: 'Set up mail import' }));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByText('How mail arrives')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-047: without the mail option the integration card has no mail row and nothing is loaded', async () => {
|
||||
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
|
||||
const load = vi.spyOn(mailIngestRepo, 'adminSettings');
|
||||
render(<AddonManager />);
|
||||
await screen.findByRole('heading', { name: 'Integration' });
|
||||
expect(screen.queryByText('Booking mail import')).not.toBeInTheDocument();
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ComponentType, ReactNode } from 'react'
|
||||
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 } 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 } from 'lucide-react'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import AirTrailIcon from '../shared/AirTrailIcon'
|
||||
@@ -12,6 +12,9 @@ import { SettingsCard, SettingsColumns, StatusPill } from '../Settings/settingsK
|
||||
import { type Addon, type CollabFeatures, COLLAB_SUB_FEATURES, getAddonLabel } from './addons/addonModel'
|
||||
import { useAddonManager } from './addons/useAddonManager'
|
||||
import AiAddonTile from './addons/AiAddonTile'
|
||||
import MailIngestAddonTile from './mailIngest/MailIngestAddonTile'
|
||||
import PaddleRegionsPanel from './paddle/PaddleRegionsPanel'
|
||||
import ToggleSwitch from '../Settings/ToggleSwitch'
|
||||
import { ImmichIcon, SynologyIcon } from './addons/PhotoProviderIcons'
|
||||
import WandererMark from '../Tours/wanderer/WandererMark'
|
||||
|
||||
@@ -65,13 +68,24 @@ const TYPE_META: Record<string, { icon: ComponentType<{ size?: number }>; labelK
|
||||
integration: { icon: Link2, labelKey: 'admin.addons.type.integration', hintKey: 'admin.addons.integrationHint' },
|
||||
}
|
||||
|
||||
export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, aside }: {
|
||||
/** The live flight status switch, an instance setting that sits with the trip addons. */
|
||||
export interface FlightLiveOption {
|
||||
on: boolean
|
||||
/** The server environment (FLIGHT_LIVE_ENABLED) holds it; the switch shows the state and says why. */
|
||||
locked: boolean
|
||||
managed: boolean
|
||||
onToggle: () => void
|
||||
}
|
||||
|
||||
export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, flightLive, mailImport = false }: {
|
||||
bagTrackingEnabled?: boolean
|
||||
onToggleBagTracking?: () => void
|
||||
collabFeatures?: CollabFeatures
|
||||
onToggleCollabFeature?: (key: string) => void
|
||||
/** Cards that set up what the integrations reach (flight status, booking mails), under them in the right column. */
|
||||
aside?: ReactNode
|
||||
/** Live flight status, a row of the trip card: it follows the trips' booked flights. */
|
||||
flightLive?: FlightLiveOption
|
||||
/** Booking mail import, a row of the integration card with its setup dialog; off on a managed install. */
|
||||
mailImport?: boolean
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const {
|
||||
@@ -181,6 +195,8 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
onToggle={() => void toggle()}
|
||||
/>
|
||||
)),
|
||||
// The paddle water data the tour planner reads, set up in a dialog of its own.
|
||||
<PaddleRegionsPanel key="paddle-regions" />,
|
||||
]
|
||||
}
|
||||
return null
|
||||
@@ -202,6 +218,9 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether a card holds rows beside its own addons: the AI tile, an instance option. */
|
||||
const extraRows = (key: string) =>
|
||||
(key === 'trip' && !!flightLive) || (key === 'integration' && (aiAddons.length > 0 || mailImport))
|
||||
/* A card per type, the way every other admin tab sets its cards: Trip in the
|
||||
left column, Global and Integration in the right one, each card with the
|
||||
dialogs' head band carrying the type, its count and what it means. */
|
||||
@@ -209,14 +228,14 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
{ key: 'trip', addons: tripAddons },
|
||||
{ key: 'global', addons: globalAddons },
|
||||
{ key: 'integration', addons: integrationAddons },
|
||||
].filter(g => g.addons.length > 0 || (g.key === 'integration' && aiAddons.length > 0))
|
||||
].filter(g => g.addons.length > 0 || extraRows(g.key))
|
||||
|
||||
const card = (g: (typeof groups)[number]) => {
|
||||
const meta = TYPE_META[g.key]
|
||||
const all = g.key === 'integration' ? [...aiAddons, ...g.addons] : g.addons
|
||||
const visible = g.addons
|
||||
const ai = g.key === 'integration' && aiAddons.length > 0
|
||||
if (!visible.length && !ai) return null
|
||||
if (!visible.length && !ai && !extraRows(g.key)) return null
|
||||
const on = all.filter(a => a.enabled).length
|
||||
return (
|
||||
<SettingsCard
|
||||
@@ -235,6 +254,10 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
{/* The AI addons share a connection and a settings dialog, so they head the card as one tile. */}
|
||||
{ai && <AiAddonTile addons={aiAddons} onToggle={handleToggle} />}
|
||||
{visible.map(tile)}
|
||||
{/* Not addons but instance options of the same kind, as rows of the same card;
|
||||
the count above stays the addons'. */}
|
||||
{g.key === 'trip' && flightLive && <FlightLiveTile option={flightLive} />}
|
||||
{g.key === 'integration' && mailImport && <MailIngestAddonTile />}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
)
|
||||
@@ -251,5 +274,21 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
)
|
||||
}
|
||||
|
||||
return <SettingsColumns start={cards.start} end={<>{cards.end}{aside}</>} />
|
||||
return <SettingsColumns start={cards.start} end={cards.end} />
|
||||
}
|
||||
|
||||
/** Live flight status as a trip row: on, it follows every booked flight on its day. */
|
||||
function FlightLiveTile({ option }: { option: FlightLiveOption }) {
|
||||
const { t } = useTranslation()
|
||||
const name = t('flightLive.adminTitle')
|
||||
const hint = option.managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')
|
||||
return (
|
||||
<AddonTile
|
||||
icon={<Radar size={18} />}
|
||||
name={name}
|
||||
description={option.locked ? `${hint} ${t('flightLive.envLocked')}` : hint}
|
||||
enabled={option.on}
|
||||
trailing={<ToggleSwitch on={option.on} label={t('flightLive.adminToggle')} disabled={option.locked} onToggle={option.onToggle} />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import React, { useId, type ReactNode } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
} from '../shared/DialogShell';
|
||||
|
||||
/**
|
||||
* The dialog an addon's setup row opens: the icon tile, the addon it belongs
|
||||
* to above the title, what it sets up below, and one Close, since everything
|
||||
* inside saves on its own (booking mails, paddle water data).
|
||||
*/
|
||||
export default function AddonSetupDialog({
|
||||
icon,
|
||||
eyebrow,
|
||||
title,
|
||||
sub,
|
||||
onClose,
|
||||
blocked = false,
|
||||
children,
|
||||
}: {
|
||||
icon: ReactNode;
|
||||
eyebrow: string;
|
||||
title: string;
|
||||
sub: string;
|
||||
onClose: () => void;
|
||||
/** A confirmation stacked on top holds the dialog while it is open. */
|
||||
blocked?: boolean;
|
||||
children: ReactNode;
|
||||
}): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const labelId = useId();
|
||||
return (
|
||||
<DialogShell
|
||||
onClose={onClose}
|
||||
labelledBy={labelId}
|
||||
width="detail"
|
||||
blocked={blocked}
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={<DialogTile>{icon}</DialogTile>}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={labelId}
|
||||
eyebrow={eyebrow}
|
||||
title={title}
|
||||
sub={sub}
|
||||
subWraps
|
||||
onClose={onClose}
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
<DialogButton variant="primary" onClick={onClose}>
|
||||
{t('common.close')}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { ChevronRight, Settings2 } from 'lucide-react';
|
||||
import React, { type ReactNode } from 'react';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
|
||||
/**
|
||||
* The last row of an addon's shelf that opens its settings dialog: a gear, what
|
||||
* the dialog sets up, and a chevron. It keeps a card of addons as short as its
|
||||
* switches and puts the long forms behind one tap (AI, booking mails, paddle
|
||||
* water data). A badge says what waits inside, such as requests to look at.
|
||||
*/
|
||||
export default function AddonSetupRow({
|
||||
label,
|
||||
onOpen,
|
||||
badge,
|
||||
}: {
|
||||
label: string;
|
||||
onOpen: () => void;
|
||||
badge?: ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex min-h-[44px] w-full items-center gap-2.5 border-0 bg-transparent py-1.5 pe-4 ps-[60px] text-start transition-colors hover:bg-surface-hover focus-visible:bg-surface-hover focus-visible:outline-none"
|
||||
>
|
||||
<span className="grid h-6 w-6 flex-none place-items-center text-content-muted">
|
||||
<Settings2 size={14} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12.5, 'body')}>
|
||||
{label}
|
||||
</span>
|
||||
{badge}
|
||||
<ChevronRight size={15} strokeWidth={2.2} className="flex-none text-content-faint rtl:rotate-180" />
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { ChevronRight, Settings2, Sparkles } from 'lucide-react';
|
||||
import { Sparkles } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { StatusPill } from '../../Settings/settingsKit';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import AddonSetupRow from '../AddonSetupRow';
|
||||
import AddonSubRow from '../AddonSubRow';
|
||||
import AddonTile from '../AddonTile';
|
||||
import { type Addon, getAddonLabel } from './addonModel';
|
||||
@@ -54,23 +55,7 @@ export default function AiAddonTile({
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{tile.canSetUp && (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
onClick={tile.openDialog}
|
||||
className="flex min-h-[44px] w-full items-center gap-2.5 border-0 bg-transparent py-1.5 pe-4 ps-[60px] text-start transition-colors hover:bg-surface-hover focus-visible:bg-surface-hover focus-visible:outline-none"
|
||||
>
|
||||
<span className="grid h-6 w-6 flex-none place-items-center text-content-muted">
|
||||
<Settings2 size={14} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12.5, 'body')}>
|
||||
{t('admin.addons.ai.setup')}
|
||||
</span>
|
||||
<ChevronRight size={15} strokeWidth={2.2} className="flex-none text-content-faint rtl:rotate-180" />
|
||||
</button>
|
||||
</li>
|
||||
)}
|
||||
{tile.canSetUp && <AddonSetupRow label={t('admin.addons.ai.setup')} onOpen={tile.openDialog} />}
|
||||
</AddonTile>
|
||||
{tile.dialogOpen && <AiSettingsDialog addons={addons} onClose={tile.closeDialog} />}
|
||||
</>
|
||||
|
||||
+42
-33
@@ -1,22 +1,17 @@
|
||||
import { AlertTriangle, CheckCircle, Copy, Loader2, Mail, PlugZap, Save, XCircle } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { copyText } from '../../../utils/clipboard';
|
||||
import { relativeTime } from '../../../utils/relativeTime';
|
||||
import {
|
||||
HintMark,
|
||||
SETTINGS_BUTTON,
|
||||
SETTINGS_BUTTON_PRIMARY,
|
||||
SettingRow,
|
||||
SettingRows,
|
||||
SettingsCard,
|
||||
StatusPill,
|
||||
} from '../../Settings/settingsKit';
|
||||
import { HintMark, SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, StatusPill } from '../../Settings/settingsKit';
|
||||
import ToggleSwitch from '../../Settings/ToggleSwitch';
|
||||
import CustomSelect from '../../shared/CustomSelect';
|
||||
import { EditorField, GRID_2, INPUT, READONLY_BOX } from '../../shared/dialogParts';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import AddonSetupDialog from '../AddonSetupDialog';
|
||||
import AddonSetupRow from '../AddonSetupRow';
|
||||
import AddonTile from '../AddonTile';
|
||||
import {
|
||||
TRANSPORTS,
|
||||
problemText,
|
||||
@@ -306,32 +301,46 @@ function Setup({ admin, form, t, locale }: { admin: MailIngestAdmin; form: MailA
|
||||
}
|
||||
|
||||
/**
|
||||
* The booking mail import in the admin settings of a self-hosted install: the
|
||||
* instance switch, how mail arrives (IMAP or a signed webhook), the forwarding
|
||||
* address template, the AI allowance per person and day, a connection test and
|
||||
* the status in counts. Not shown on a managed install, where the operator
|
||||
* runs the TREK Cloud relay.
|
||||
* The booking mail import as a row of the integration card: its switch, and
|
||||
* while it is on one row to the dialog that sets it up (how mail arrives, the
|
||||
* forwarding address template, the AI allowance per person and day, a
|
||||
* connection test and the status in counts). Not shown on a managed install,
|
||||
* where the operator runs the TREK Cloud relay.
|
||||
*/
|
||||
export default function MailIngestAdminCard() {
|
||||
export default function MailIngestAddonTile() {
|
||||
const { t, locale } = useTranslation();
|
||||
const admin = useMailIngestAdmin(true);
|
||||
const [open, setOpen] = useState(false);
|
||||
const name = t('mailAdmin.title');
|
||||
return (
|
||||
<SettingsCard icon={Mail} title={t('mailAdmin.title')} hint={t('mailAdmin.hint')}>
|
||||
<SettingRows>
|
||||
<SettingRow
|
||||
label={t('mailAdmin.enabled')}
|
||||
hint={t('mailAdmin.enabledHint')}
|
||||
control={
|
||||
<ToggleSwitch
|
||||
on={admin.enabled}
|
||||
label={t('mailAdmin.enabled')}
|
||||
disabled={!admin.loaded}
|
||||
onToggle={() => admin.toggle(!admin.enabled)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingRows>
|
||||
{admin.enabled && admin.form && <Setup admin={admin} form={admin.form} t={t} locale={locale} />}
|
||||
</SettingsCard>
|
||||
<>
|
||||
<AddonTile
|
||||
icon={<Mail size={15} />}
|
||||
name={name}
|
||||
description={`${t('mailAdmin.hint')} ${t('mailAdmin.enabledHint')}`}
|
||||
enabled={admin.enabled}
|
||||
trailing={
|
||||
<ToggleSwitch
|
||||
on={admin.enabled}
|
||||
label={t('mailAdmin.enabled')}
|
||||
disabled={!admin.loaded}
|
||||
onToggle={() => admin.toggle(!admin.enabled)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{admin.enabled && admin.form && <AddonSetupRow label={t('mailAdmin.setup')} onOpen={() => setOpen(true)} />}
|
||||
</AddonTile>
|
||||
{open && admin.enabled && admin.form && (
|
||||
<AddonSetupDialog
|
||||
icon={<Mail size={20} strokeWidth={2} />}
|
||||
eyebrow={name}
|
||||
title={t('mailAdmin.setup')}
|
||||
sub={t('mailAdmin.hint')}
|
||||
onClose={() => setOpen(false)}
|
||||
>
|
||||
<Setup admin={admin} form={admin.form} t={t} locale={locale} />
|
||||
</AddonSetupDialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -78,17 +78,22 @@ function adminState(overrides: Partial<Admin> = {}, search: Partial<Admin['searc
|
||||
};
|
||||
}
|
||||
|
||||
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}) {
|
||||
/** The panel as the Tours shelf shows it: a setup row, opened into its dialog unless asked not to. */
|
||||
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}, { open = true } = {}) {
|
||||
const state = adminState(overrides, search);
|
||||
hook.usePaddleRegionsAdmin.mockReturnValue(state);
|
||||
return { state, ...render(<PaddleRegionsPanel />) };
|
||||
const view = render(
|
||||
<ul>
|
||||
<PaddleRegionsPanel />
|
||||
</ul>
|
||||
);
|
||||
if (open && state.toursOn) fireEvent.click(setupRow());
|
||||
return { state, ...view };
|
||||
}
|
||||
|
||||
/** The card's title row, where the number of regions sits beside the title. */
|
||||
function titleRow(): HTMLElement {
|
||||
const row = screen.getByRole('heading', { name: 'Paddle water data' }).parentElement;
|
||||
if (!row) throw new Error('no title row');
|
||||
return row;
|
||||
/** The shelf row that opens the dialog, where the count of requests or regions sits beside the title. */
|
||||
function setupRow(): HTMLElement {
|
||||
return screen.getAllByRole('button', { name: /^Paddle water data/ })[0];
|
||||
}
|
||||
|
||||
function rowOf(name: string): HTMLElement {
|
||||
@@ -100,7 +105,7 @@ function rowOf(name: string): HTMLElement {
|
||||
describe('PaddleRegionsPanel', () => {
|
||||
it('FE-ADMIN-PADDLEREG-001: renders nothing while the Tours addon is off', () => {
|
||||
const { container } = show({ toursOn: false, regions: [READY] });
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
expect(container.querySelector('ul')).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-002: shows the card with its hint, the attribution and the empty state', () => {
|
||||
@@ -110,7 +115,7 @@ describe('PaddleRegionsPanel', () => {
|
||||
expect(screen.getByText(EMPTY)).toBeInTheDocument();
|
||||
expect(screen.getByText(ATTRIBUTION)).toBeInTheDocument();
|
||||
// No count beside the title while there is no region.
|
||||
expect(titleRow()).toHaveTextContent(/^Paddle water data$/);
|
||||
expect(setupRow()).toHaveTextContent(/^Paddle water data$/);
|
||||
const search = screen.getByRole('searchbox', { name: 'Add a region' });
|
||||
expect(search).toBeEnabled();
|
||||
expect(search).toHaveAttribute('placeholder', 'Search Geofabrik, for example Oberpfalz');
|
||||
@@ -277,12 +282,31 @@ describe('PaddleRegionsPanel', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-019: the title carries the number of regions', () => {
|
||||
it('FE-ADMIN-PADDLEREG-019: the setup row carries the open requests, else the number of regions', () => {
|
||||
show({ regions: [READY, WAITING, FAILED_FIRST] });
|
||||
expect(within(titleRow()).getByText('3')).toBeInTheDocument();
|
||||
expect(within(setupRow()).getByText('3')).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('paddle-region-row')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-019b: an open request outranks the region count, a declined one does not count', () => {
|
||||
const base = { bytes: 1, requested_by: 'elmo', requested_at: '2026-10-18T09:00:00Z' };
|
||||
show(
|
||||
{
|
||||
regions: [READY, WAITING],
|
||||
requests: [
|
||||
{ ...base, id: 'norway', name: 'Norway', reason: 'too_large', declined: true },
|
||||
{ ...base, id: 'saale', name: 'Saale', reason: 'limit', declined: false },
|
||||
],
|
||||
},
|
||||
{},
|
||||
{ open: false }
|
||||
);
|
||||
expect(within(setupRow()).getByText('1')).toBeInTheDocument();
|
||||
expect(within(setupRow()).queryByText('2')).toBeNull();
|
||||
// Closed until the row is opened.
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-PADDLEREG-020: removing asks first, naming the region, and confirming hands it to the hook', () => {
|
||||
const { state } = show({ regions: [READY], removing: READY });
|
||||
const message = 'Oberpfalz and its obstacle data are removed. Paddle tours there then show no data.';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared';
|
||||
import { Check, ChevronRight, Loader2, Plus, RefreshCw, Search, Trash2, Waves, WifiOff } from 'lucide-react';
|
||||
import { useId } from 'react';
|
||||
import { useId, useState } from 'react';
|
||||
import { useDateFormat } from '../../../hooks/useDateFormat';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { formatDisplayDate } from '../../../utils/dateFormat';
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
SettingRows,
|
||||
SETTINGS_BUTTON,
|
||||
SETTINGS_ICON_BUTTON,
|
||||
SettingsCard,
|
||||
SettingsHint,
|
||||
StatusPill,
|
||||
} from '../../Settings/settingsKit';
|
||||
@@ -17,6 +16,8 @@ import { EditorField, INPUT } from '../../shared/dialogParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import ErrorBoundary from '../../shared/ErrorBoundary';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import AddonSetupDialog from '../AddonSetupDialog';
|
||||
import AddonSetupRow from '../AddonSetupRow';
|
||||
import { AutoLoadSettings, AutoOriginPill, RequestList } from './PaddleAutoLoadParts';
|
||||
import { progressPercent, regionStatusTone } from './paddleRegionsModel';
|
||||
import { usePaddleRegionsAdmin } from './usePaddleRegionsAdmin';
|
||||
@@ -27,8 +28,10 @@ type Admin = ReturnType<typeof usePaddleRegionsAdmin>;
|
||||
* PAD-05A in the admin area: the regions TREK reads paddle obstacles for,
|
||||
* picked from Geofabrik's list, and (PAD-11C) how TREK loads the region of a
|
||||
* place a paddler plans in by itself, with the regions that wait for an admin.
|
||||
* The desktop admin shows this card under the addons while the Tours addon
|
||||
* is on; the phone has MAdminPaddleRegionsPanel on the same hook.
|
||||
* The desktop admin shows it as a row of the Tours addon that opens it as a
|
||||
* dialog while the addon is on; the row counts what waits for the admin (the
|
||||
* requests) or else the regions. The phone has MAdminPaddleRegionsPanel on
|
||||
* the same hook.
|
||||
*/
|
||||
export default function PaddleRegionsPanel() {
|
||||
return (
|
||||
@@ -41,14 +44,42 @@ export default function PaddleRegionsPanel() {
|
||||
function Panel() {
|
||||
const { t } = useTranslation();
|
||||
const admin = usePaddleRegionsAdmin();
|
||||
const [open, setOpen] = useState(false);
|
||||
if (!admin.toursOn) return null;
|
||||
const title = t('admin.paddleRegions.title');
|
||||
// A declined request no longer waits for anyone; only the open ones ask for a look.
|
||||
const waiting = admin.requests.filter((r) => !r.declined).length;
|
||||
const badge =
|
||||
waiting > 0 ? (
|
||||
<StatusPill tone="warning">{waiting}</StatusPill>
|
||||
) : admin.regions.length > 0 ? (
|
||||
<StatusPill>{admin.regions.length}</StatusPill>
|
||||
) : undefined;
|
||||
const close = () => setOpen(false);
|
||||
return (
|
||||
<SettingsCard
|
||||
icon={Waves}
|
||||
title={t('admin.paddleRegions.title')}
|
||||
hint={t('admin.paddleRegions.hint')}
|
||||
badge={admin.regions.length > 0 ? <StatusPill>{admin.regions.length}</StatusPill> : undefined}
|
||||
>
|
||||
<>
|
||||
<AddonSetupRow label={title} onOpen={() => setOpen(true)} badge={badge} />
|
||||
{open && (
|
||||
<AddonSetupDialog
|
||||
icon={<Waves size={20} strokeWidth={2} />}
|
||||
eyebrow={t('admin.addons.catalog.tours.name')}
|
||||
title={title}
|
||||
sub={t('admin.paddleRegions.hint')}
|
||||
onClose={close}
|
||||
blocked={admin.removing !== null}
|
||||
>
|
||||
<PanelBody admin={admin} />
|
||||
</AddonSetupDialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the dialog holds: the state of the list, the settings, the requests, the search and the regions. */
|
||||
function PanelBody({ admin }: { admin: Admin }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{admin.offline && (
|
||||
<p
|
||||
role="status"
|
||||
@@ -86,7 +117,7 @@ function Panel() {
|
||||
message={t('admin.paddleRegions.removeMessage', { name: admin.removing?.name ?? '' })}
|
||||
confirmLabel={t('common.remove')}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
|
||||
photoId: 7,
|
||||
video: false,
|
||||
photoCount: 1,
|
||||
visibility: 'private',
|
||||
draft: false,
|
||||
fromTripPlace: false,
|
||||
dayIndex: 0,
|
||||
@@ -86,13 +85,15 @@ afterEach(() => {
|
||||
|
||||
describe('the journal entries card', () => {
|
||||
it('FE-AI-JOURNEY-001: one entry reads as a row with its photo, facts, marks and text under the journal', () => {
|
||||
const { container } = block([card([look({ visibility: 'public', draft: true, photoCount: 4, video: true })])]);
|
||||
// A card stored while entries carried a visibility: it reads, and says nothing of it.
|
||||
const stored = { ...look({ draft: true, photoCount: 4, video: true }), visibility: 'public' };
|
||||
const { container } = block([card([stored])]);
|
||||
expect(screen.getByRole('region', { name: 'Journal entries' })).toBeInTheDocument();
|
||||
expect(screen.getByText('Sunset at the Spree')).toBeInTheDocument();
|
||||
expect(screen.getByText('14:30')).toBeInTheDocument();
|
||||
expect(screen.getByText('Berlin')).toBeInTheDocument();
|
||||
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Public')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Public')).toBeNull();
|
||||
expect(screen.getByText('Draft')).toBeInTheDocument();
|
||||
expect(screen.getByText('4 photos')).toBeInTheDocument();
|
||||
expect(screen.getByText('Opens with a video')).toBeInTheDocument();
|
||||
@@ -225,13 +226,12 @@ describe('a change row of a journal entry', () => {
|
||||
}
|
||||
|
||||
it('FE-AI-JOURNEY-008: a waiting delete shows the photo, the text and that it goes back to a suggestion; a receipt opens it', () => {
|
||||
const entry = look({ fromTripPlace: true, visibility: 'shared' });
|
||||
const entry = look({ fromTripPlace: true });
|
||||
const held = card([entry], { change: 'willDelete', tripJournal: true });
|
||||
const onOpen = vi.fn();
|
||||
const first = inView(<AssistantChangeCard items={[item('pending', held)]} />, { onOpen });
|
||||
expect(screen.getByText('Delete the journal entry')).toBeInTheDocument();
|
||||
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Shared')).toBeInTheDocument();
|
||||
expect(screen.getByText('Goes back to a suggestion')).toBeInTheDocument();
|
||||
expect(screen.getByText('Tue, Oct 21')).toBeInTheDocument();
|
||||
expect(screen.getByText('Museum Island')).toBeInTheDocument();
|
||||
@@ -255,7 +255,6 @@ describe('a change row of a journal entry', () => {
|
||||
{ op: 'change', labelKey: 'name', before: 'Sunset', after: 'Sunset at the Spree' },
|
||||
{ op: 'change', labelKey: 'time', before: '14:30', after: '' },
|
||||
{ op: 'change', labelKey: 'text', before: 'Old story', after: 'New story' },
|
||||
{ op: 'change', labelKey: 'field', field: 'visibility', before: 'private', after: 'public' },
|
||||
{ op: 'change', labelKey: 'field', field: 'mood', before: 'good', after: '' },
|
||||
{ op: 'change', labelKey: 'field', field: 'weather', before: 'sunny', after: 'Drizzle' },
|
||||
{ op: 'change', labelKey: 'field', field: 'is_draft', before: '✓', after: '✗' },
|
||||
@@ -267,8 +266,6 @@ describe('a change row of a journal entry', () => {
|
||||
expect(screen.getByText('14:30')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Old story')).toHaveClass('line-through');
|
||||
expect(screen.getByText('New story')).toBeInTheDocument();
|
||||
expect(screen.getByText('Private')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Public')).toBeInTheDocument();
|
||||
expect(screen.getByText('Good')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Sunny')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Drizzle')).toBeInTheDocument();
|
||||
|
||||
@@ -28,7 +28,6 @@ const ENTRY: JourneyEntryLook = {
|
||||
photoId: null,
|
||||
video: false,
|
||||
photoCount: 0,
|
||||
visibility: 'private',
|
||||
draft: false,
|
||||
fromTripPlace: false,
|
||||
dayIndex: null,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { JourneyEntryLook } from '@trek/shared';
|
||||
import { CalendarDays, Globe, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp, Users } from 'lucide-react';
|
||||
import { CalendarDays, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp } from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { cardDateLabel, cardPlace } from '../../../Journey/journeyCard';
|
||||
@@ -12,8 +12,8 @@ import { moodOf, weatherOf } from './journeyTones';
|
||||
/**
|
||||
* The pieces a journal entry is drawn from in the chat, the same in an
|
||||
* answer, a change row and a receipt: its photo, the facts of when and where
|
||||
* as the planner's badges, the marks of how it reads (shared, draft, mood,
|
||||
* weather, more photos) and the start of its text. Every fact wraps, none is
|
||||
* as the planner's badges, the marks of how it reads (draft, mood, weather,
|
||||
* more photos) and the start of its text. Every fact wraps, none is
|
||||
* cut.
|
||||
*/
|
||||
|
||||
@@ -63,19 +63,6 @@ export function EntryWhen({ look }: { look: JourneyEntryLook }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Shared or public; nothing for a private entry. */
|
||||
function VisibilityMark({ visibility }: { visibility: JourneyEntryLook['visibility'] }) {
|
||||
const { t } = useTranslation();
|
||||
if (visibility === 'private') return null;
|
||||
const shared = visibility === 'shared';
|
||||
const Icon = shared ? Users : Globe;
|
||||
return (
|
||||
<SoftPill tone="info" icon={<Icon size={10} strokeWidth={2.2} aria-hidden="true" />}>
|
||||
{shared ? t('journey.visibility.shared') : t('journey.visibility.public')}
|
||||
</SoftPill>
|
||||
);
|
||||
}
|
||||
|
||||
/** A mood the journal knows, in its own colour; nothing for any other. */
|
||||
function MoodMark({ id }: { id: string | null }) {
|
||||
const { t } = useTranslation();
|
||||
@@ -129,17 +116,16 @@ function ListMarks({ look }: { look: JourneyEntryLook }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** How the entry reads: shared or public, a draft, its mood and weather, its photos past the first, its tags and verdict. */
|
||||
/** How the entry reads: a draft, its mood and weather, its photos past the first, its tags and verdict. */
|
||||
export function EntryMarks({ look }: { look: JourneyEntryLook }) {
|
||||
const { t } = useTranslation();
|
||||
const mood = moodOf(look.mood) !== null;
|
||||
const lists = (look.tags?.length ?? 0) > 0 || !!look.verdict;
|
||||
if (look.visibility === 'private' && !look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
|
||||
if (!look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<CardFacts>
|
||||
<VisibilityMark visibility={look.visibility} />
|
||||
{look.draft && <SoftPill tone="warning">{t('journey.entry.draft')}</SoftPill>}
|
||||
<MoodMark id={look.mood} />
|
||||
<WeatherMark weather={look.weather} />
|
||||
|
||||
@@ -31,7 +31,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
|
||||
photoId: null,
|
||||
video: false,
|
||||
photoCount: 0,
|
||||
visibility: 'private',
|
||||
draft: false,
|
||||
fromTripPlace: false,
|
||||
dayIndex: null,
|
||||
@@ -97,12 +96,13 @@ describe('journeyCardModel', () => {
|
||||
});
|
||||
|
||||
it('FE-AI-JOURNEY-MODEL-009: the states an update sets are named by field, flags by on and off', () => {
|
||||
expect(stateOf('visibility', 'public')?.labelKey).toBe('journey.visibility.public');
|
||||
// The stored visibility keeps nothing off the share link, so it has no name to show.
|
||||
expect(stateOf('visibility', 'private')).toBeNull();
|
||||
expect(stateOf('type', 'skeleton')?.labelKey).toBe('journey.entry.suggestion');
|
||||
expect(stateOf('mood', 'good')?.labelKey).toBe('journey.mood.good');
|
||||
expect(stateOf('weather', 'cold')?.labelKey).toBe('journey.weather.cold');
|
||||
expect(stateOf('weather', 'Drizzle')).toBeNull();
|
||||
expect(stateOf('visibility', 'toString')).toBeNull();
|
||||
expect(stateOf('type', 'toString')).toBeNull();
|
||||
expect(stateOf(undefined, 'public')).toBeNull();
|
||||
expect(flagOf('is_draft', '✓')?.labelKey).toBe('journey.entry.draft');
|
||||
expect(flagOf('is_draft', '✗')?.labelKey).toBe('assistant.card.journey.notDraft');
|
||||
|
||||
@@ -7,8 +7,6 @@ import {
|
||||
Eye,
|
||||
EyeOff,
|
||||
Frown,
|
||||
Globe,
|
||||
Lock,
|
||||
type LucideIcon,
|
||||
MapPinCheck,
|
||||
Meh,
|
||||
@@ -19,14 +17,13 @@ import {
|
||||
Snowflake,
|
||||
Sparkles,
|
||||
Sun,
|
||||
Users,
|
||||
} from 'lucide-react';
|
||||
|
||||
/**
|
||||
* How the states of a journal entry read in the chat, the way the journal
|
||||
* draws them: its moods with the glyphs of its tiles, its weathers, and the
|
||||
* words for what an update sets beyond the text (who sees the entry, its
|
||||
* kind, a draft, the route, a waved-away suggestion).
|
||||
* words for what an update sets beyond the text (its kind, a draft, the
|
||||
* route, a waved-away suggestion).
|
||||
*/
|
||||
|
||||
/** How a state is drawn: its glyph and the key of its name. */
|
||||
@@ -57,12 +54,6 @@ const WEATHERS: Readonly<Record<string, EntryTone>> = {
|
||||
cold: { Icon: Snowflake, labelKey: 'journey.weather.cold' },
|
||||
};
|
||||
|
||||
const VISIBILITIES: Readonly<Record<string, EntryTone>> = {
|
||||
private: { Icon: Lock, labelKey: 'journey.visibility.private' },
|
||||
shared: { Icon: Users, labelKey: 'journey.visibility.shared' },
|
||||
public: { Icon: Globe, labelKey: 'journey.visibility.public' },
|
||||
};
|
||||
|
||||
const TYPES: Readonly<Record<string, EntryTone>> = {
|
||||
entry: { Icon: BookOpenText, labelKey: 'assistant.card.journey.typeEntry' },
|
||||
checkin: { Icon: MapPinCheck, labelKey: 'assistant.card.journey.typeCheckin' },
|
||||
@@ -119,7 +110,6 @@ export function flagOf(field: string | undefined, value: string): EntryTone | nu
|
||||
export function stateOf(field: string | undefined, value: string | null): EntryTone | null {
|
||||
if (field === 'mood') return moodOf(value);
|
||||
if (field === 'weather') return weatherOf(value);
|
||||
if (field === 'visibility') return own(VISIBILITIES, value);
|
||||
if (field === 'type') return own(TYPES, value);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { OnlineOnlyError } from '../../repo/onlineOnly';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useCanDo } from '../../store/permissionsStore';
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { chatTextOf } from './assistantShare';
|
||||
@@ -35,7 +36,10 @@ export function useAssistantShare(tripId: number, message: AssistantMessage, wri
|
||||
const { offline } = useNetworkMode();
|
||||
const can = useCanDo();
|
||||
const trip = useTripStore((s) => (s.trip?.id === tripId ? s.trip : null));
|
||||
const chatOn = useAddonStore((s) => s.collabChat && s.addons.some((a) => a.id === 'collab' && a.enabled));
|
||||
// The chat is an instance-wide part of Collab, which this trip may have on or off.
|
||||
const chatFeatureOn = useAddonStore((s) => s.collabChat);
|
||||
const collabOn = useTripAddonEnabled(tripId, 'collab');
|
||||
const chatOn = chatFeatureOn && collabOn;
|
||||
const threadId = useAssistantStore((s) => chatOf(s, tripId).threadId);
|
||||
const [previewing, setPreviewing] = useState(false);
|
||||
const [includeChanges, setIncludeChanges] = useState(true);
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { render, waitFor } from '../../../tests/helpers/render';
|
||||
import { offlineDb } from '../../db/offlineDb';
|
||||
import type { Day, Trip } from '../../types';
|
||||
|
||||
const published = vi.hoisted(() => ({ calls: [] as unknown[][] }));
|
||||
|
||||
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(async () => ({ remove: vi.fn() })) } }));
|
||||
vi.mock('../../native/capabilities', () => ({ useNativeCapabilities: () => ({ caps: {} }) }));
|
||||
vi.mock('../../native/watch', () => ({
|
||||
applyWatchActions: vi.fn(async () => []),
|
||||
buildWatchSnapshot: vi.fn(),
|
||||
publishWatch: vi.fn(async () => {}),
|
||||
takeWatchActions: vi.fn(async () => []),
|
||||
watchActive: () => false,
|
||||
}));
|
||||
vi.mock('../../native/widgetMedia', () => ({
|
||||
widgetCover: vi.fn(async () => null),
|
||||
widgetWeather: vi.fn(async () => null),
|
||||
}));
|
||||
vi.mock('../../native/widgetOnline', () => ({
|
||||
atlasSummary: vi.fn(async () => null),
|
||||
collabSummary: vi.fn(async () => null),
|
||||
packingDetail: vi.fn(async () => null),
|
||||
}));
|
||||
vi.mock('../../native/widgets', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../native/widgets')>();
|
||||
return {
|
||||
...actual,
|
||||
widgetsActive: () => true,
|
||||
publishWidgets: vi.fn(async (...args: unknown[]) => {
|
||||
published.calls.push(args);
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
import { collabSummary, packingDetail } from '../../native/widgetOnline';
|
||||
import NativeWidgetsSync from './NativeWidgetsSync';
|
||||
|
||||
const trip = {
|
||||
id: 7,
|
||||
title: 'Lisbon',
|
||||
start_date: '2026-11-06',
|
||||
end_date: '2026-11-08',
|
||||
is_archived: 0,
|
||||
} as unknown as Trip;
|
||||
const day = (id: number, n: number, date: string, name: string) =>
|
||||
({
|
||||
id,
|
||||
trip_id: 7,
|
||||
day_number: n,
|
||||
date,
|
||||
assignments: [{ id: id * 10, order_index: 0, place: { name, place_time: '10:00' } }],
|
||||
}) as unknown as Day;
|
||||
|
||||
describe('NativeWidgetsSync', () => {
|
||||
beforeEach(async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(new Date(2026, 10, 7, 9, 0));
|
||||
published.calls = [];
|
||||
await offlineDb.trips.put(trip as never);
|
||||
await offlineDb.days.bulkPut([
|
||||
day(1, 1, '2026-11-06', 'Castle'),
|
||||
day(2, 2, '2026-11-07', 'Harbour'),
|
||||
day(3, 3, '2026-11-08', 'Market'),
|
||||
] as never);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await offlineDb.trips.clear();
|
||||
await offlineDb.days.clear();
|
||||
await offlineDb.todoItems.clear();
|
||||
await offlineDb.tripAddons.clear();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WSYNC-001: writes today and every day ahead, so the widgets turn the day without the app', async () => {
|
||||
render(<NativeWidgetsSync />);
|
||||
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
|
||||
const snapshot = published.calls[0][0] as {
|
||||
today: { date: string; stops: { name: string }[] } | null;
|
||||
days: { date: string; stops: { name: string }[] }[];
|
||||
};
|
||||
expect(snapshot.today).toMatchObject({ date: '2026-11-07', stops: [{ name: 'Harbour' }] });
|
||||
expect(snapshot.days.map((d) => [d.date, d.stops[0]?.name])).toEqual([
|
||||
['2026-11-07', 'Harbour'],
|
||||
['2026-11-08', 'Market'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WSYNC-002: a trip with Lists and Collab switched off shows neither its todos nor its chat', async () => {
|
||||
await offlineDb.todoItems.put({ id: 70, trip_id: 7, name: 'Book ferry', checked: 0 } as never);
|
||||
const off = (id: string) => ({ id, name: id, icon: null, enabled: false, instanceEnabled: true, overridden: true });
|
||||
await offlineDb.tripAddons.put({ tripId: 7, addons: [off('packing'), off('collab')] });
|
||||
vi.mocked(packingDetail).mockClear();
|
||||
vi.mocked(collabSummary).mockClear();
|
||||
|
||||
render(<NativeWidgetsSync />);
|
||||
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
|
||||
const snapshot = published.calls[0][0] as { todos?: unknown; collab?: unknown };
|
||||
expect(snapshot.todos).toBeUndefined();
|
||||
expect(snapshot.collab).toBeUndefined();
|
||||
expect(vi.mocked(packingDetail)).not.toHaveBeenCalled();
|
||||
expect(vi.mocked(collabSummary)).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-WSYNC-003: a trip the device never read the addons of shows its todos, as before', async () => {
|
||||
await offlineDb.todoItems.put({ id: 71, trip_id: 7, name: 'Book ferry', checked: 0 } as never);
|
||||
|
||||
render(<NativeWidgetsSync />);
|
||||
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
|
||||
const snapshot = published.calls[0][0] as { todos?: { items?: unknown[] } };
|
||||
expect(snapshot.todos).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -25,20 +25,22 @@ import {
|
||||
liveFlightOf,
|
||||
pickTrip,
|
||||
publishWidgets,
|
||||
todayOf,
|
||||
snapshotDays,
|
||||
tripDayState,
|
||||
widgetTripChoices,
|
||||
widgetsActive,
|
||||
withBookings,
|
||||
type TripWidgetSnapshot,
|
||||
type WidgetLabels,
|
||||
} from '../../native/widgets';
|
||||
import { cachedTripAddons } from '../../repo/tripAddonsRepo';
|
||||
import { instanceAddonOn, useAddonStore } from '../../store/addonStore';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useFlightLiveStore } from '../../store/flightLiveStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Day, Place, Reservation, TranslationFn, Trip } from '../../types';
|
||||
import { formatTime } from '../../utils/formatters';
|
||||
import { tripAddonEnabled } from '../../utils/tripAddons';
|
||||
import { localDateStr } from '../../vacay/monthGrid';
|
||||
|
||||
const REFRESH_MS = 15 * 60 * 1000;
|
||||
@@ -121,15 +123,31 @@ async function flightOf(trip: Trip, reservations: Reservation[], path: string, c
|
||||
return widgetFlight(legs, Date.now(), path, { locale: context.language, timeFormat: context.timeFormat });
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the trip has Lists and Collab on, from the list the device kept for it
|
||||
* (the sync reads it with the trip). A trip it never read follows the instance,
|
||||
* and while that is not known either the widgets show both, as they always did.
|
||||
*/
|
||||
async function tripSections(tripId: number): Promise<{ lists: boolean; collab: boolean }> {
|
||||
const own = await cachedTripAddons(tripId);
|
||||
const instance = useAddonStore.getState();
|
||||
const on = (id: string) => tripAddonEnabled(own, id, instanceAddonOn(instance, id, true));
|
||||
return { lists: on('packing'), collab: on('collab') };
|
||||
}
|
||||
|
||||
async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
|
||||
const { today, language, unit, time } = context;
|
||||
const [places, reservations, todos, packing, memberRows] = await Promise.all([
|
||||
const [places, reservations, todoRows, packingRows, memberRows, sections] = await Promise.all([
|
||||
offlineDb.places.where('trip_id').equals(trip.id).toArray(),
|
||||
offlineDb.reservations.where('trip_id').equals(trip.id).toArray(),
|
||||
offlineDb.todoItems.where('trip_id').equals(trip.id).toArray(),
|
||||
offlineDb.packingItems.where('trip_id').equals(trip.id).toArray(),
|
||||
offlineDb.tripMembers.where('tripId').equals(trip.id).toArray(),
|
||||
tripSections(trip.id),
|
||||
]);
|
||||
// A trip with Lists off shows no todos or packing, on the widgets and the watch alike.
|
||||
const todos = sections.lists ? todoRows : [];
|
||||
const packing = sections.lists ? packingRows : [];
|
||||
const members = memberRows.length;
|
||||
const names = [trip.owner_username, ...memberRows.map((m) => m.username)].filter((n): n is string => !!n);
|
||||
const path = `/trips/${trip.id}`;
|
||||
@@ -145,13 +163,15 @@ async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
|
||||
const [weather, cover, bags, collab, flight] = await Promise.all([
|
||||
spot && inRange ? widgetWeather(spot, { date: weatherDate, lang: language, unit, place }) : Promise.resolve(null),
|
||||
widgetCover(trip.cover_image),
|
||||
packingDetail(trip.id, packing),
|
||||
collabSummary(
|
||||
trip.id,
|
||||
`/trips/${trip.id}?tab=collab`,
|
||||
[...new Set(names)],
|
||||
useAuthStore.getState().user?.id ?? null
|
||||
),
|
||||
sections.lists ? packingDetail(trip.id, packing) : Promise.resolve(null),
|
||||
sections.collab
|
||||
? collabSummary(
|
||||
trip.id,
|
||||
`/trips/${trip.id}?tab=collab`,
|
||||
[...new Set(names)],
|
||||
useAuthStore.getState().user?.id ?? null
|
||||
)
|
||||
: Promise.resolve(null),
|
||||
flightOf(trip, reservations, path, context),
|
||||
]);
|
||||
const packed = packingSummary(packing, `/trips/${trip.id}?tab=listen`);
|
||||
@@ -167,7 +187,7 @@ async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
|
||||
memberCount: members > 0 ? members + 1 : 0,
|
||||
weather,
|
||||
bookings: bookingsAhead(reservations, { dayDates, today, tripPath: path, formatTime: time }),
|
||||
todos: todosSummary(todos, `${path}?tab=listen`),
|
||||
todos: sections.lists ? todosSummary(todos, `${path}?tab=listen`) : undefined,
|
||||
packing: packed && bags ? { ...packed, ...bags } : packed,
|
||||
collab,
|
||||
flight,
|
||||
@@ -191,11 +211,15 @@ export default function NativeWidgetsSync(): null {
|
||||
const tripSnapshot = async (trip: Trip | null, context: SyncContext, atlas: WidgetAtlas | null) => {
|
||||
const days = trip ? await offlineDb.days.where('trip_id').equals(trip.id).toArray() : [];
|
||||
const extra = trip ? await tripExtras(trip, days, context) : null;
|
||||
const plain = trip
|
||||
? todayOf(trip, days, context.today, (n, m) => t('native.widget.dayOf', { n, m }), context.time)
|
||||
: null;
|
||||
const day = plain ? withBookings(plain, extra?.reservations ?? [], context.today, context.time) : null;
|
||||
return { day, days, extra, snapshot: buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas }) };
|
||||
// Today and the days after it: the widgets turn to the next day at midnight by themselves.
|
||||
const { today: day, ahead } = snapshotDays(trip, days, {
|
||||
reservations: extra?.reservations ?? [],
|
||||
from: context.today,
|
||||
dayLabel: (n, m) => t('native.widget.dayOf', { n, m }),
|
||||
formatTime: context.time,
|
||||
});
|
||||
const snapshot = buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas, days: ahead });
|
||||
return { day, days, extra, snapshot };
|
||||
};
|
||||
|
||||
/** The hero trip in full for the watch, with the ticks from it applied so far. */
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import mapboxgl from 'mapbox-gl'
|
||||
import 'mapbox-gl/dist/mapbox-gl.css'
|
||||
import rtlTextPluginUrl from '@mapbox/mapbox-gl-rtl-text/dist/mapbox-gl-rtl-text.js?url'
|
||||
import { registerRtlTextPlugin } from '../rtlText'
|
||||
|
||||
/**
|
||||
* The only module in the client that pulls mapbox-gl in at runtime.
|
||||
@@ -10,8 +8,8 @@ import { registerRtlTextPlugin } from '../rtlText'
|
||||
* a static import from anywhere in the tree drags 1.8 MB into the parent chunk and
|
||||
* quietly undoes the split. `npm run check:gl-split` fails on that.
|
||||
*/
|
||||
// Arabic/Hebrew/Persian labels come out unjoined and reversed without this.
|
||||
// Mapbox's signature is (url, callback, deferred) — see rtlText.ts.
|
||||
registerRtlTextPlugin(() => mapboxgl.setRTLTextPlugin(rtlTextPluginUrl, null, true))
|
||||
// No RTL text plugin to register: since 3.33 Mapbox GL shapes Arabic and orders
|
||||
// bidirectional text itself, loading a small WebAssembly module from
|
||||
// api.mapbox.com the first time such a label appears (#2235).
|
||||
|
||||
export default mapboxgl
|
||||
|
||||
@@ -25,7 +25,7 @@ import { installOfflineProtocol } from '../../../native/offlineTiles'
|
||||
// together with this module.
|
||||
maplibregl.setWorkerUrl(workerUrl)
|
||||
|
||||
// No RTL text plugin here, unlike mapbox. MapLibre 6.9 shapes Arabic and orders
|
||||
// No RTL text plugin here, as with mapbox. MapLibre 6.9 shapes Arabic and orders
|
||||
// bidirectional text itself; the old plugin would replace that implementation, and
|
||||
// a v6 worker can only load the plugin's UMD build through eval.
|
||||
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* What each engine module does on import. Everything else is a helper: the guard
|
||||
* in rtlText.ts has its own tests, but a guard nobody calls looks exactly like a
|
||||
* working fix from the outside. Deleting the mapbox registration, swapping an
|
||||
* argument or dropping the deferred flag left the whole suite green, and so would
|
||||
* a maplibre engine that forgot its worker URL.
|
||||
* What each engine module does on import. Both GL engines shape right-to-left
|
||||
* text themselves now (MapLibre since 6.9, Mapbox since 3.33), so neither may
|
||||
* register the old plugin, and a maplibre engine that forgot its worker URL
|
||||
* would draw no tile at all.
|
||||
*
|
||||
* The engines are mocked because importing them for real builds a worker pool
|
||||
* under jsdom, and the plugin URL is mocked so the 133 KB payload never loads.
|
||||
* under jsdom.
|
||||
*/
|
||||
const { mapboxSet, maplibreSet, maplibreWorker } = vi.hoisted(() => ({
|
||||
mapboxSet: vi.fn(),
|
||||
@@ -21,7 +20,6 @@ vi.mock('maplibre-gl', () => ({ setRTLTextPlugin: maplibreSet, setWorkerUrl: map
|
||||
vi.mock('mapbox-gl/dist/mapbox-gl.css', () => ({}));
|
||||
vi.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));
|
||||
vi.mock('maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url', () => ({ default: '/assets/maplibre-worker.js' }));
|
||||
vi.mock('@mapbox/mapbox-gl-rtl-text/dist/mapbox-gl-rtl-text.js?url', () => ({ default: '/assets/rtl-plugin.js' }));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
@@ -30,15 +28,14 @@ beforeEach(() => {
|
||||
maplibreWorker.mockReset();
|
||||
});
|
||||
|
||||
describe('the GL engines register the RTL text plugin (#2235)', () => {
|
||||
it('FE-MAP-RTL-001: importing the mapbox engine registers it deferred, with a null callback', async () => {
|
||||
await import('./mapbox');
|
||||
describe('the GL engines on import (#2235)', () => {
|
||||
it('FE-MAP-RTL-001: importing the mapbox engine registers no plugin', async () => {
|
||||
const engine = await import('./mapbox');
|
||||
|
||||
expect(mapboxSet).toHaveBeenCalledTimes(1);
|
||||
// Mapbox GL 3 takes (url, callback, deferred). The third argument is what
|
||||
// keeps the payload off the wire until a map paints RTL text; dropping it
|
||||
// would fetch 133 KB for every user on every map.
|
||||
expect(mapboxSet).toHaveBeenCalledWith(expect.stringContaining('rtl'), null, true);
|
||||
// Mapbox GL 3.33 shapes right-to-left text itself and dropped the plugin API;
|
||||
// calling it would throw on the real engine.
|
||||
expect(mapboxSet).not.toHaveBeenCalled();
|
||||
expect(engine.default).toBeDefined();
|
||||
});
|
||||
|
||||
it('FE-MAP-RTL-002: importing the maplibre engine registers no plugin', async () => {
|
||||
@@ -49,14 +46,6 @@ describe('the GL engines register the RTL text plugin (#2235)', () => {
|
||||
expect(maplibreSet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-MAP-RTL-003: an engine still loads when its registration throws', async () => {
|
||||
mapboxSet.mockImplementation(() => { throw new Error('already registered'); });
|
||||
|
||||
const engine = await import('./mapbox');
|
||||
|
||||
expect(engine.default).toBeDefined();
|
||||
});
|
||||
|
||||
it('FE-MAP-RTL-004: importing the maplibre engine points it at the bundled worker', async () => {
|
||||
const engine = await import('./maplibre');
|
||||
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { registerRtlTextPlugin } from './rtlText'
|
||||
|
||||
describe('registerRtlTextPlugin', () => {
|
||||
it('runs the engine-supplied registration', () => {
|
||||
const register = vi.fn()
|
||||
|
||||
expect(registerRtlTextPlugin(register)).toBe(true)
|
||||
expect(register).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
// Registering twice is how the engines report it: Mapbox throws.
|
||||
it('never lets a refused registration break map creation', () => {
|
||||
const register = vi.fn(() => {
|
||||
throw new Error('setRTLTextPlugin cannot be called multiple times.')
|
||||
})
|
||||
|
||||
expect(() => registerRtlTextPlugin(register)).not.toThrow()
|
||||
expect(registerRtlTextPlugin(register)).toBe(false)
|
||||
})
|
||||
|
||||
// MapLibre reports the same by rejecting, and an unhandled rejection would
|
||||
// reach the console for something the user cannot act on.
|
||||
it('swallows a rejected registration promise', async () => {
|
||||
const onUnhandled = vi.fn()
|
||||
process.on('unhandledRejection', onUnhandled)
|
||||
|
||||
expect(registerRtlTextPlugin(() => Promise.reject(new Error('404')))).toBe(true)
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
process.off('unhandledRejection', onUnhandled)
|
||||
|
||||
expect(onUnhandled).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves a resolved promise alone', async () => {
|
||||
expect(registerRtlTextPlugin(() => Promise.resolve())).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* Arabic, Hebrew, Persian and Urdu labels need two things a GL engine does not do
|
||||
* on its own: the bidirectional algorithm, and Arabic contextual shaping (a letter
|
||||
* is drawn differently depending on its neighbours). Without them the engine lays
|
||||
* the codepoints out one by one, left to right, in isolated forms — so القاهرة
|
||||
* comes out as ة ر ه ا ق ل ا, unjoined and reversed. Raster basemaps never showed
|
||||
* this because their labels are drawn server-side, which is why it only surfaced
|
||||
* once the default basemap became a vector style.
|
||||
*
|
||||
* Mapbox GL exposes the fix as an optional plugin and does not load it by
|
||||
* default. Registering is global to the engine, so it happens once in the engine
|
||||
* module rather than at each map's construction site. MapLibre needed the same
|
||||
* plugin up to version 5; since 6.9 it shapes and reorders the text itself, and
|
||||
* its engine module registers nothing.
|
||||
*
|
||||
* The call itself stays with the caller: Mapbox GL 3 takes
|
||||
* `(url, callback, deferred)` and returns nothing, while MapLibre took
|
||||
* `(url, lazy)` and returned a promise, so the guard below accepts either rather
|
||||
* than guessing an arity.
|
||||
*
|
||||
* Deliberately no getRTLTextPluginStatus() pre-check: reading it made MapLibre
|
||||
* build its worker pool, which is an eager side effect for a module that is
|
||||
* imported for its default export, and throws outright under jsdom. Registering
|
||||
* twice is reported — by a throw or a rejected promise depending on the engine —
|
||||
* and both are handled below, so the probe bought nothing.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Runs a GL engine's RTL-plugin registration, swallowing the ways it can fail.
|
||||
*
|
||||
* Callers register lazily, so the payload is only fetched once a map actually
|
||||
* paints RTL text and a user who never leaves Latin script downloads nothing.
|
||||
*
|
||||
* @returns whether the registration call completed without throwing.
|
||||
*/
|
||||
export function registerRtlTextPlugin(register: () => void | Promise<unknown>): boolean {
|
||||
try {
|
||||
const pending = register()
|
||||
// MapLibre reports a failed or duplicate registration by rejecting; Mapbox
|
||||
// routes the same through its callback. Neither is worth surfacing: a map
|
||||
// with unshaped labels still renders, and an unhandled rejection would not
|
||||
// give the user anything to act on.
|
||||
if (pending instanceof Promise) pending.catch(() => {})
|
||||
return true
|
||||
} catch {
|
||||
// Already registered, or the engine refused outright. Registering the plugin
|
||||
// must never be able to break map creation.
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
type TripRouteAnswers, type TripRouteSummary,
|
||||
} from './tripRouteGeometry'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
|
||||
import type { RoadtripVia } from '@trek/shared'
|
||||
import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'
|
||||
import type { TourStageStops } from './dayTourProjection'
|
||||
@@ -51,7 +51,7 @@ export function useTripRouteOverview(
|
||||
tourStageStops?: TourStageStops,
|
||||
): TripRouteOverview {
|
||||
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
|
||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
|
||||
// Leg text is formatted at compute time, so a km↔mi switch has to re-run (#1300).
|
||||
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
|
||||
const [result, setResult] = useState<TripRouteOverview>(EMPTY)
|
||||
|
||||
@@ -259,6 +259,25 @@ describe('downloadTripPDF', () => {
|
||||
expect(iframe!.srcdoc).toContain('Air Italia · AI123 · CDG → FCO')
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-013s: a flight prints its seat, a direct one and each leg of one with a stop alike', async () => {
|
||||
const direct = { ...transportReservation, metadata: JSON.stringify({ airline: 'Air Italia', flight_number: 'AI123', seat: '31A', departure_airport: 'CDG', arrival_airport: 'FCO' }) }
|
||||
const stopover = {
|
||||
...multiLegFlight,
|
||||
metadata: JSON.stringify({
|
||||
legs: [
|
||||
{ from: 'FRA', to: 'BER', airline: 'Lufthansa', flight_number: 'LH1' },
|
||||
{ from: 'BER', to: 'HND', airline: 'Lufthansa', flight_number: 'LH2', seat: '14C' },
|
||||
],
|
||||
departure_airport: 'FRA', arrival_airport: 'HND', airline: 'Lufthansa', flight_number: 'LH1',
|
||||
}),
|
||||
}
|
||||
await downloadTripPDF({ ...richArgs, reservations: [direct, stopover] })
|
||||
const html = getIframe()?.srcdoc ?? ''
|
||||
expect(html).toContain('Air Italia · AI123 · reservations.meta.seat 31A · CDG → FCO')
|
||||
expect(html).toContain('Lufthansa · LH2 · reservations.meta.seat 14C · BER → HND')
|
||||
expect(html).not.toContain('LH1 · reservations.meta.seat')
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-013f: the stop a booked night wrote is not listed, so a morning flight prints before the hotel (#2434)', async () => {
|
||||
// The desktop toolbar hands the export the store's assignments, hidden stop and
|
||||
// all, and that stop heads its check-in day. The day plan hides it and shows the
|
||||
|
||||
@@ -14,7 +14,7 @@ import { renderIconMarkup } from '../../utils/iconMarkup'
|
||||
import { formatMoney, formatMoneySum, formatClockTime, splitReservationDateTime, type MoneyEntry } from '../../utils/formatters'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { tripAddonEnabledNow } from '../../store/tripAddonsStore'
|
||||
import { projectDayItinerary } from '../Map/dayTourProjection'
|
||||
import { planCosts } from '../Planner/planCosts'
|
||||
import { routeDistanceLabel } from '../Map/tripRouteLabels'
|
||||
@@ -180,8 +180,10 @@ interface downloadTripPDFProps {
|
||||
showServiceStops?: boolean
|
||||
/** The trip's expenses, which the cost figures add up with Costs on (#2551). Read from the trip store when left out. */
|
||||
budgetItems?: BudgetItem[]
|
||||
/** Whether the Costs addon is on. Read from the addon store when left out. */
|
||||
/** Whether the Costs addon is on for this trip. Read from the trip's addons when left out. */
|
||||
costsEnabled?: boolean
|
||||
/** Whether the Tours addon is on for this trip. Read from the trip's addons when left out. */
|
||||
toursEnabled?: boolean
|
||||
/** Prints only this member's plan (#2168): the stops and bookings that name them, and the ones that name nobody. */
|
||||
onlyUserId?: number
|
||||
/** The planner's road trip vias and tour stages, and the routing progress and stop (#2876). */
|
||||
@@ -192,7 +194,7 @@ interface downloadTripPDFProps {
|
||||
|
||||
// `assignments` is normalised here once, to the plan's own list; every read below
|
||||
// (and fetchPlacePhotos) relies on it being an object.
|
||||
export async function downloadTripPDF({ trip, days, places, assignments: allStored = {}, categories, dayNotes, reservations: allReservations = [], t: _t, locale: _locale, timeFormat: _timeFormat, distanceUnit: _distanceUnit, showServiceStops = true, budgetItems, costsEnabled, onlyUserId, route, signal }: downloadTripPDFProps) {
|
||||
export async function downloadTripPDF({ trip, days, places, assignments: allStored = {}, categories, dayNotes, reservations: allReservations = [], t: _t, locale: _locale, timeFormat: _timeFormat, distanceUnit: _distanceUnit, showServiceStops = true, budgetItems, costsEnabled, toursEnabled: toursOn, onlyUserId, route, signal }: downloadTripPDFProps) {
|
||||
const { assignments: stored, reservations } = onlyUserId != null
|
||||
? onlyMyPlan(allStored, allReservations, onlyUserId)
|
||||
: { assignments: allStored, reservations: allReservations }
|
||||
@@ -226,7 +228,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
|
||||
const unit: DistanceUnit = (_distanceUnit || useSettingsStore.getState().settings.distance_unit) === 'imperial'
|
||||
? 'imperial' : 'metric'
|
||||
const toursEnabled = useAddonStore.getState().isEnabled('tours')
|
||||
const toursEnabled = toursOn ?? tripAddonEnabledNow(trip.id, 'tours')
|
||||
const hasInvalidTour = toursEnabled && Object.values(assignments).some(list =>
|
||||
projectDayItinerary(list || [], true, places).some(item => item.kind === 'tour' && !item.valid))
|
||||
const { route: tripRoute, mapSvg: tripMapSvg } = await drawTripRoute({
|
||||
@@ -289,7 +291,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
// The same figures the plan shows (#2551): the expenses with Costs on, each once,
|
||||
// else each planned place's own price once. An expense linked to a place finds its
|
||||
// day through every stop, the booked night's included.
|
||||
const withCosts = costsEnabled ?? useAddonStore.getState().isEnabled('budget')
|
||||
const withCosts = costsEnabled ?? tripAddonEnabledNow(trip.id, 'budget')
|
||||
const costs = planCosts({
|
||||
days: sorted,
|
||||
assignments: withCosts ? stored : assignments,
|
||||
@@ -415,7 +417,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
// flat metadata pair for legacy single-leg flights without endpoints.
|
||||
const stops = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)).map(e => e.code || e.name)
|
||||
const route = stops.length >= 2 ? stops.join(' → ') : (meta.departure_airport && meta.arrival_airport ? `${meta.departure_airport} → ${meta.arrival_airport}` : '')
|
||||
subtitle = [meta.airline, meta.flight_number, route].filter(Boolean).join(' · ')
|
||||
subtitle = [meta.airline, meta.flight_number, meta.seat ? `${tr('reservations.meta.seat')} ${meta.seat}` : '', route].filter(Boolean).join(' · ')
|
||||
}
|
||||
}
|
||||
else if (r.type === 'train') {
|
||||
|
||||
@@ -33,6 +33,7 @@ import { useTripStore } from '../../store/tripStore'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
|
||||
import { openSaveToCollection } from '../Collections/saveTarget'
|
||||
import { computeMultiDayMove as computeMultiDayMoveIn, getDayOrder as getDayOrderIn, type SpanPhase } from './DayPlanSidebar.multiDayMove'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -41,7 +42,6 @@ import { Tooltip } from '../shared/Tooltip'
|
||||
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
|
||||
import { BarButton, MoreButton, SoftPill, TimePill, tintOf } from './planParts'
|
||||
import './dayPlanRows.css'
|
||||
|
||||
import { TypeTile } from './bookings/bookingParts'
|
||||
import { typeInfo } from './bookings/bookingsModel'
|
||||
import { transportSubtitle } from './transportDetailModel'
|
||||
@@ -218,7 +218,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
|
||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
|
||||
const tripActions = useRef(useTripStore.getState()).current
|
||||
|
||||
const { noteUi, setNoteUi, noteInputRef, dayNotes, openAddNote: _openAddNote, openEditNote: _openEditNote, cancelNote, saveNote, deleteNote: _deleteNote, moveNote: _moveNote } = useDayNotes(tripId)
|
||||
@@ -1098,7 +1098,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
|
||||
// Total Cost reads the expenses in Costs when it is on (#2551).
|
||||
const budgetItems = useTripStore(s => s.budgetItems)
|
||||
const costsEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const costsEnabled = useTripAddonEnabled(tripId, 'budget')
|
||||
const totalCostLabel = useMemo(() => {
|
||||
return formatMoneySum(planCosts({ days, assignments, reservations, budgetItems, costsEnabled, tripCurrency: currency, displayCurrency: costBase }).total, costBase, locale, fxRates)
|
||||
}, [days, assignments, reservations, budgetItems, costsEnabled, currency, costBase, locale, fxRates])
|
||||
@@ -1276,7 +1276,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
|
||||
const dateFirst = useSettingsStore(s => s.settings.day_date_first === true)
|
||||
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
|
||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
|
||||
// Plugin time contributions in the day plan (dayScheduleProvider hook).
|
||||
const daySchedule = usePluginDaySchedule(tripId)
|
||||
// Per-day colours from the dayTintProvider hook — e.g. which leg of the trip a
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-PLANNER-DPTRANSPORT-001 to FE-PLANNER-DPTRANSPORT-021
|
||||
// FE-PLANNER-DPTRANSPORT-001 to FE-PLANNER-DPTRANSPORT-024
|
||||
import { render, screen, fireEvent, within } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
@@ -329,4 +329,29 @@ describe('DayPlanSidebarTransportDetailModal', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Close' }))
|
||||
expect(setTransportDetail).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
// #3122: a transport holding only times showed them without the day they fall on.
|
||||
it('FE-PLANNER-DPTRANSPORT-022: a booking holding only times names the date of its linked day', () => {
|
||||
seedStore(useTripStore, { days: [{ id: 4, trip_id: 1, day_number: 2, date: '2025-06-16' }] as never })
|
||||
const res = { ...flight(), day_id: 4, reservation_time: '09:15', reservation_end_time: '11:00', endpoints: [] } as Reservation
|
||||
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
|
||||
expect(screen.getByText('09:15 → 11:00').parentElement).toHaveTextContent(/Mon, Jun 16/)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DPTRANSPORT-023: an overnight booking names the arrival date too', () => {
|
||||
const res = { ...flight(), reservation_time: '2025-06-15T22:30:00', reservation_end_time: '2025-06-16T06:05:00' } as Reservation
|
||||
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
|
||||
expect(screen.getByText('22:30 → 06:05').parentElement).toHaveTextContent(/Sun, Jun 15 → Mon, Jun 16/)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DPTRANSPORT-024: in a right-to-left UI the overnight days read in order', () => {
|
||||
document.documentElement.dir = 'rtl'
|
||||
try {
|
||||
const res = { ...flight(), reservation_time: '2025-06-15T22:30:00', reservation_end_time: '2025-06-16T06:05:00' } as Reservation
|
||||
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
|
||||
expect(screen.getByText('22:30 → 06:05').parentElement).toHaveTextContent('Sun, Jun 15 ← Mon, Jun 16')
|
||||
} finally {
|
||||
document.documentElement.dir = ''
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,13 +8,15 @@ import { BlurredCode } from '../shared/BookingCode'
|
||||
import { DialogButton, DialogFooter, DialogSection, DialogShell, FooterSpacer, PILL } from '../shared/DialogShell'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { formatTime, splitReservationDateTime } from '../../utils/formatters'
|
||||
import { parseReservationMetadata } from '../../utils/flightLegs'
|
||||
import { parseReservationMetadata, seatCells } from '../../utils/flightLegs'
|
||||
import { BookingDialogHeader } from './bookings/BookingDialogShell'
|
||||
import { BOX, Eyebrow, Field, fs, toneColor, toneOf } from './bookings/bookingParts'
|
||||
import { filesFor } from '../../utils/reservationFiles'
|
||||
import { bookingDayLabel, segmentCodeLabel } from './transportDetailModel'
|
||||
import { TransitLegs, transitSummary } from './bookings/transitParts'
|
||||
import type { Reservation } from '../../types'
|
||||
import { bookingDates } from './bookings/bookingsModel'
|
||||
import { flowText } from '../../utils/flowText'
|
||||
import type { Day, Reservation } from '../../types'
|
||||
|
||||
type Translate = (key: string, params?: Record<string, string | number>) => string
|
||||
|
||||
@@ -50,11 +52,12 @@ export function DayPlanSidebarTransportDetailModal({ transportDetail, ...rest }:
|
||||
function TransportDetailDialog({ res, setTransportDetail, onNavigateToFiles, onEdit, t, locale, timeFormat }: Omit<DayPlanSidebarTransportDetailModalProps, 'transportDetail'> & { res: Reservation }) {
|
||||
const titleId = useId()
|
||||
const allFiles = useTripStore(s => s.files)
|
||||
const days = useTripStore(s => s.days)
|
||||
const close = () => setTransportDetail(null)
|
||||
const meta = parseReservationMetadata(res)
|
||||
const transit = transitSummary(meta)
|
||||
const files = filesFor(res, allFiles || [])
|
||||
const when = whenOf(res, locale, timeFormat)
|
||||
const when = whenOf(res, days, locale, timeFormat)
|
||||
const cells = detailCells(res, meta, t)
|
||||
const confirmed = res.status === 'confirmed'
|
||||
|
||||
@@ -172,11 +175,13 @@ function detailCells(res: Reservation, meta: Record<string, unknown>, t: Transla
|
||||
add(t('reservations.meta.flightNumber'), meta.flight_number)
|
||||
add(t('reservations.meta.from'), meta.departure_airport)
|
||||
add(t('reservations.meta.to'), meta.arrival_airport)
|
||||
add(t('reservations.meta.seat'), meta.seat)
|
||||
} else if (res.type === 'train') {
|
||||
add(t('reservations.meta.trainNumber'), meta.train_number)
|
||||
add(t('reservations.meta.platform'), meta.platform)
|
||||
add(t('reservations.meta.seat'), meta.seat)
|
||||
}
|
||||
// Each leg's seat under its route on a booking with a stop, not just the first leg's.
|
||||
if (res.type === 'flight' || res.type === 'train') {
|
||||
for (const c of seatCells(res, t('reservations.meta.seat'))) add(c.label, c.value)
|
||||
}
|
||||
add(t('reservations.confirmationCode'), res.confirmation_number, true)
|
||||
// A stopover booking can carry its own reference per segment (#1943); the
|
||||
@@ -192,11 +197,18 @@ function detailCells(res: Reservation, meta: Record<string, unknown>, t: Transla
|
||||
return cells
|
||||
}
|
||||
|
||||
/** The booking's day and its time or time range, each empty when the booking has none. */
|
||||
function whenOf(res: Reservation, locale: string, timeFormat: string): { day: string; time: string } {
|
||||
const { date, time } = splitReservationDateTime(res.reservation_time)
|
||||
/**
|
||||
* The booking's calendar day (both, when it arrives on a later one) and its time or
|
||||
* time range, each empty when the booking has none. A booking holding only times
|
||||
* takes the date of the day it is linked to (#3122).
|
||||
*/
|
||||
function whenOf(res: Reservation, days: Day[], locale: string, timeFormat: string): { day: string; time: string } {
|
||||
const { time } = splitReservationDateTime(res.reservation_time)
|
||||
const { time: endTime } = splitReservationDateTime(res.reservation_end_time)
|
||||
const day = date ? bookingDayLabel(date, locale) : ''
|
||||
const dates = bookingDates(res, days || [])
|
||||
// An arrival date alone would read as the departure, so it only joins a start date.
|
||||
const span = dates.start ? [dates.start, dates.end !== dates.start ? dates.end : null].filter((d): d is string => !!d) : []
|
||||
const day = span.length > 0 ? flowText(span.map(d => bookingDayLabel(d, locale))) : ''
|
||||
const start = time ? formatTime(time, locale, timeFormat) : ''
|
||||
const end = endTime ? formatTime(endTime, locale, timeFormat) : ''
|
||||
return { day, time: start && end ? `${start} → ${end}` : start }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-PLANNER-CONTACT-001 to FE-PLANNER-CONTACT-002
|
||||
// FE-PLANNER-CONTACT-001 to FE-PLANNER-CONTACT-004
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { useState } from 'react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
@@ -54,7 +54,7 @@ describe('PlaceContactFields (#2472)', () => {
|
||||
const opens = screen.getAllByRole('textbox', { name: /Monday opens/ })
|
||||
await user.type(opens[0], '0930')
|
||||
expect(opens[0]).toHaveValue('09:30')
|
||||
expect(JSON.parse(onChange.mock.lastCall![1])[0]).toEqual({ closed: false, open: '09:30' })
|
||||
expect(JSON.parse(onChange.mock.lastCall?.[1])[0]).toEqual({ closed: false, open: '09:30' })
|
||||
})
|
||||
|
||||
it('FE-PLANNER-CONTACT-004: looked-up hours fill an empty place, and an edited one offers to take them over', async () => {
|
||||
@@ -87,5 +87,33 @@ describe('PlaceContactFields (#2472)', () => {
|
||||
// Still an e-mail field, so the keyboard and the browser's check stay.
|
||||
expect(screen.getByLabelText('E-mail')).toHaveAttribute('type', 'email')
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-PLANNER-CONTACT-003: a day opens around the clock with one switch, and an all-day lookup shows it on', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<Harness onChange={onChange} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Add opening hours' }))
|
||||
|
||||
const allDay = screen.getByRole('switch', { name: 'Monday: Open 24 hours' })
|
||||
expect(allDay).toHaveAttribute('aria-checked', 'false')
|
||||
await user.click(allDay)
|
||||
expect(JSON.parse(onChange.mock.lastCall?.[1])[0]).toEqual({ closed: false, open: '00:00', close: '23:59' })
|
||||
expect(allDay).toHaveAttribute('aria-checked', 'true')
|
||||
// The two time fields give way to the word.
|
||||
expect(screen.queryByRole('textbox', { name: /Monday opens/ })).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Open 24 hours', { selector: 'span' })).toBeInTheDocument()
|
||||
|
||||
// Closing the day turns the all-day switch off.
|
||||
await user.click(screen.getByRole('switch', { name: 'Monday: Closed' }))
|
||||
expect(JSON.parse(onChange.mock.lastCall?.[1])[0]).toEqual({ closed: true })
|
||||
expect(allDay).toHaveAttribute('aria-checked', 'false')
|
||||
})
|
||||
|
||||
it('FE-PLANNER-CONTACT-004: looked-up hours open around the clock arrive with the all-day switch on', () => {
|
||||
const suggested = Array.from({ length: 7 }, () => ({ closed: false, open: '00:00', close: '23:59' }))
|
||||
render(<Harness onChange={vi.fn()} suggested={suggested} />)
|
||||
for (const day of ['Monday', 'Sunday']) {
|
||||
expect(screen.getByRole('switch', { name: `${day}: Open 24 hours` })).toHaveAttribute('aria-checked', 'true')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
import { useEffect, useId, useRef, useState } from 'react'
|
||||
import { Copy, Mail, Phone, RotateCcw, X } from 'lucide-react'
|
||||
import { useId } from 'react'
|
||||
import { Copy, DoorClosed, Mail, Phone, RotateCcw, X } from 'lucide-react'
|
||||
import type { PlaceClientOrigin, PlaceOpeningHours } from '@trek/shared'
|
||||
import CustomTimePicker from '../shared/CustomTimePicker'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { DialogSection, fs } from '../shared/DialogShell'
|
||||
import { AddRowButton, EditorField, GRID_2, INPUT } from '../shared/dialogParts'
|
||||
import { cleanWeek, readWeek, weekdayNames, writeWeek } from './placeHours'
|
||||
import { isAllDay, weekdayNames } from './placeHours'
|
||||
import { usePlaceHours } from './usePlaceHours'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { NO_AUTOFILL } from '../../utils/noAutofill'
|
||||
|
||||
/** A closed or all-day row says so in place of the two times, in a box of their height. */
|
||||
const DAY_STATE = 'flex h-[38px] min-w-0 items-center rounded-[10px] border border-edge-faint bg-surface-tertiary px-3.5 font-medium text-content-muted'
|
||||
/** The two switches after the times: square, as tall as a time field. */
|
||||
const DAY_BUTTON = 'grid h-[38px] w-[38px] flex-none place-items-center rounded-[10px] border font-semibold transition-colors'
|
||||
const DAY_BUTTON_OFF = 'border-edge bg-surface-input text-content-faint hover:border-content-faint hover:text-content'
|
||||
const DAY_BUTTON_ON = 'border-transparent bg-accent text-accent-text shadow-sm'
|
||||
|
||||
interface Props {
|
||||
/** Anchor for the "add by hand" jump from an empty search. */
|
||||
id?: string
|
||||
@@ -36,45 +44,11 @@ interface Props {
|
||||
export function PlaceContactFields({ id: anchorId, phone, email, openingHours, onChange, suggestedHours }: Props) {
|
||||
const { t, locale } = useTranslation()
|
||||
const id = useId()
|
||||
// The editor's own draft, so a half-typed time ("09:3") stays on screen while
|
||||
// only finished times reach the place.
|
||||
const [week, setDraft] = useState(() => readWeek(openingHours))
|
||||
const written = useRef(openingHours)
|
||||
const [editing, setEditing] = useState(() => openingHours !== '')
|
||||
const hours = usePlaceHours({ openingHours, suggestedHours, onChange: (value, origin) => onChange('opening_hours', value, origin) })
|
||||
const { week, editing } = hours
|
||||
const names = weekdayNames(locale, 'short')
|
||||
const longNames = weekdayNames(locale, 'long')
|
||||
|
||||
// A value from outside (a picked search result, a reopened place) replaces the draft.
|
||||
useEffect(() => {
|
||||
if (openingHours === written.current) return
|
||||
written.current = openingHours
|
||||
setDraft(readWeek(openingHours))
|
||||
if (openingHours) setEditing(true)
|
||||
}, [openingHours])
|
||||
|
||||
const setWeek = (next: PlaceOpeningHours, origin?: PlaceClientOrigin) => {
|
||||
setDraft(next)
|
||||
const text = writeWeek(cleanWeek(next))
|
||||
written.current = text
|
||||
onChange('opening_hours', text, origin)
|
||||
}
|
||||
const setDay = (i: number, patch: Partial<PlaceOpeningHours[number]>) =>
|
||||
setWeek(week.map((day, d) => (d === i ? { ...day, ...patch } : day)))
|
||||
const copyFirstToAll = () => setWeek(week.map(() => ({ ...week[0] })))
|
||||
const clearHours = () => { setWeek(readWeek('')); setEditing(false) }
|
||||
|
||||
// Looked-up hours are taken over by a place that has none yet, once per lookup.
|
||||
const adopted = useRef<PlaceOpeningHours | null>(null)
|
||||
useEffect(() => {
|
||||
if (!suggestedHours || adopted.current === suggestedHours) return
|
||||
adopted.current = suggestedHours
|
||||
if (written.current) return
|
||||
setWeek(suggestedHours, 'enrichment')
|
||||
setEditing(true)
|
||||
// setWeek only reads refs and setters; the lookup is the trigger.
|
||||
}, [suggestedHours])
|
||||
const canTakeOver = !!suggestedHours && writeWeek(suggestedHours) !== writeWeek(cleanWeek(week))
|
||||
|
||||
return (
|
||||
<div id={anchorId} className="flex flex-col gap-4">
|
||||
<div className={GRID_2}>
|
||||
@@ -98,22 +72,22 @@ export function PlaceContactFields({ id: anchorId, phone, email, openingHours, o
|
||||
label={t('inspector.openingHours')}
|
||||
action={editing ? (
|
||||
<div className="flex items-center gap-1">
|
||||
{canTakeOver && (
|
||||
{hours.canTakeOver && (
|
||||
<Tooltip label={t('places.hoursFromDetails')}>
|
||||
<button type="button" onClick={() => setWeek(suggestedHours!, 'enrichment')} aria-label={t('places.hoursFromDetails')}
|
||||
<button type="button" onClick={hours.takeOver} aria-label={t('places.hoursFromDetails')}
|
||||
className="grid h-7 w-7 place-items-center rounded-full text-content-faint hover:bg-surface-hover hover:text-content">
|
||||
<RotateCcw size={13} strokeWidth={2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip label={t('places.hoursCopyFirst', { day: longNames[0] })}>
|
||||
<button type="button" onClick={copyFirstToAll} aria-label={t('places.hoursCopyFirst', { day: longNames[0] })}
|
||||
<button type="button" onClick={hours.copyFirstToAll} aria-label={t('places.hoursCopyFirst', { day: longNames[0] })}
|
||||
className="grid h-7 w-7 place-items-center rounded-full text-content-faint hover:bg-surface-hover hover:text-content">
|
||||
<Copy size={13} strokeWidth={2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('places.hoursRemove')}>
|
||||
<button type="button" onClick={clearHours} aria-label={t('places.hoursRemove')}
|
||||
<button type="button" onClick={hours.clearHours} aria-label={t('places.hoursRemove')}
|
||||
className="grid h-7 w-7 place-items-center rounded-full text-content-faint hover:bg-surface-hover hover:text-danger">
|
||||
<X size={14} strokeWidth={2.2} />
|
||||
</button>
|
||||
@@ -126,32 +100,45 @@ export function PlaceContactFields({ id: anchorId, phone, email, openingHours, o
|
||||
{week.map((day, i) => (
|
||||
<div key={i} className="grid min-h-[46px] grid-cols-[44px_minmax(0,1fr)_auto] items-center gap-2.5 px-3 py-1.5">
|
||||
<span className="font-semibold text-content-secondary" style={fs(12.5, 'body')} title={longNames[i]}>{names[i]}</span>
|
||||
{day.closed ? (
|
||||
<span className="text-content-faint" style={fs(12.5, 'body')}>{t('places.hoursClosed')}</span>
|
||||
{day.closed || isAllDay(day) ? (
|
||||
<span className={DAY_STATE} style={fs(12.5, 'body')}>
|
||||
{day.closed ? t('places.hoursClosed') : t('places.hoursAllDay')}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
<div className="min-w-0 flex-1">
|
||||
<CustomTimePicker value={day.open ?? ''} onChange={v => setDay(i, { open: v || undefined })}
|
||||
<div className='flex min-w-0 items-center gap-1.5'>
|
||||
<div className='min-w-0 flex-1'>
|
||||
<CustomTimePicker value={day.open ?? ''} onChange={v => hours.setDay(i, { open: v || undefined })}
|
||||
aria-label={`${longNames[i]} ${t('places.hoursOpens')}`} />
|
||||
</div>
|
||||
<span className="flex-none text-content-faint">–</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<CustomTimePicker value={day.close ?? ''} onChange={v => setDay(i, { close: v || undefined })}
|
||||
<span className='flex-none text-content-faint'>–</span>
|
||||
<div className='min-w-0 flex-1'>
|
||||
<CustomTimePicker value={day.close ?? ''} onChange={v => hours.setDay(i, { close: v || undefined })}
|
||||
aria-label={`${longNames[i]} ${t('places.hoursCloses')}`} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<button type="button" role="switch" aria-checked={day.closed} aria-label={`${longNames[i]}: ${t('places.hoursClosed')}`}
|
||||
onClick={() => setDay(i, day.closed ? { closed: false } : { closed: true, open: undefined, close: undefined })}
|
||||
className={`rounded-full border px-2.5 py-[3px] font-semibold transition-colors ${day.closed ? 'border-[color:var(--text-primary)] bg-surface-tertiary text-content' : 'border-edge text-content-faint hover:text-content'}`}
|
||||
style={fs(11)}>
|
||||
{t('places.hoursClosed')}
|
||||
</button>
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<Tooltip label={t('places.hoursAllDay')}>
|
||||
<button type='button' role='switch' aria-checked={isAllDay(day)} aria-label={`${longNames[i]}: ${t('places.hoursAllDay')}`}
|
||||
onClick={() => hours.toggleAllDay(i)}
|
||||
className={`${DAY_BUTTON} ${isAllDay(day) ? DAY_BUTTON_ON : DAY_BUTTON_OFF}`}
|
||||
style={fs(11.5, 'body')}>
|
||||
24h
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('places.hoursClosed')}>
|
||||
<button type='button' role='switch' aria-checked={day.closed} aria-label={`${longNames[i]}: ${t('places.hoursClosed')}`}
|
||||
onClick={() => hours.toggleClosed(i)}
|
||||
className={`${DAY_BUTTON} ${day.closed ? DAY_BUTTON_ON : DAY_BUTTON_OFF}`}>
|
||||
<DoorClosed size={15} strokeWidth={2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<AddRowButton onClick={() => setEditing(true)}>{t('places.hoursAdd')}</AddRowButton>
|
||||
<AddRowButton raised onClick={() => hours.setEditing(true)}>{t('places.hoursAdd')}</AddRowButton>
|
||||
)}
|
||||
</DialogSection>
|
||||
</div>
|
||||
|
||||
@@ -238,7 +238,7 @@ export default function PlaceDetailsColumn({
|
||||
// tiles, which is too small to tell a facade from a foyer. The column is
|
||||
// stretched to the form's height by the row it sits in, so the extra room
|
||||
// costs nothing that was being used.
|
||||
<aside className={dialog ? `${SIDE_COLUMN} ${fluid ? '' : 'sm:w-80'}` : `w-full ${fluid ? '' : 'sm:w-80'} shrink-0 flex flex-col rounded-[18px] border border-[color:var(--m-cbr)] bg-[color:var(--m-card)] overflow-hidden self-stretch`}>
|
||||
<aside className={dialog ? `${SIDE_COLUMN} ${fluid ? '' : 'sm:w-80'}` : `w-full ${fluid ? '' : 'sm:w-80'} shrink-0 flex flex-col self-stretch`}>
|
||||
{dialog ? (
|
||||
<ColumnHead icon={<Landmark size={13} strokeWidth={2.2} />}>{t('places.details.title')}</ColumnHead>
|
||||
) : (
|
||||
@@ -247,16 +247,15 @@ export default function PlaceDetailsColumn({
|
||||
aria-expanded={open}
|
||||
aria-controls={bodyId}
|
||||
onClick={() => setOpen(o => !o)}
|
||||
className={`flex w-full shrink-0 items-center gap-2.5 px-3 py-2.5 text-start ${open ? 'border-b border-[color:var(--m-rowbr)]' : ''}`}
|
||||
// A badge over the column's blocks: what they are, and the fold.
|
||||
className="flex h-[36px] w-full shrink-0 items-center gap-2 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] pe-3 ps-3.5 text-start"
|
||||
>
|
||||
<span className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-ink">
|
||||
<Landmark size={15} strokeWidth={2} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 text-body font-semibold text-m-ink">{t('places.details.title')}</span>
|
||||
<Landmark size={13} strokeWidth={2.2} className="flex-none text-m-muted" />
|
||||
<span className="min-w-0 flex-1 truncate font-geist text-caption font-semibold text-m-ink">{t('places.details.title')}</span>
|
||||
<ChevronDown
|
||||
size={16}
|
||||
size={13}
|
||||
strokeWidth={2.2}
|
||||
className={`flex-none text-m-muted transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
|
||||
className={`flex-none text-m-faint transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
)}
|
||||
@@ -267,7 +266,7 @@ export default function PlaceDetailsColumn({
|
||||
className={dialog ? 'contents' : `grid transition-[grid-template-rows] duration-300 ease-out ${open ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'}`}
|
||||
>
|
||||
<div className={dialog ? 'flex min-h-0 flex-1 flex-col gap-3.5 overflow-y-auto px-3 pb-3' : `min-h-0 overflow-hidden ${open ? '' : 'invisible'}`}>
|
||||
<div className={dialog ? 'contents' : 'p-3 space-y-3'}>
|
||||
<div className={dialog ? 'contents' : 'space-y-3 pt-3'}>
|
||||
{/* The place's picture first: its own ones are there whatever the sources answer. */}
|
||||
<PictureBlock
|
||||
photos={state === 'ready' && !data?.disabled ? (data?.photos ?? []) : []}
|
||||
|
||||
@@ -47,6 +47,11 @@ export interface PlaceFormData {
|
||||
// Which shareable fields the user typed and which a pick or the details column filled
|
||||
// (placeFieldOrigins.ts). Rides along to the save as `fieldOrigins`; never shown.
|
||||
fieldOrigins?: PlaceFieldOrigins
|
||||
// The ids of the place's tags, always the whole set, as the save takes them. Absent
|
||||
// until one is ticked or unticked in the form (usePlaceTags): a missing key writes
|
||||
// nothing, so a save that never touched the tags cannot undo a tag put on the place
|
||||
// elsewhere in the meantime.
|
||||
tags?: number[]
|
||||
}
|
||||
|
||||
export function isGoogleMapsUrl(input: string): boolean {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// FE-PLANNER-PLACEFORM-TAGS-001 to FE-PLANNER-PLACEFORM-TAGS-004: the place's tags in the
|
||||
// desktop dialog. The logic is usePlaceTags', tested on its own; this is the form around it.
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildPlace, buildTag } from '../../../tests/helpers/factories';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { placeFormProps, seedPlaceFormStores } from '../../../tests/helpers/placeFormSetup';
|
||||
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import PlaceFormModal from './PlaceFormModal';
|
||||
|
||||
vi.mock('../shared/CustomTimePicker', async () => ({
|
||||
default: (await import('../../../tests/helpers/placeForm')).TimePickerStub,
|
||||
}));
|
||||
|
||||
const monument = buildTag({ id: 7, trip_id: 1, name: 'Monument', color: '#6366f1' });
|
||||
const zone = buildTag({ id: 8, trip_id: 1, name: 'Zone', color: '#10b981' });
|
||||
|
||||
const tagGroup = () => screen.getByRole('group', { name: 'Tags' });
|
||||
const tagSwitch = (name: string) => within(tagGroup()).getByRole('button', { name });
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedPlaceFormStores();
|
||||
seedStore(useTripStore, { tripTags: [monument, zone] });
|
||||
});
|
||||
|
||||
describe('PlaceFormModal, the tags', () => {
|
||||
it('FE-PLANNER-PLACEFORM-TAGS-001: a new place is saved with the tags ticked in the form', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
render(<PlaceFormModal {...placeFormProps} onSave={onSave} />);
|
||||
expect(tagSwitch('Monument')).toHaveAttribute('aria-pressed', 'false');
|
||||
|
||||
await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Belem Tower');
|
||||
await user.click(tagSwitch('Monument'));
|
||||
expect(tagSwitch('Monument')).toHaveAttribute('aria-pressed', 'true');
|
||||
await user.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
|
||||
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ name: 'Belem Tower', tags: [7] }));
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-TAGS-002: an edit starts from the tags the place carries and saves the whole set', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const place = buildPlace({ name: 'Belem Tower', tags: [{ id: 8, name: 'Zone' }] });
|
||||
render(<PlaceFormModal {...placeFormProps} place={place} onSave={onSave} />);
|
||||
expect(tagSwitch('Zone')).toHaveAttribute('aria-pressed', 'true');
|
||||
|
||||
await user.click(tagSwitch('Monument'));
|
||||
await user.click(tagSwitch('Zone'));
|
||||
await user.click(screen.getByRole('button', { name: /^Update$/i }));
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
|
||||
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ tags: [7] }));
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-TAGS-003: an edit that never touched the tags leaves them out of the save', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const place = buildPlace({ name: 'Belem Tower', tags: [{ id: 8, name: 'Zone' }] });
|
||||
render(<PlaceFormModal {...placeFormProps} place={place} onSave={onSave} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /^Update$/i }));
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
|
||||
expect(onSave.mock.calls[0][0]).not.toHaveProperty('tags');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-TAGS-004: a name typed into the tag field becomes a tag of the trip, ticked, without saving the place', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
let sent: unknown;
|
||||
server.use(
|
||||
http.post('/api/trips/1/tags', async ({ request }) => {
|
||||
sent = await request.json();
|
||||
return HttpResponse.json({ tag: buildTag({ id: 9, trip_id: 1, name: 'Viewpoint' }) }, { status: 201 });
|
||||
})
|
||||
);
|
||||
render(<PlaceFormModal {...placeFormProps} onSave={onSave} />);
|
||||
const field = screen.getByRole('textbox', { name: 'New tag' });
|
||||
expect(screen.getByRole('button', { name: 'Add tag' })).toBeDisabled();
|
||||
|
||||
await user.type(field, 'Viewpoint{Enter}');
|
||||
|
||||
// The tag reaches the trip first and is ticked a beat later, so wait for the tick itself.
|
||||
await waitFor(() => expect(tagSwitch('Viewpoint')).toHaveAttribute('aria-pressed', 'true'));
|
||||
expect(sent).toMatchObject({ name: 'Viewpoint' });
|
||||
expect(field).toHaveValue('');
|
||||
expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Viewpoint', 'Zone']);
|
||||
expect(onSave).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -66,7 +66,7 @@ describe('PlaceFormModal', () => {
|
||||
|
||||
it('FE-COMP-PLACEFORM-005: shows Description field', () => {
|
||||
render(<PlaceFormModal {...defaultProps} />);
|
||||
expect(screen.getByPlaceholderText(/Short description/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Description')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACEFORM-006: shows Address field', () => {
|
||||
@@ -1486,8 +1486,9 @@ describe('PlaceFormModal', () => {
|
||||
|
||||
render(<PlaceFormModal {...defaultProps} onSave={onSave} categories={[cat]} />);
|
||||
await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Louvre');
|
||||
await user.type(screen.getByPlaceholderText(/Short description/i), 'Glass pyramid');
|
||||
await user.type(screen.getByPlaceholderText(/Personal notes/i), 'Book ahead');
|
||||
await user.type(screen.getByLabelText('Description'), 'Glass pyramid');
|
||||
await user.click(within(screen.getByRole('group', { name: 'Text to edit' })).getByRole('button', { name: 'Notes' }));
|
||||
await user.type(screen.getByLabelText('Notes'), 'Book ahead');
|
||||
await user.type(screen.getByPlaceholderText(/Street, City, Country/i), 'Rue de Rivoli');
|
||||
await user.type(screen.getByPlaceholderText(/Longitude/i), '2.3376');
|
||||
await user.type(screen.getByPlaceholderText('https://...'), 'https://louvre.fr');
|
||||
@@ -2438,16 +2439,13 @@ describe('PlaceFormModal on the dialog frame', () => {
|
||||
// The icon button beside it carries the same name.
|
||||
expect(within(screen.getByPlaceholderText('Search places...').closest('.flex') as HTMLElement).getByRole('button', { name: 'Search' })).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Name *')).toHaveValue('Louvre');
|
||||
expect(screen.getByLabelText('Description')).toBe(screen.getByPlaceholderText(/Short description/i));
|
||||
expect(screen.getByLabelText('Notes')).toBe(screen.getByPlaceholderText(/Personal notes/i));
|
||||
expect(screen.getByLabelText('Address')).toBe(screen.getByPlaceholderText(/Street, City, Country/i));
|
||||
expect(screen.getByLabelText('Notes for this day')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Website')).toBe(screen.getByPlaceholderText('https://...'));
|
||||
const coords = screen.getByRole('group', { name: 'Coordinates' });
|
||||
expect(within(coords).getByPlaceholderText(/Latitude/i)).toBeInTheDocument();
|
||||
expect(within(coords).getByPlaceholderText(/Longitude/i)).toBeInTheDocument();
|
||||
// Each Markdown field keeps its own formatting bar.
|
||||
expect(screen.getAllByRole('toolbar')).toHaveLength(2);
|
||||
expect(screen.getAllByRole('toolbar', { hidden: true })).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLACEFORM-105: the new category field takes the focus when it opens', async () => {
|
||||
@@ -2683,10 +2681,10 @@ describe('PlaceFormModal in the look of the booking editors', () => {
|
||||
it('FE-PLANNER-PLACEFORM-120: the formatting bars show their names in the shared tooltip, never the native one', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PlaceFormModal {...defaultProps} />);
|
||||
const bars = screen.getAllByRole('toolbar');
|
||||
const bars = screen.getAllByRole('toolbar', { hidden: true });
|
||||
expect(bars).toHaveLength(2);
|
||||
for (const bar of bars) {
|
||||
for (const button of within(bar).getAllByRole('button')) expect(button).not.toHaveAttribute('title');
|
||||
for (const b of within(bar).getAllByRole('button', { hidden: true })) expect(b).not.toHaveAttribute('title');
|
||||
}
|
||||
await user.hover(within(bars[0]).getByRole('button', { name: 'Bold' }));
|
||||
expect(await screen.findByRole('tooltip')).toHaveTextContent('Bold');
|
||||
@@ -2746,6 +2744,7 @@ describe('PlaceFormModal and the columns beside it', () => {
|
||||
const assignment = buildAssignment({ id: 123, day_id: 5, place, notes: 'Old note' });
|
||||
render(<PlaceFormModal {...defaultProps} onSave={onSave} place={place} assignmentId={123} dayAssignments={[assignment]} />);
|
||||
|
||||
await user.click(within(screen.getByRole('group', { name: 'Text to edit' })).getByRole('button', { name: /day/i }));
|
||||
const notes = screen.getByRole('textbox', { name: 'Notes for this day' });
|
||||
expect(notes).toHaveValue('Old note');
|
||||
await user.clear(notes);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNode } from 'react'
|
||||
import type { PlaceClientOrigin, RoadtripStopType, TourListItem } from '@trek/shared'
|
||||
import NoteFormatToolbar from '../shared/NoteFormatToolbar'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
@@ -23,6 +23,9 @@ import {
|
||||
prefillForm, savedCategoryId, type PlaceFormData, type PlacePrefill,
|
||||
} from './PlaceFormModal.helpers'
|
||||
import { useNewCategory, usePlaceForm } from './usePlaceForm'
|
||||
import { usePlaceTags } from './usePlaceTags'
|
||||
import { PlaceFormTags } from './PlaceFormTags'
|
||||
import { PlaceFormTexts } from './PlaceFormTexts'
|
||||
import { usePlaceSearch } from './usePlaceSearch'
|
||||
import { guessCategoryId } from '@trek/shared'
|
||||
import { offersGoogleRetry } from '../../utils/placeSource'
|
||||
@@ -37,9 +40,9 @@ import { DEFAULT_SERVICE_KIND, serviceStopChoice, type ServiceStopMode } from '.
|
||||
import { STOP_KIND_BY_KEY } from '../Roadtrip/stopKinds'
|
||||
import { getCategoryIcon } from '../shared/categoryIcons'
|
||||
import {
|
||||
DialogShell, DialogHeader, DialogTile, DialogSection, DialogFooter, FooterSpacer, DialogButton, NEUTRAL_TINT, fs,
|
||||
DialogShell, DialogHeader, DialogTile, DialogFooter, FooterSpacer, DialogButton, NEUTRAL_TINT, fs,
|
||||
} from '../shared/DialogShell'
|
||||
import { EditorField, GRID_2, INPUT, LABEL, PANEL, TEXTAREA } from '../shared/dialogParts'
|
||||
import { EditorField, GRID_2, INPUT, LABEL, PANEL } from '../shared/dialogParts'
|
||||
import { SoftPill, tintOf } from './planParts'
|
||||
import { TimeSection } from './PlaceFormTimeSection'
|
||||
import { HeaderPills } from './PlaceFormHeaderPills'
|
||||
@@ -118,7 +121,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const tripObj = useTripStore((s) => s.trip)
|
||||
const canUploadFiles = can('file_upload', tripObj)
|
||||
const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'))
|
||||
const isBudgetEnabled = useAddonStore((s) => s.isEnabled('budget'))
|
||||
const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget')
|
||||
const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem)
|
||||
const {
|
||||
form, setForm, autoFilledRef, pendingFiles, addFilesFromInput, removeFile, handlePaste, isSaving, setIsSaving,
|
||||
@@ -128,6 +131,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const image = usePlaceImageField({
|
||||
place, imageUrl: form.image_url, pendingImage, canUploadFiles, stageUpload, stageAttached, removeImage,
|
||||
})
|
||||
const tagField = usePlaceTags({ tripId, place, tags: form.tags, setForm, t, toast })
|
||||
// The index the picked place came from, as its row named it, shown as a pill
|
||||
// in the head band. Null for a place typed by hand or taken from the saved list.
|
||||
const [pickedSource, setPickedSource] = useState<string | null>(null)
|
||||
@@ -220,6 +224,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
}, [place, prefillCoords, isOpen, assignmentId])
|
||||
|
||||
const places = useTripStore((s) => s.places)
|
||||
const tripDays = useTripStore((s) => s.days)
|
||||
// Where the trip is happening — the hint that tells the search which of a
|
||||
// thousand identically named places is meant. Autocomplete wants a box, the
|
||||
// search wants a point; both are derived from the same places.
|
||||
@@ -403,6 +408,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
categories,
|
||||
assignmentId,
|
||||
dayAssignments,
|
||||
dayNumber: dayNumberOf(assignmentId, dayAssignments, tripDays),
|
||||
isMobile,
|
||||
collectionsEnabled,
|
||||
form,
|
||||
@@ -451,6 +457,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
handlePaste,
|
||||
pickImage,
|
||||
image,
|
||||
tagField,
|
||||
adoptDescription,
|
||||
hasTimeError,
|
||||
handleSubmit,
|
||||
@@ -792,13 +799,15 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Extra labels next to the one category, to filter the places by. Not for a
|
||||
stop on a drive, which is not an activity anyone looks up by its tags. */}
|
||||
{!serviceStop && <PlaceFormTags tags={S.tagField} t={t} />}
|
||||
|
||||
{/* The day in context: its times and its own note. Both live on the
|
||||
day-assignment, not on the pool place (#2163), so they are only shown
|
||||
when a single assignment is in context (itinerary edit, or a
|
||||
single-assignment pool edit). Hidden when creating, and for unassigned
|
||||
or multi-day pool edits where a single time is ambiguous and would not
|
||||
persist. */}
|
||||
{/* The day in context: its times. They live on the day-assignment, not on
|
||||
the pool place (#2163), so they are only shown when a single assignment
|
||||
is in context (itinerary edit, or a single-assignment pool edit). Hidden
|
||||
when creating, and for unassigned or multi-day pool edits where a single
|
||||
time is ambiguous and would not persist. */}
|
||||
{!!(place && S.assignmentId) && (
|
||||
<div className={PANEL}>
|
||||
<TimeSection
|
||||
@@ -811,39 +820,25 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
tour={props.tour}
|
||||
t={t}
|
||||
/>
|
||||
<EditorField label={t('places.assignmentNotes')} htmlFor={`${fieldId}-day-notes`}>
|
||||
<textarea
|
||||
id={`${fieldId}-day-notes`}
|
||||
value={form.assignment_notes ?? ''}
|
||||
onChange={e => handleChange('assignment_notes', e.target.value)}
|
||||
rows={2}
|
||||
placeholder={t('places.assignmentNotesPlaceholder')}
|
||||
className={`${TEXTAREA} resize-y`}
|
||||
/>
|
||||
</EditorField>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<MarkdownField
|
||||
id={`${fieldId}-description`}
|
||||
label={t('places.formDescription')}
|
||||
value={form.description}
|
||||
onChange={v => handleChange('description', v)}
|
||||
placeholder={t('places.formDescriptionPlaceholder')}
|
||||
{/* Description, notes and the note for this day, one at a time. The day
|
||||
note follows the times: only with a single assignment in context. */}
|
||||
<PlaceFormTexts
|
||||
fieldId={fieldId}
|
||||
description={form.description}
|
||||
notes={form.notes}
|
||||
dayNotes={place && S.assignmentId ? (form.assignment_notes ?? "") : null}
|
||||
dayNumber={S.dayNumber}
|
||||
onChange={(field, value) => handleChange(field, value)}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
{/* Notes — Markdown, same as the description, and rendered as such in the
|
||||
inspector. The bar is how anyone finds that out. */}
|
||||
<MarkdownField
|
||||
id={`${fieldId}-notes`}
|
||||
label={t('places.formNotes')}
|
||||
value={form.notes}
|
||||
onChange={v => handleChange('notes', v)}
|
||||
placeholder={t('places.formNotesPlaceholder')}
|
||||
maxLength={2000}
|
||||
/>
|
||||
{!showDetails && <div className={PANEL}><PlaceImageSection image={S.image} onPickUrl={S.pickImage} t={t} /></div>}
|
||||
|
||||
{!showDetails && <PlaceImageSection image={S.image} onPickUrl={S.pickImage} t={t} />}
|
||||
{/* Link, files and how to reach the place, in one card. */}
|
||||
<div className={PANEL}>
|
||||
{/* The link and the files side by side, as on a booking. */}
|
||||
<div className={canUploadFiles ? GRID_2 : ''}>
|
||||
<EditorField label={t('places.formWebsite')} htmlFor={`${fieldId}-website`}>
|
||||
@@ -877,6 +872,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
suggestedHours={S.detailsHours}
|
||||
onChange={(field, value, origin) => handleChange(field, value, origin)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Costs — create / view the expense linked to this place (#1298).
|
||||
Same block, same flow as a booking: save first, then the editor.
|
||||
@@ -884,6 +880,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
Never for a stop on a drive: a petrol stop is not an activity with a budget
|
||||
line, and the fuel it buys is an expense of the trip rather than of a place. */}
|
||||
{S.isBudgetEnabled && !serviceStop && (
|
||||
<div className={PANEL}>
|
||||
<BookingCostsSection
|
||||
placeId={place?.id ?? null}
|
||||
reservationId={null}
|
||||
@@ -895,6 +892,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
customTooltips
|
||||
whiteButtons
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
{twoColumn && (
|
||||
@@ -905,32 +903,9 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
|
||||
)
|
||||
}
|
||||
|
||||
/** A Markdown field: its label, the formatting bar on the same line, the text under both. */
|
||||
function MarkdownField({ id, label, value, onChange, placeholder, maxLength }: {
|
||||
id: string
|
||||
label: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder: string
|
||||
maxLength?: number
|
||||
}) {
|
||||
const ref = useRef<HTMLTextAreaElement | null>(null)
|
||||
return (
|
||||
<DialogSection
|
||||
className="min-w-0"
|
||||
label={<label htmlFor={id}>{label}</label>}
|
||||
action={<NoteFormatToolbar textareaRef={ref} onChange={onChange} compact customTooltips />}
|
||||
>
|
||||
<textarea
|
||||
id={id}
|
||||
ref={ref}
|
||||
value={value}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
rows={3}
|
||||
maxLength={maxLength}
|
||||
placeholder={placeholder}
|
||||
className={`${TEXTAREA} resize-y`}
|
||||
/>
|
||||
</DialogSection>
|
||||
)
|
||||
/** The number of the day the edited visit is on, for the day note's tab; null when it is not known. */
|
||||
function dayNumberOf(assignmentId: number | null, visits: Assignment[], days: { id: number; day_number?: number | null }[]): number | null {
|
||||
if (!assignmentId) return null
|
||||
const dayId = visits.find(visit => visit.id === assignmentId)?.day_id
|
||||
return days.find(day => day.id === dayId)?.day_number ?? null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// FE-PLANNER-PLFORMTAGS-001 to FE-PLANNER-PLFORMTAGS-007: the markup of the place form's tags
|
||||
// on the desktop. The state behind it is usePlaceTags', tested on its own.
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
|
||||
import { PlaceFormTags } from './PlaceFormTags';
|
||||
import type { PlaceTagsField } from './usePlaceTags';
|
||||
|
||||
const t = (key: string) => key;
|
||||
|
||||
function field(overrides: Partial<PlaceTagsField> = {}): PlaceTagsField {
|
||||
return {
|
||||
options: [
|
||||
{ id: 7, name: 'Monument', color: '#6366f1', on: true },
|
||||
{ id: 8, name: 'Zone', on: false },
|
||||
],
|
||||
toggle: vi.fn(),
|
||||
name: '',
|
||||
setName: vi.fn(),
|
||||
newColor: '#ec4899',
|
||||
setNewColor: vi.fn(),
|
||||
recolor: vi.fn(() => Promise.resolve()),
|
||||
saving: false,
|
||||
canAdd: false,
|
||||
addNew: vi.fn(() => Promise.resolve()),
|
||||
handleNameKey: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('PlaceFormTags', () => {
|
||||
it('FE-PLANNER-PLFORMTAGS-001: shows every tag on offer as a switch that says whether it is on', () => {
|
||||
render(<PlaceFormTags tags={field()} t={t} />);
|
||||
const group = screen.getByRole('group', { name: 'places.tags' });
|
||||
expect(within(group).getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(within(group).getByRole('button', { name: 'Zone' })).toHaveAttribute('aria-pressed', 'false');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLFORMTAGS-002: a click on a tag switches that tag', () => {
|
||||
const tags = field();
|
||||
render(<PlaceFormTags tags={tags} t={t} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Zone' }));
|
||||
expect(tags.toggle).toHaveBeenCalledTimes(1);
|
||||
expect(tags.toggle).toHaveBeenCalledWith(8);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLFORMTAGS-003: the name of a new tag is typed into the field, whose keys go to the hook', () => {
|
||||
const tags = field({ name: 'View' });
|
||||
render(<PlaceFormTags tags={tags} t={t} />);
|
||||
const input = screen.getByRole('textbox', { name: 'places.newTag' });
|
||||
expect(input).toHaveValue('View');
|
||||
expect(input).toHaveAttribute('maxlength', '50');
|
||||
fireEvent.change(input, { target: { value: 'Viewpoint' } });
|
||||
expect(tags.setName).toHaveBeenCalledWith('Viewpoint');
|
||||
fireEvent.keyDown(input, { key: 'Enter' });
|
||||
expect(tags.handleNameKey).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLFORMTAGS-004: the add button waits for a name, then adds the tag; a trip without tags shows the field alone', () => {
|
||||
const idle = field({ options: [] });
|
||||
const { unmount } = render(<PlaceFormTags tags={idle} t={t} />);
|
||||
expect(screen.getByRole('button', { name: 'places.addTag' })).toBeDisabled();
|
||||
expect(within(screen.getByRole('group', { name: 'places.tags' })).getAllByRole('button')).toHaveLength(2);
|
||||
unmount();
|
||||
|
||||
const ready = field({ name: 'Viewpoint', canAdd: true });
|
||||
render(<PlaceFormTags tags={ready} t={t} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'places.addTag' }));
|
||||
expect(ready.addNew).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("FE-PLANNER-PLFORMTAGS-005: a tag's dot opens the palette, and a swatch recolours the tag and closes it", () => {
|
||||
const tags = field();
|
||||
render(<PlaceFormTags tags={tags} t={t} />);
|
||||
// The mock t ignores the name, so the first dot is Monument's.
|
||||
const dot = screen.getAllByRole('button', { name: 'places.tagColor' })[0];
|
||||
expect(screen.queryByRole('button', { name: '#10b981' })).not.toBeInTheDocument();
|
||||
fireEvent.click(dot);
|
||||
expect(dot).toHaveAttribute('aria-expanded', 'true');
|
||||
// The tag's own colour is the one marked.
|
||||
expect(screen.getByRole('button', { name: '#6366f1' })).toHaveAttribute('aria-pressed', 'true');
|
||||
fireEvent.click(screen.getByRole('button', { name: '#10b981' }));
|
||||
expect(tags.recolor).toHaveBeenCalledWith(7, '#10b981');
|
||||
expect(screen.queryByRole('button', { name: '#10b981' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("FE-PLANNER-PLFORMTAGS-006: the new tag's colour is picked the same way and tints the field once a name is typed", () => {
|
||||
const tags = field({ name: 'Food' });
|
||||
render(<PlaceFormTags tags={tags} t={t} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'places.newTagColor' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: '#f97316' }));
|
||||
expect(tags.setNewColor).toHaveBeenCalledWith('#f97316');
|
||||
expect(tags.recolor).not.toHaveBeenCalled();
|
||||
const pill = screen.getByRole('textbox', { name: 'places.newTag' }).parentElement as HTMLElement;
|
||||
expect(pill.style.background).toContain('#ec4899');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLFORMTAGS-007: Escape and a click outside close the palette without a pick', () => {
|
||||
const tags = field();
|
||||
render(<PlaceFormTags tags={tags} t={t} />);
|
||||
const onDialogKey = vi.fn();
|
||||
document.addEventListener('keydown', onDialogKey);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'places.newTagColor' }));
|
||||
fireEvent.keyDown(screen.getByRole('button', { name: '#f97316' }), { key: 'Escape' });
|
||||
expect(screen.queryByRole('button', { name: '#f97316' })).not.toBeInTheDocument();
|
||||
// Escape stays in the palette and does not reach the dialog around it.
|
||||
expect(onDialogKey).not.toHaveBeenCalled();
|
||||
document.removeEventListener('keydown', onDialogKey);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'places.newTagColor' }));
|
||||
fireEvent.pointerDown(document.body);
|
||||
expect(screen.queryByRole('button', { name: '#f97316' })).not.toBeInTheDocument();
|
||||
expect(tags.setNewColor).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { TRIP_TAG_NAME_MAX } from '@trek/shared';
|
||||
import { Check, Plus } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { DialogSection, fs } from '../shared/DialogShell';
|
||||
import { PANEL } from '../shared/dialogParts';
|
||||
import { TagColorPopover } from './TagColorPopover';
|
||||
import type { PlaceTagsField } from './usePlaceTags';
|
||||
|
||||
type Translate = (key: string, params?: Record<string, string | number>) => string;
|
||||
|
||||
const ROW = 'flex flex-wrap items-center gap-2';
|
||||
/** One tag: the colour dot and the name, two buttons in one pill. */
|
||||
const PILL =
|
||||
'relative inline-flex h-8 min-w-0 max-w-full items-center rounded-full border shadow-sm transition-[background-color,border-color,box-shadow] duration-150';
|
||||
const PILL_OFF = 'border-edge bg-surface-input hover:border-content-faint';
|
||||
const DOT_BUTTON =
|
||||
'ms-1 grid h-6 w-6 flex-none place-items-center rounded-full transition-transform duration-150 hover:scale-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]';
|
||||
const DOT = 'h-3.5 w-3.5 rounded-full ring-1 ring-inset ring-edge';
|
||||
const NAME_BUTTON = 'inline-flex h-full min-w-0 items-center gap-1.5 rounded-e-full ps-1.5 font-medium';
|
||||
/** The tick of a picked tag, in a round white badge. */
|
||||
const TICK = 'me-1 grid h-5 w-5 flex-none place-items-center rounded-full bg-surface-card shadow-sm';
|
||||
const NEW_TAG =
|
||||
'relative inline-flex h-8 min-w-0 items-center rounded-full border pe-1 transition-[background-color,border-color,box-shadow] duration-150 focus-within:shadow-sm';
|
||||
const NEW_TAG_INPUT = 'w-32 min-w-0 bg-transparent ps-1.5 text-content outline-none placeholder:text-content-faint';
|
||||
const ADD_BUTTON =
|
||||
'grid h-6 w-6 flex-none place-items-center rounded-full shadow-sm transition-[background-color,color,transform] duration-150 enabled:hover:scale-110 disabled:cursor-default disabled:bg-surface-tertiary disabled:text-content-faint disabled:shadow-none';
|
||||
|
||||
const FALLBACK_COLOR = 'var(--text-muted)';
|
||||
const tint = (color: string, percent: number) => `color-mix(in srgb, ${color} ${percent}%, var(--bg-input))`;
|
||||
|
||||
/**
|
||||
* The tags of the place form on the desktop, as a card like the search and the
|
||||
* address. Every tag on offer is a pill in its own colour: the name ticks it for
|
||||
* the place, the dot opens a palette that recolours it for the whole trip. The
|
||||
* field after them adds a new tag, in a colour picked the same way and shown on
|
||||
* the field as it is typed. The state is usePlaceTags'; this is its markup.
|
||||
*/
|
||||
export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate }) {
|
||||
// Which palette is open: a tag's id, 'new' for the new tag's colour, or none.
|
||||
const [palette, setPalette] = useState<number | 'new' | null>(null);
|
||||
// The colour a tag shows while its custom colour is being dragged, before it is kept.
|
||||
const [preview, setPreview] = useState<{ id: number; color: string } | null>(null);
|
||||
const typing = !!tags.name.trim();
|
||||
const closePalette = () => {
|
||||
setPalette(null);
|
||||
setPreview(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={PANEL}>
|
||||
<DialogSection label={t('places.tags')}>
|
||||
<div role="group" aria-label={t('places.tags')} className={ROW}>
|
||||
{tags.options.map((tag) => {
|
||||
const color = (preview?.id === tag.id ? preview.color : tag.color) ?? FALLBACK_COLOR;
|
||||
return (
|
||||
<span
|
||||
key={tag.id}
|
||||
className={`${PILL} ${tag.on ? '' : PILL_OFF}`}
|
||||
style={tag.on ? { background: tint(color, 18), borderColor: tint(color, 55) } : undefined}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.tagColor', { name: tag.name })}
|
||||
aria-expanded={palette === tag.id}
|
||||
onClick={() => (palette === tag.id ? closePalette() : setPalette(tag.id))}
|
||||
className={DOT_BUTTON}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: color }} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={tag.on}
|
||||
onClick={() => tags.toggle(tag.id)}
|
||||
className={`${NAME_BUTTON} ${tag.on ? 'pe-0 text-content' : 'pe-3 text-content-secondary hover:text-content'}`}
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
<span className="truncate">{tag.name}</span>
|
||||
{tag.on && (
|
||||
<span aria-hidden="true" className={TICK}>
|
||||
<Check size={11} strokeWidth={3.2} style={{ color }} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{palette === tag.id && (
|
||||
<TagColorPopover
|
||||
label={t('places.tagColor', { name: tag.name })}
|
||||
value={tag.color ?? null}
|
||||
onPick={(next) => void tags.recolor(tag.id, next)}
|
||||
onPreview={(next) => setPreview({ id: tag.id, color: next })}
|
||||
onClose={closePalette}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
<span
|
||||
className={NEW_TAG}
|
||||
style={{
|
||||
background: tint(tags.newColor, typing ? 14 : 6),
|
||||
borderColor: tint(tags.newColor, typing ? 60 : 35),
|
||||
borderStyle: typing ? 'solid' : 'dashed',
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.newTagColor')}
|
||||
aria-expanded={palette === 'new'}
|
||||
onClick={() => (palette === 'new' ? closePalette() : setPalette('new'))}
|
||||
className={DOT_BUTTON}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: tags.newColor }} />
|
||||
</button>
|
||||
<input
|
||||
type="text"
|
||||
value={tags.name}
|
||||
onChange={(e) => tags.setName(e.target.value)}
|
||||
onKeyDown={tags.handleNameKey}
|
||||
maxLength={TRIP_TAG_NAME_MAX}
|
||||
aria-label={t('places.newTag')}
|
||||
placeholder={t('places.newTag')}
|
||||
className={NEW_TAG_INPUT}
|
||||
style={fs(12, 'body')}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void tags.addNew()}
|
||||
disabled={!tags.canAdd}
|
||||
aria-label={t('places.addTag')}
|
||||
className={ADD_BUTTON}
|
||||
style={tags.canAdd ? { background: tags.newColor, color: 'var(--bg-card)' } : undefined}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.8} />
|
||||
</button>
|
||||
{palette === 'new' && (
|
||||
<TagColorPopover
|
||||
label={t('places.newTagColor')}
|
||||
value={tags.newColor}
|
||||
onPick={tags.setNewColor}
|
||||
onPreview={tags.setNewColor}
|
||||
onClose={closePalette}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</DialogSection>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// FE-PLANNER-PLFORMTEXTS-001 to FE-PLANNER-PLFORMTEXTS-004: the place form's three texts in one card.
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
|
||||
import { PlaceFormTexts } from './PlaceFormTexts';
|
||||
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
params ? `${key}:${Object.values(params).join(',')}` : key;
|
||||
|
||||
function renderTexts(overrides: Partial<Parameters<typeof PlaceFormTexts>[0]> = {}) {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<PlaceFormTexts
|
||||
fieldId="f"
|
||||
description="A tower"
|
||||
notes=""
|
||||
dayNotes={null}
|
||||
onChange={onChange}
|
||||
t={t}
|
||||
{...overrides}
|
||||
/>
|
||||
);
|
||||
return onChange;
|
||||
}
|
||||
|
||||
const tabs = () => within(screen.getByRole('group', { name: 'places.notesKind' }));
|
||||
|
||||
describe('PlaceFormTexts', () => {
|
||||
it('FE-PLANNER-PLFORMTEXTS-001: shows one text at a time, with the line on where it appears', () => {
|
||||
renderTexts();
|
||||
expect(tabs().getByRole('button', { name: 'places.notesTabAbout' })).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByLabelText('places.formDescription')).toBeVisible();
|
||||
expect(screen.getByLabelText('places.formNotes')).not.toBeVisible();
|
||||
expect(screen.getByLabelText('places.formDescription')).toHaveAccessibleDescription('places.notesHintDescription');
|
||||
|
||||
fireEvent.click(tabs().getByRole('button', { name: 'places.formNotes' }));
|
||||
expect(screen.getByLabelText('places.formNotes')).toBeVisible();
|
||||
expect(screen.getByLabelText('places.formDescription')).not.toBeVisible();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLFORMTEXTS-002: each text writes its own field, and both keep their text while hidden', () => {
|
||||
const onChange = renderTexts({ notes: 'Book ahead' });
|
||||
fireEvent.change(screen.getByLabelText('places.formDescription'), { target: { value: 'A tall tower' } });
|
||||
expect(onChange).toHaveBeenLastCalledWith('description', 'A tall tower');
|
||||
expect(screen.getByLabelText('places.formNotes')).toHaveValue('Book ahead');
|
||||
fireEvent.change(screen.getByLabelText('places.formNotes'), { target: { value: 'Book early' } });
|
||||
expect(onChange).toHaveBeenLastCalledWith('notes', 'Book early');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLFORMTEXTS-003: the day tab is there only with a visit in context, named after its day', () => {
|
||||
renderTexts();
|
||||
expect(tabs().getAllByRole('button')).toHaveLength(2);
|
||||
expect(screen.queryByLabelText('places.assignmentNotes')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLFORMTEXTS-004: the day note is plain text under the tab of its day', () => {
|
||||
const onChange = renderTexts({ dayNotes: 'Meet at 9', dayNumber: 3 });
|
||||
const day = tabs().getByRole('button', { name: 'places.notesTabDayN:3' });
|
||||
fireEvent.click(day);
|
||||
const field = screen.getByLabelText('places.assignmentNotes');
|
||||
expect(field).toBeVisible();
|
||||
expect(field).toHaveValue('Meet at 9');
|
||||
fireEvent.change(field, { target: { value: 'Meet at 10' } });
|
||||
expect(onChange).toHaveBeenLastCalledWith('assignment_notes', 'Meet at 10');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import { CalendarDays, Info, StickyNote } from 'lucide-react';
|
||||
import { useRef, type ReactNode } from 'react';
|
||||
|
||||
import { fs } from '../shared/DialogShell';
|
||||
import NoteFormatToolbar from '../shared/NoteFormatToolbar';
|
||||
import { PANEL, Segmented } from '../shared/dialogParts';
|
||||
import { usePlaceTextTabs, type PlaceTextField } from './usePlaceTextTabs';
|
||||
|
||||
type Translate = (key: string, params?: Record<string, string | number>) => string;
|
||||
|
||||
/** The desktop draws each tab with an icon; the phone keeps to the words. */
|
||||
const ICONS: Record<PlaceTextField, ReactNode> = {
|
||||
description: <Info size={13} strokeWidth={2} />,
|
||||
notes: <StickyNote size={13} strokeWidth={2} />,
|
||||
assignment_notes: <CalendarDays size={13} strokeWidth={2} />,
|
||||
};
|
||||
|
||||
const DOT = 'h-1.5 w-1.5 flex-none rounded-full bg-current opacity-60';
|
||||
/** The field's frame, holding the text and, under it, the formatting bar, like a message composer. */
|
||||
const FIELD_BOX =
|
||||
'overflow-hidden rounded-[10px] border border-edge bg-surface-input focus-within:ring-2 focus-within:ring-[color:var(--text-primary)]';
|
||||
const BARE_TEXTAREA =
|
||||
'block w-full min-w-0 resize-y border-0 bg-transparent px-3 py-2 text-[length:calc(13px*var(--fs-scale-body,1))] leading-normal text-content outline-none placeholder:text-content-faint';
|
||||
const FIELD_BAR = 'flex items-center justify-end border-t border-edge-faint px-1.5 py-0.5';
|
||||
|
||||
/**
|
||||
* The place's three texts in one card: what the place is, notes on it, and the
|
||||
* note for this day's visit. A switch on top picks the one to write; the others
|
||||
* stay mounted and only hidden, so each keeps its caret and undo history, and a
|
||||
* dot marks a tab that already holds text. The day tab is there only when the
|
||||
* form edits one day-assignment.
|
||||
*/
|
||||
export function PlaceFormTexts({
|
||||
fieldId,
|
||||
description,
|
||||
notes,
|
||||
dayNotes,
|
||||
dayNumber = null,
|
||||
onChange,
|
||||
t,
|
||||
}: {
|
||||
fieldId: string;
|
||||
description: string;
|
||||
notes: string;
|
||||
/** null when no single day-assignment is in context. */
|
||||
dayNotes: string | null;
|
||||
/** The day that visit is on, to name the tab after it ("Only day 3"). */
|
||||
dayNumber?: number | null;
|
||||
onChange: (field: PlaceTextField, value: string) => void;
|
||||
t: Translate;
|
||||
}) {
|
||||
const { tabs, shown, setActive } = usePlaceTextTabs({ description, notes, dayNotes, dayNumber, t });
|
||||
const refs = {
|
||||
description: useRef<HTMLTextAreaElement | null>(null),
|
||||
notes: useRef<HTMLTextAreaElement | null>(null),
|
||||
assignment_notes: useRef<HTMLTextAreaElement | null>(null),
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={PANEL}>
|
||||
<Segmented<PlaceTextField>
|
||||
fill
|
||||
value={shown.field}
|
||||
onChange={setActive}
|
||||
label={t('places.notesKind')}
|
||||
options={tabs.map((tab) => ({
|
||||
value: tab.field,
|
||||
label: tab.value.trim() ? (
|
||||
<>
|
||||
{tab.label}
|
||||
<span aria-hidden="true" className={DOT} />
|
||||
</>
|
||||
) : (
|
||||
tab.label
|
||||
),
|
||||
icon: (
|
||||
<span aria-hidden="true" className="flex">
|
||||
{ICONS[tab.field]}
|
||||
</span>
|
||||
),
|
||||
}))}
|
||||
/>
|
||||
{tabs.map((tab) => (
|
||||
<p
|
||||
key={tab.field}
|
||||
id={`${fieldId}-${tab.field}-hint`}
|
||||
hidden={tab.field !== shown.field}
|
||||
className="m-0 -mb-1 leading-snug text-content-muted"
|
||||
style={fs(11)}
|
||||
>
|
||||
{tab.hint}
|
||||
</p>
|
||||
))}
|
||||
{/* The box hides, not the field: the field's own `block` class would win over `hidden`. */}
|
||||
{tabs.map((tab) => (
|
||||
<div key={tab.field} hidden={tab.field !== shown.field} className={FIELD_BOX}>
|
||||
<textarea
|
||||
id={`${fieldId}-${tab.field}`}
|
||||
ref={refs[tab.field]}
|
||||
aria-label={tab.aria}
|
||||
aria-describedby={`${fieldId}-${tab.field}-hint`}
|
||||
value={tab.value}
|
||||
onChange={(e) => onChange(tab.field, e.target.value)}
|
||||
rows={3}
|
||||
maxLength={tab.maxLength}
|
||||
className={BARE_TEXTAREA}
|
||||
/>
|
||||
{tab.markdown && (
|
||||
<div className={FIELD_BAR}>
|
||||
<NoteFormatToolbar
|
||||
textareaRef={refs[tab.field]}
|
||||
onChange={(v) => onChange(tab.field, v)}
|
||||
compact
|
||||
customTooltips
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -169,7 +169,7 @@ function UploadTile({
|
||||
disabled={reading}
|
||||
aria-pressed={selected}
|
||||
aria-label={t('places.uploadImage')}
|
||||
className={`${TILE} ${ring(selected, dialog)} ${preview ? '' : 'border border-dashed border-edge bg-surface-card'}`}
|
||||
className={`${TILE} ${ring(selected, dialog)} ${preview ? '' : dialog ? 'border border-edge-faint bg-surface-secondary hover:bg-surface-tertiary' : 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]'}`}
|
||||
onMouseEnter={() => onHover(!!preview)}
|
||||
onMouseLeave={() => onHover(false)}
|
||||
>
|
||||
@@ -179,13 +179,15 @@ function UploadTile({
|
||||
{selected && <Picked />}
|
||||
</>
|
||||
) : (
|
||||
<span className="flex h-full w-full flex-col items-center justify-center gap-1 px-1 text-center text-caption leading-tight text-content-muted group-hover:text-content">
|
||||
{reading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<ImagePlus className="h-4 w-4" strokeWidth={2} />
|
||||
)}
|
||||
{t('places.uploadImage')}
|
||||
// Icon only: the tooltip and the button's name say what it does.
|
||||
<span className="flex h-full w-full items-center justify-center">
|
||||
<span className="grid h-11 w-11 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm transition-transform duration-150 group-hover:scale-105 group-hover:text-content">
|
||||
{reading ? (
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
) : (
|
||||
<ImagePlus className="h-5 w-5" strokeWidth={1.9} />
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
@@ -1782,6 +1782,17 @@ describe('PlaceInspector', () => {
|
||||
expect(header.textContent).not.toContain('·');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-INSPECTOR-106b: the tags of the place are pills beside its category, each once and by name', () => {
|
||||
const tags = [{ id: 8, name: 'Zone', color: '#10b981' }, { id: 7, name: 'Monument' }, { id: 8, name: 'Zone' }];
|
||||
render(<PlaceInspector {...defaultProps} place={{ ...place, id: 716, category_id: cat.id, tags }} />);
|
||||
const header = document.querySelector('header') as HTMLElement;
|
||||
const pills = ['Landmark', 'Monument', 'Zone'].map(name => within(header).getByText(name));
|
||||
expect(pills[0].compareDocumentPosition(pills[1]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(pills[1].compareDocumentPosition(pills[2]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
// The tag's own colour is on its mark only; the pill and the marker keep theirs.
|
||||
expect((pills[2].querySelector('svg') as SVGElement).style.color).toBe('rgb(16, 185, 129)');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-INSPECTOR-107: the rating block is labelled and quotes the first usable review', async () => {
|
||||
vi.mocked(mapsApi.details).mockResolvedValue({
|
||||
place: { rating: 4.1, reviews: [{ text: 'meh' }, { text: 'Lovely staff and view' }] },
|
||||
|
||||
@@ -330,7 +330,7 @@ export default function PlaceInspector({
|
||||
// periods next to them, in the place's own timezone. open_now stays the fallback.
|
||||
// Hours the traveller typed in win over looked-up ones (#2472): they are what
|
||||
// somebody actually checked, and a place nobody listed has no other source.
|
||||
const ownHours = hoursLines(place.opening_hours, locale, t('places.hoursClosed'))
|
||||
const ownHours = hoursLines(place.opening_hours, locale, t('places.hoursClosed'), t('places.hoursAllDay'))
|
||||
const openingHours = ownHours ?? googleDetails?.opening_hours ?? null
|
||||
const detailLat = place.lat ?? googleDetails?.lat
|
||||
const detailLng = place.lng ?? googleDetails?.lng
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
import { Banknote, ChevronDown, ChevronUp, Mail, MapPin, MapPinOff, Phone, Star, X } from 'lucide-react';
|
||||
import {
|
||||
Banknote,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Mail,
|
||||
MapPin,
|
||||
MapPinOff,
|
||||
Phone,
|
||||
Star,
|
||||
Tag as TagIcon,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import type { KeyboardEvent, ReactNode, RefObject } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import type { Category, Place } from '../../types';
|
||||
import { tagChoices } from '../../utils/placeTags';
|
||||
import AssistantAskButton from '../Assistant/AssistantAskButton';
|
||||
import DawarichIcon from '../shared/DawarichIcon';
|
||||
import { NEUTRAL_TINT, fs } from '../shared/DialogShell';
|
||||
@@ -84,9 +96,12 @@ export function InspectorHead({
|
||||
const hasCoords = !!(place.lat && place.lng);
|
||||
// A typed address that never got coordinates: the place has no marker, and says why (#2837).
|
||||
const offMap = addressWithoutCoordinates(place);
|
||||
// The extra labels of the place, beside its one category. They never reach the marker.
|
||||
const tags = tagChoices(place.tags);
|
||||
const hasPills =
|
||||
openNow !== null ||
|
||||
!!category ||
|
||||
tags.length > 0 ||
|
||||
!!time ||
|
||||
rating != null ||
|
||||
!!price ||
|
||||
@@ -174,6 +189,12 @@ export function InspectorHead({
|
||||
{category.name}
|
||||
</span>
|
||||
)}
|
||||
{tags.map((tag) => (
|
||||
<span key={tag.id} className={HEAD_PILL} style={fs(10.5)}>
|
||||
<TagIcon size={11} strokeWidth={2} className="flex-none" style={{ color: tag.color }} />
|
||||
{tag.name}
|
||||
</span>
|
||||
))}
|
||||
{time && <TimePill>{time}</TimePill>}
|
||||
{rating != null && rating > 0 && (
|
||||
<span className={HEAD_PILL} style={fs(10.5)}>
|
||||
|
||||
@@ -20,7 +20,8 @@ const LABEL: Record<RefreshField, string> = {
|
||||
/** A value as the list shows it: hours as one line per day, the rest as stored. */
|
||||
function shown(field: RefreshField, value: string, locale: string | undefined, t: Translate): string[] {
|
||||
if (!value) return [t('places.refresh.empty')];
|
||||
if (field === 'opening_hours') return hoursLines(value, locale, t('places.hoursClosed')) ?? [value];
|
||||
if (field === 'opening_hours')
|
||||
return hoursLines(value, locale, t('places.hoursClosed'), t('places.hoursAllDay')) ?? [value];
|
||||
return [value];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// FE-PLANNER-SIDEBAR-TAGS-001 to FE-PLANNER-SIDEBAR-TAGS-005: the tags in the category filter
|
||||
// of the desktop places list. The predicate itself is covered in utils/placesFilter.test.ts.
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildCategory, buildPlace, buildTag, buildTrip, buildUser } from '../../../tests/helpers/factories';
|
||||
import { render, screen, within } from '../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import PlacesSidebar from './PlacesSidebar';
|
||||
|
||||
// The rows' pictures would ask the server for photos.
|
||||
vi.mock('../../services/photoService', () => ({
|
||||
getCached: vi.fn(() => null),
|
||||
isLoading: vi.fn(() => false),
|
||||
fetchPhoto: vi.fn(),
|
||||
onThumbReady: vi.fn(() => () => undefined),
|
||||
}));
|
||||
|
||||
const monument = buildTag({ id: 7, trip_id: 1, name: 'Monument', color: '#6366f1' });
|
||||
const zone = buildTag({ id: 8, trip_id: 1, name: 'Zone', color: '#10b981' });
|
||||
const park = buildCategory({ id: 4, name: 'Park', color: '#22c55e' });
|
||||
|
||||
const tower = buildPlace({
|
||||
name: 'Belem Tower',
|
||||
address: 'Lisbon',
|
||||
category_id: 4,
|
||||
tags: [{ id: 7, name: 'Monument' }],
|
||||
});
|
||||
const garden = buildPlace({ name: 'Estrela Garden', address: 'Lisbon', category_id: 4 });
|
||||
const market = buildPlace({
|
||||
name: 'Time Out Market',
|
||||
address: 'Lisbon',
|
||||
category_id: null,
|
||||
// A traveller's personal tag, put on the place through the API: the trip does not list it.
|
||||
tags: [
|
||||
{ id: 8, name: 'Zone' },
|
||||
{ id: 50, name: 'Hidden gem' },
|
||||
],
|
||||
});
|
||||
|
||||
const props = {
|
||||
tripId: 1,
|
||||
places: [tower, garden, market],
|
||||
categories: [park],
|
||||
assignments: {},
|
||||
selectedDayId: null,
|
||||
selectedPlaceId: null,
|
||||
onPlaceClick: vi.fn(),
|
||||
onAddPlace: vi.fn(),
|
||||
onAssignToDay: vi.fn(),
|
||||
onEditPlace: vi.fn(),
|
||||
onDeletePlace: vi.fn(),
|
||||
days: [],
|
||||
isMobile: false,
|
||||
};
|
||||
|
||||
type User = ReturnType<typeof userEvent.setup>;
|
||||
|
||||
const trigger = () => screen.getByRole('button', { name: 'Categories' });
|
||||
|
||||
async function openFilter(user: User) {
|
||||
if (trigger().getAttribute('aria-expanded') !== 'true') await user.click(trigger());
|
||||
}
|
||||
|
||||
/** What the closed filter says is in force, read from its tooltip. */
|
||||
async function filterLabel(user: User) {
|
||||
if (trigger().getAttribute('aria-expanded') === 'true') await user.click(trigger());
|
||||
// The tip opens when the pointer comes in, so it leaves first.
|
||||
await user.unhover(trigger());
|
||||
await user.hover(trigger());
|
||||
const text = (await screen.findByRole('tooltip')).textContent;
|
||||
await user.unhover(trigger());
|
||||
return text;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1 }), tripTags: [monument, zone] });
|
||||
});
|
||||
|
||||
describe('PlacesSidebar category filter: tags', () => {
|
||||
it('FE-PLANNER-SIDEBAR-TAGS-001: lists the tags under the categories, the ones of the trip and any other a place carries', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PlacesSidebar {...props} />);
|
||||
await openFilter(user);
|
||||
expect(screen.getByText('Tags')).toBeInTheDocument();
|
||||
for (const name of ['Park', 'No Category', 'Hidden gem', 'Monument', 'Zone']) {
|
||||
expect(screen.getByRole('button', { name })).toHaveAttribute('aria-pressed', 'false');
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-PLANNER-SIDEBAR-TAGS-002: a ticked tag keeps the places that carry it', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PlacesSidebar {...props} />);
|
||||
await openFilter(user);
|
||||
await user.click(screen.getByRole('button', { name: 'Monument' }));
|
||||
expect(screen.getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByText('Belem Tower')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Estrela Garden')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Time Out Market')).not.toBeInTheDocument();
|
||||
expect(useTripStore.getState().placesCategoryFilter).toEqual(new Set(['tag:7']));
|
||||
expect(await filterLabel(user)).toBe('Categories: Monument');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-SIDEBAR-TAGS-003: a category and a tag ticked together both have to hold, and the filter names them', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PlacesSidebar {...props} />);
|
||||
await openFilter(user);
|
||||
await user.click(screen.getByRole('button', { name: 'Park' }));
|
||||
expect(screen.getByText('Estrela Garden')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Monument' }));
|
||||
expect(screen.getByText('Belem Tower')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Estrela Garden')).not.toBeInTheDocument();
|
||||
expect(within(trigger()).getByText('2')).toBeInTheDocument();
|
||||
expect(await filterLabel(user)).toBe('Categories: Park, Monument');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-SIDEBAR-TAGS-004: clearing the filter unticks the tags as well', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PlacesSidebar {...props} />);
|
||||
await openFilter(user);
|
||||
await user.click(screen.getByRole('button', { name: 'Zone' }));
|
||||
await user.click(screen.getByRole('button', { name: 'No Category' }));
|
||||
expect(screen.getByText('Time Out Market')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Belem Tower')).not.toBeInTheDocument();
|
||||
expect(await filterLabel(user)).toBe('Categories: No Category, Zone');
|
||||
|
||||
await openFilter(user);
|
||||
await user.click(screen.getByText('Clear filter'));
|
||||
expect(useTripStore.getState().placesCategoryFilter.size).toBe(0);
|
||||
expect(screen.getByText('Belem Tower')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Zone' })).toHaveAttribute('aria-pressed', 'false');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-SIDEBAR-TAGS-005: a trip with tags and no category still has the filter; with neither it has none', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { unmount } = render(<PlacesSidebar {...props} categories={[]} />);
|
||||
await openFilter(user);
|
||||
expect(screen.getByRole('button', { name: 'Monument' })).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
seedStore(useTripStore, { tripTags: [] });
|
||||
render(<PlacesSidebar {...props} categories={[]} places={[garden]} />);
|
||||
expect(screen.queryByRole('button', { name: 'Categories' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -8,9 +8,10 @@ import { Eyebrow } from './bookings/bookingParts'
|
||||
import { tintOf } from './planParts'
|
||||
import { CategoryTile } from './PlacesBulkCategoryModal'
|
||||
import type { SidebarState } from './usePlacesSidebar'
|
||||
import { placesFilterTabs } from './usePlacesPool'
|
||||
import { placesFilterTabs, usePlacesFilterTags } from './usePlacesPool'
|
||||
import { PLACES_SORTS, type PlacesSort } from './placesSort'
|
||||
import { RATING_FLOORS, UNCATEGORIZED } from '../../utils/placesFilter'
|
||||
import { RATING_FLOORS, UNCATEGORIZED, tagFilterKey } from '../../utils/placesFilter'
|
||||
import type { TagChoice } from '../../utils/placeTags'
|
||||
|
||||
/**
|
||||
* Below this the two labels stop fitting side by side and both buttons fall back
|
||||
@@ -249,22 +250,31 @@ function FilterDropdown({ label, active, badge, icon, open, setOpen, name, child
|
||||
)
|
||||
}
|
||||
|
||||
/** Which categories to show, many at once; the label says what is in force. */
|
||||
/**
|
||||
* What the category filter says is in force: nothing, the one name, or how many
|
||||
* categories. Once a tag is ticked too it is no count of categories any more, so
|
||||
* the names say it.
|
||||
*/
|
||||
function categoryFilterLabel({ t, categories, categoryFilters }: SidebarState, tags: TagChoice[]): string {
|
||||
if (categoryFilters.size === 0) return t('places.allCategories')
|
||||
const tagNames = tags.filter(tag => categoryFilters.has(tagFilterKey(tag.id))).map(tag => tag.name)
|
||||
if (tagNames.length === 0 && categoryFilters.size > 1) {
|
||||
return `${categoryFilters.size} ${t('places.categoriesSelected', { count: categoryFilters.size })}`
|
||||
}
|
||||
const names = categories.filter(c => categoryFilters.has(String(c.id))).map(c => c.name)
|
||||
if (categoryFilters.has(UNCATEGORIZED)) names.push(t('places.noCategory'))
|
||||
return [...names, ...tagNames].join(', ') || t('places.allCategories')
|
||||
}
|
||||
|
||||
/** Which categories and which tags to show, many at once; the label says what is in force. */
|
||||
function CategoryFilter(S: SidebarState) {
|
||||
const { t, places, categories, categoryFilters, setCategoryFilters, toggleCategoryFilter } = S
|
||||
const [open, setOpen] = useState(false)
|
||||
if (categories.length === 0) return null
|
||||
let label = t('places.allCategories')
|
||||
if (categoryFilters.size === 1) {
|
||||
const only = categories.find(c => categoryFilters.has(String(c.id)))
|
||||
if (categoryFilters.has(UNCATEGORIZED)) label = t('places.noCategory')
|
||||
else if (only) label = only.name
|
||||
} else if (categoryFilters.size > 1) {
|
||||
label = `${categoryFilters.size} ${t('places.categoriesSelected', { count: categoryFilters.size })}`
|
||||
}
|
||||
const tags = usePlacesFilterTags(places)
|
||||
if (categories.length === 0 && tags.length === 0) return null
|
||||
return (
|
||||
<FilterDropdown name={t('categories.title')} label={label} active={categoryFilters.size > 0} badge={categoryFilters.size}
|
||||
icon={<Tag size={14} strokeWidth={2} />} open={open} setOpen={setOpen}>
|
||||
<FilterDropdown name={t('categories.title')} label={categoryFilterLabel(S, tags)} active={categoryFilters.size > 0}
|
||||
badge={categoryFilters.size} icon={<Tag size={14} strokeWidth={2} />} open={open} setOpen={setOpen}>
|
||||
{categories.map(c => (
|
||||
<CategoryChoice
|
||||
key={c.id}
|
||||
@@ -282,6 +292,21 @@ function CategoryFilter(S: SidebarState) {
|
||||
label={t('places.noCategory')}
|
||||
/>
|
||||
)}
|
||||
{/* The tags, in the same list: a place has one category and any number of these. */}
|
||||
{tags.length > 0 && <Eyebrow className="px-1.5 pb-1 pt-2">{t('places.tags')}</Eyebrow>}
|
||||
{tags.map(tag => (
|
||||
<CategoryChoice
|
||||
key={tagFilterKey(tag.id)}
|
||||
on={categoryFilters.has(tagFilterKey(tag.id))}
|
||||
onClick={() => toggleCategoryFilter(tagFilterKey(tag.id))}
|
||||
tile={(
|
||||
<span className="grid h-[22px] w-[22px] flex-none place-items-center rounded-[7px] bg-surface-tertiary text-content-faint">
|
||||
<Tag size={11} strokeWidth={2.2} style={{ color: tag.color }} />
|
||||
</span>
|
||||
)}
|
||||
label={tag.name}
|
||||
/>
|
||||
))}
|
||||
{categoryFilters.size > 0 && (
|
||||
<button type="button" onClick={() => setCategoryFilters(new Set())}
|
||||
className="mt-1 flex w-full items-center gap-1.5 rounded-[9px] border-t border-edge-faint px-1.5 pb-1 pt-2 text-start font-semibold text-content-muted hover:text-content"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useMemo, useId } from 'react'
|
||||
import { useParams } from 'react-router'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
|
||||
import CustomSelect from '../shared/CustomSelect'
|
||||
import { BookingCodeInput } from '../shared/BookingCode'
|
||||
import { buildAssignmentOptions } from './assignmentOptions'
|
||||
@@ -71,7 +71,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
|
||||
const fileInputRef = useRef(null)
|
||||
const titleId = useId()
|
||||
|
||||
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const isBudgetEnabled = useTripAddonEnabled(Number(tripId), 'budget')
|
||||
const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)
|
||||
// Set right before submit when the user clicked create/edit expense.
|
||||
const expense = useBookingExpenseIntent(() => handleSubmit(), {
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// FE-PLANNER-TAGCOLORFIELD-001 to FE-PLANNER-TAGCOLORFIELD-003: the custom colour of the tag palette.
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { TagColorField } from './TagColorField';
|
||||
|
||||
const t = (key: string) => key;
|
||||
|
||||
function renderField(value = '#ff0000') {
|
||||
const onPreview = vi.fn();
|
||||
const onPick = vi.fn();
|
||||
render(<TagColorField value={value} onPreview={onPreview} onPick={onPick} t={t} />);
|
||||
return { onPreview, onPick };
|
||||
}
|
||||
|
||||
describe('TagColorField', () => {
|
||||
it('FE-PLANNER-TAGCOLORFIELD-001: a complete typed code is shown at once and kept on Enter; a broken one goes back', () => {
|
||||
const { onPreview, onPick } = renderField();
|
||||
const code = screen.getByRole('textbox', { name: 'places.tagColorHex' });
|
||||
expect(code).toHaveValue('#ff0000');
|
||||
fireEvent.change(code, { target: { value: '#10b9' } });
|
||||
expect(onPreview).not.toHaveBeenCalled();
|
||||
fireEvent.change(code, { target: { value: '10b981' } });
|
||||
expect(onPreview).toHaveBeenLastCalledWith('#10b981');
|
||||
fireEvent.keyDown(code, { key: 'Enter' });
|
||||
expect(onPick).toHaveBeenLastCalledWith('#10b981');
|
||||
|
||||
fireEvent.change(code, { target: { value: 'nope' } });
|
||||
fireEvent.blur(code);
|
||||
expect(code).toHaveValue('#10b981');
|
||||
expect(onPick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TAGCOLORFIELD-002: the arrow keys move the field and the hue, and keep each step', () => {
|
||||
const { onPick } = renderField('#ff0000');
|
||||
const field = screen.getByRole('slider', { name: 'places.tagColorCustom' });
|
||||
fireEvent.keyDown(field, { key: 'ArrowDown' });
|
||||
// Full red, a little darker.
|
||||
expect(onPick).toHaveBeenLastCalledWith('#f50000');
|
||||
const hue = screen.getByRole('slider', { name: 'places.tagColorHue' });
|
||||
expect(hue).toHaveAttribute('aria-valuenow', '0');
|
||||
fireEvent.keyDown(hue, { key: 'ArrowRight' });
|
||||
expect(hue).toHaveAttribute('aria-valuenow', '6');
|
||||
fireEvent.keyDown(hue, { key: 'Tab' });
|
||||
expect(onPick).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TAGCOLORFIELD-003: a drag shows the colour as it goes and keeps the one it ends on', () => {
|
||||
const { onPreview, onPick } = renderField('#ff0000');
|
||||
const field = screen.getByRole('slider', { name: 'places.tagColorCustom' });
|
||||
field.getBoundingClientRect = () => ({
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: 100,
|
||||
height: 100,
|
||||
right: 100,
|
||||
bottom: 100,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => ({}),
|
||||
});
|
||||
field.setPointerCapture = vi.fn();
|
||||
field.releasePointerCapture = vi.fn();
|
||||
field.hasPointerCapture = () => true;
|
||||
fireEvent.pointerDown(field, { pointerId: 1, clientX: 100, clientY: 0 });
|
||||
fireEvent.pointerMove(field, { pointerId: 1, clientX: 0, clientY: 0 });
|
||||
expect(onPreview).toHaveBeenLastCalledWith('#ffffff');
|
||||
expect(onPick).not.toHaveBeenCalled();
|
||||
fireEvent.pointerUp(field, { pointerId: 1, clientX: 0, clientY: 100 });
|
||||
expect(onPick).toHaveBeenCalledTimes(1);
|
||||
expect(onPick).toHaveBeenLastCalledWith('#000000');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import { useState, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
|
||||
import { hexToHsv, hsvToHex, hueHex, normalizeHex, type Hsv } from '../../utils/colorSpace';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
|
||||
type Translate = (key: string, params?: Record<string, string | number>) => string;
|
||||
|
||||
// The hue circle as a track, and the field over the picked hue: white to the right
|
||||
// into the hue, black from the bottom up. Built as strings so no colour literal sits in a style.
|
||||
const HUE_TRACK = `linear-gradient(to right, ${[0, 60, 120, 180, 240, 300, 360].map(hueHex).join(', ')})`;
|
||||
const fieldBackground = (h: number) =>
|
||||
`linear-gradient(to top, ${hsvToHex({ h: 0, s: 0, v: 0 })}, transparent), linear-gradient(to right, ${hsvToHex({ h: 0, s: 0, v: 1 })}, ${hueHex(h)})`;
|
||||
|
||||
const THUMB =
|
||||
'pointer-events-none absolute h-4 w-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-surface-card shadow-md';
|
||||
const KEY_STEP = 0.04;
|
||||
|
||||
const clamp = (n: number) => Math.min(1, Math.max(0, n));
|
||||
|
||||
/** Where a pointer is inside an element, as 0 to 1 across and down. */
|
||||
function at(e: ReactPointerEvent<HTMLElement>): { x: number; y: number } {
|
||||
const box = e.currentTarget.getBoundingClientRect();
|
||||
return { x: clamp((e.clientX - box.left) / box.width), y: clamp((e.clientY - box.top) / box.height) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The custom colour of the tag palette: a field for saturation and brightness,
|
||||
* a slider for the hue and the hex code to type. Dragging shows the colour as it
|
||||
* goes (onPreview); it is kept when the pointer lets go, or when a typed code is
|
||||
* complete (onPick), so a drag sends one change and not one per pixel.
|
||||
*/
|
||||
export function TagColorField({
|
||||
value,
|
||||
onPreview,
|
||||
onPick,
|
||||
t,
|
||||
}: {
|
||||
value: string;
|
||||
onPreview: (hex: string) => void;
|
||||
onPick: (hex: string) => void;
|
||||
t: Translate;
|
||||
}) {
|
||||
const [hsv, setHsv] = useState<Hsv>(() => hexToHsv(value));
|
||||
const [typed, setTyped] = useState(value);
|
||||
const hex = hsvToHex(hsv);
|
||||
|
||||
const show = (next: Hsv) => {
|
||||
setHsv(next);
|
||||
const nextHex = hsvToHex(next);
|
||||
setTyped(nextHex);
|
||||
onPreview(nextHex);
|
||||
};
|
||||
|
||||
const drag = (read: (e: ReactPointerEvent<HTMLElement>) => Hsv) => ({
|
||||
onPointerDown: (e: ReactPointerEvent<HTMLElement>) => {
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
show(read(e));
|
||||
},
|
||||
onPointerMove: (e: ReactPointerEvent<HTMLElement>) => {
|
||||
if (e.currentTarget.hasPointerCapture(e.pointerId)) show(read(e));
|
||||
},
|
||||
onPointerUp: (e: ReactPointerEvent<HTMLElement>) => {
|
||||
e.currentTarget.releasePointerCapture(e.pointerId);
|
||||
onPick(hsvToHex(read(e)));
|
||||
},
|
||||
});
|
||||
|
||||
// The arrow keys move the field's point and the slider, and keep the colour at once.
|
||||
const nudge = (patch: (cur: Hsv) => Hsv) => (e: KeyboardEvent<HTMLElement>) => {
|
||||
const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: 1, ArrowDown: -1 }[e.key];
|
||||
if (step === undefined) return;
|
||||
e.preventDefault();
|
||||
const next = patch({
|
||||
...hsv,
|
||||
...(e.key === 'ArrowUp' || e.key === 'ArrowDown'
|
||||
? { v: clamp(hsv.v + step * KEY_STEP) }
|
||||
: { s: clamp(hsv.s + step * KEY_STEP) }),
|
||||
});
|
||||
show(next);
|
||||
onPick(hsvToHex(next));
|
||||
};
|
||||
|
||||
const typeHex = (raw: string) => {
|
||||
setTyped(raw);
|
||||
const norm = normalizeHex(raw);
|
||||
if (!norm) return;
|
||||
setHsv(hexToHsv(norm));
|
||||
onPreview(norm);
|
||||
};
|
||||
const keepTyped = () => {
|
||||
const norm = normalizeHex(typed);
|
||||
if (norm) onPick(norm);
|
||||
else setTyped(hex);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2.5">
|
||||
<div
|
||||
role="slider"
|
||||
// The gradient runs left to right in every language; so does the pick on it.
|
||||
dir="ltr"
|
||||
tabIndex={0}
|
||||
aria-label={t('places.tagColorCustom')}
|
||||
aria-valuetext={hex}
|
||||
aria-valuenow={Math.round(hsv.s * 100)}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
className="relative h-28 cursor-crosshair touch-none rounded-[10px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]"
|
||||
style={{ background: fieldBackground(hsv.h) }}
|
||||
onKeyDown={nudge((next) => next)}
|
||||
{...drag((e) => {
|
||||
const p = at(e);
|
||||
return { h: hsv.h, s: p.x, v: 1 - p.y };
|
||||
})}
|
||||
>
|
||||
<span
|
||||
className={THUMB}
|
||||
style={{ insetInlineStart: `${hsv.s * 100}%`, top: `${(1 - hsv.v) * 100}%`, background: hex }}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
role="slider"
|
||||
// The gradient runs left to right in every language; so does the pick on it.
|
||||
dir="ltr"
|
||||
tabIndex={0}
|
||||
aria-label={t('places.tagColorHue')}
|
||||
aria-valuenow={Math.round(hsv.h)}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={360}
|
||||
className="relative h-3 cursor-pointer touch-none rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]"
|
||||
style={{ background: HUE_TRACK }}
|
||||
onKeyDown={(e) => {
|
||||
const step = { ArrowLeft: -6, ArrowRight: 6 }[e.key];
|
||||
if (step === undefined) return;
|
||||
e.preventDefault();
|
||||
const next = { ...hsv, h: (hsv.h + step + 360) % 360 };
|
||||
show(next);
|
||||
onPick(hsvToHex(next));
|
||||
}}
|
||||
{...drag((e) => ({ ...hsv, h: at(e).x * 359.9 }))}
|
||||
>
|
||||
<span
|
||||
className={`${THUMB} top-1/2`}
|
||||
style={{ insetInlineStart: `${(hsv.h / 360) * 100}%`, background: hueHex(hsv.h) }}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="h-7 w-7 flex-none rounded-full ring-1 ring-inset ring-edge"
|
||||
style={{ background: hex }}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={typed}
|
||||
onChange={(e) => typeHex(e.target.value)}
|
||||
onBlur={keepTyped}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'Enter') return;
|
||||
e.preventDefault();
|
||||
keepTyped();
|
||||
}}
|
||||
maxLength={7}
|
||||
spellCheck={false}
|
||||
aria-label={t('places.tagColorHex')}
|
||||
className="h-7 min-w-0 flex-1 rounded-[8px] border border-edge bg-surface-input px-2 font-mono uppercase text-content outline-none focus:border-content-faint"
|
||||
style={fs(12, 'body')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { Check, ChevronDown } from 'lucide-react';
|
||||
import { useEffect, useRef, useState, type KeyboardEvent } from 'react';
|
||||
|
||||
import { TAG_COLORS } from '../../utils/placeTags';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
import { TagColorField } from './TagColorField';
|
||||
|
||||
type Translate = (key: string, params?: Record<string, string | number>) => string;
|
||||
|
||||
const PANEL =
|
||||
'absolute start-0 top-full z-20 mt-2 flex w-[240px] flex-col gap-2.5 rounded-[16px] border border-edge-faint bg-surface-card p-3 shadow-lg';
|
||||
const SWATCH =
|
||||
'grid h-8 w-8 place-items-center rounded-full ring-1 ring-inset ring-edge transition-transform duration-150 hover:scale-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]';
|
||||
/** The tick on the picked swatch, in a white badge like the tick on a picked tag. */
|
||||
const TICK = 'grid h-4 w-4 place-items-center rounded-full bg-surface-card shadow-sm';
|
||||
const CUSTOM_TOGGLE =
|
||||
'flex items-center gap-2 rounded-[10px] px-1.5 py-1 font-semibold text-content-secondary transition-colors hover:bg-surface-hover hover:text-content';
|
||||
/** The custom colour's mark: every colour of the palette round the wheel. */
|
||||
const RAINBOW = `conic-gradient(${[...TAG_COLORS, TAG_COLORS[0]].join(', ')})`;
|
||||
|
||||
/**
|
||||
* The palette under a tag's colour dot: the trip's colours as swatches, and
|
||||
* under them a colour of one's own in TREK's own colour field. A swatch is kept
|
||||
* at once and closes the palette; the field keeps its colour when a drag ends
|
||||
* and stays open. Closes on a click outside or Escape, which stays here and does
|
||||
* not close the dialog around it.
|
||||
*/
|
||||
export function TagColorPopover({
|
||||
label,
|
||||
value,
|
||||
onPick,
|
||||
onPreview,
|
||||
onClose,
|
||||
className = PANEL,
|
||||
t,
|
||||
}: {
|
||||
/** What the palette colours, for its accessible name. */
|
||||
label: string;
|
||||
value: string | null;
|
||||
onPick: (color: string) => void;
|
||||
/** The colour while it is being dragged, for whoever can show it before it is kept. */
|
||||
onPreview?: (color: string) => void;
|
||||
onClose: () => void;
|
||||
/** The frame: a floating card by default; the phone lays it into the sheet instead. */
|
||||
className?: string;
|
||||
t: Translate;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement | null>(null);
|
||||
const current = value?.toLowerCase() ?? null;
|
||||
const isPreset = current !== null && TAG_COLORS.includes(current);
|
||||
// A colour of its own opens with the field showing it.
|
||||
const [custom, setCustom] = useState(current !== null && !isPreset);
|
||||
// The latest close handler, so the listener below is set up once.
|
||||
const close = useRef(onClose);
|
||||
useEffect(() => {
|
||||
close.current = onClose;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const outside = (e: PointerEvent) => {
|
||||
// The dot that opened it toggles it itself; a click there is not "outside".
|
||||
const host = ref.current?.parentElement;
|
||||
if (host && !host.contains(e.target as Node)) close.current();
|
||||
};
|
||||
document.addEventListener('pointerdown', outside);
|
||||
return () => document.removeEventListener('pointerdown', outside);
|
||||
}, []);
|
||||
|
||||
const pick = (color: string) => {
|
||||
onPick(color);
|
||||
onClose();
|
||||
};
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
e.stopPropagation();
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={ref} role="group" aria-label={label} className={className} onKeyDown={onKeyDown}>
|
||||
<div className="grid grid-cols-5 justify-items-center gap-y-2">
|
||||
{TAG_COLORS.map((color) => {
|
||||
const on = current === color;
|
||||
return (
|
||||
<button
|
||||
key={color}
|
||||
type="button"
|
||||
aria-label={color}
|
||||
aria-pressed={on}
|
||||
onClick={() => pick(color)}
|
||||
className={SWATCH}
|
||||
style={{ background: color }}
|
||||
>
|
||||
{on && (
|
||||
<span className={TICK}>
|
||||
<Check size={10} strokeWidth={3.4} aria-hidden="true" style={{ color }} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="h-px bg-[var(--border-faint)]" />
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={custom}
|
||||
onClick={() => setCustom(!custom)}
|
||||
className={CUSTOM_TOGGLE}
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="grid h-5 w-5 place-items-center rounded-full"
|
||||
style={{ background: RAINBOW }}
|
||||
>
|
||||
{current !== null && !isPreset && <span className="h-2 w-2 rounded-full bg-surface-card" />}
|
||||
</span>
|
||||
{t('places.tagColorCustom')}
|
||||
<ChevronDown
|
||||
size={14}
|
||||
strokeWidth={2.2}
|
||||
aria-hidden="true"
|
||||
className={`ms-auto transition-transform ${custom ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
{custom && (
|
||||
<TagColorField value={value ?? TAG_COLORS[0]} onPreview={(hex) => onPreview?.(hex)} onPick={onPick} t={t} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -357,7 +357,7 @@ describe('TransitSearchPanel', () => {
|
||||
await user.click(fromInput)
|
||||
const picks = (await screen.findAllByRole('button', { name: /Hotel Adlon|Stop \d|Hostel/ })).map(b => b.textContent)
|
||||
expect(picks[0]).toBe('Hotel Adlon')
|
||||
expect(picks.slice(1)).toEqual(['Stop 1', 'Stop 2', 'Stop 3', 'Stop 4', 'Stop 5', 'Stop 6', 'Stop 7', 'Stop 8'])
|
||||
expect(picks.slice(1)).toEqual([...places.map(p => p.name), 'Later Hostel'])
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Hotel Adlon' }))
|
||||
expect(fromInput).toHaveValue('Hotel Adlon')
|
||||
@@ -744,7 +744,7 @@ describe('quick picks from the bookings of the day (#1506)', () => {
|
||||
const places = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 100 + i, name: `P${i}`, lat: 52 + i / 100, lng: 13 }))
|
||||
const picks = buildQuickPicks(day, [day], places as any, [], dayBookingStops(day, [flight] as any))
|
||||
expect(picks.slice(0, 2).map(p => p.name)).toEqual(['FRA', 'BER Airport'])
|
||||
expect(picks).toHaveLength(2 + 8)
|
||||
expect(picks).toHaveLength(2 + places.length)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ import { transitApi } from '../../api/client'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { getDayBookendHotels } from '../../utils/dayOrder'
|
||||
import { getDayBookendHotels, isDayInAccommodationRange } from '../../utils/dayOrder'
|
||||
import { orderTransitStaysByDate } from './transitStayOrder'
|
||||
import type { Day, Place, Accommodation, Reservation } from '../../types'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { isCarrierTransport } from '../../utils/dayMerge'
|
||||
@@ -110,7 +111,11 @@ function fmtDuration(seconds: number, t: (k: string, p?: Record<string, string |
|
||||
|
||||
// ── quick picks ──────────────────────────────────────────────────────────────
|
||||
|
||||
const MAX_QUICK_PICKS = 8
|
||||
const MAX_OTHER_DAY_STAYS = 8
|
||||
|
||||
function pickedPlaceKey(p: PickedPlace): string {
|
||||
return JSON.stringify([p.name.trim().toLowerCase(), p.lat, p.lng])
|
||||
}
|
||||
|
||||
function stayPick(a: Accommodation): PickedPlace | null {
|
||||
return a.place_lat != null && a.place_lng != null && a.place_name ? { name: a.place_name, lat: a.place_lat, lng: a.place_lng } : null
|
||||
@@ -143,28 +148,30 @@ export function dayBookingStops(day: Pick<Day, 'id' | 'date'>, reservations: Res
|
||||
* starts in and the one it ends in come first and are never cut, since most
|
||||
* connections of a day begin or end there (#2538); the day's airports and
|
||||
* stations follow and are not cut either (#1506); then the day's own located
|
||||
* places and the trip's other stays, up to MAX_QUICK_PICKS.
|
||||
* places and remaining stays covering the day, without a limit. Only stays
|
||||
* outside the selected day's range are capped, nearest in nights first.
|
||||
*/
|
||||
export function buildQuickPicks(day: Day, days: Day[], places: Place[], accommodations: Accommodation[], bookingStops: PickedPlace[] = []): PickedPlace[] {
|
||||
const { morning, evening } = getDayBookendHotels(day, days, accommodations)
|
||||
const dayStays = [morning, evening].filter((a): a is Accommodation => a != null)
|
||||
const bookendStays = [morning, evening].filter((a): a is Accommodation => a != null)
|
||||
const dayStays = accommodations.filter(a => isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days))
|
||||
|
||||
const seen = new Set<string>()
|
||||
const unique = (p: PickedPlace | null): p is PickedPlace => {
|
||||
if (!p) return false
|
||||
const k = `${p.name}:${p.lat}`
|
||||
const k = pickedPlaceKey(p)
|
||||
if (seen.has(k)) return false
|
||||
seen.add(k)
|
||||
return true
|
||||
}
|
||||
|
||||
const stays = dayStays.map(stayPick).filter(unique)
|
||||
const stays = bookendStays.map(stayPick).filter(unique)
|
||||
const stations = bookingStops.filter(unique)
|
||||
const rest = [
|
||||
...places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)),
|
||||
...accommodations.filter(a => !dayStays.includes(a)).map(stayPick),
|
||||
].filter(unique)
|
||||
return [...stays, ...stations, ...rest.slice(0, MAX_QUICK_PICKS)]
|
||||
const dayPlaces = places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)).filter(unique)
|
||||
const remainingDayStays = dayStays.map(stayPick).filter(unique)
|
||||
const otherStays = orderTransitStaysByDate(day, days, accommodations.filter(a => !dayStays.includes(a)))
|
||||
.map(stayPick).filter(unique).slice(0, MAX_OTHER_DAY_STAYS)
|
||||
return [...stays, ...stations, ...dayPlaces, ...remainingDayStays, ...otherStays]
|
||||
}
|
||||
|
||||
// ── from/to stop picker ──────────────────────────────────────────────────────
|
||||
@@ -221,6 +228,8 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
const [results, setResults] = useState<TransitPlaceResult[]>([])
|
||||
const [open, setOpen] = useState(false)
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
// Ignore lookups superseded by another query, a saved pick, or leaving this day.
|
||||
const requestId = useRef(0)
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const fieldRef = useRef<HTMLDivElement>(null)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
@@ -235,21 +244,45 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
return () => document.removeEventListener('mousedown', close)
|
||||
}, [])
|
||||
|
||||
useEffect(() => () => { if (debounceRef.current) clearTimeout(debounceRef.current) }, [])
|
||||
useEffect(() => () => {
|
||||
requestId.current += 1
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
}, [])
|
||||
|
||||
const search = (q: string) => {
|
||||
const id = ++requestId.current
|
||||
setText(q)
|
||||
setResults([])
|
||||
onPick(null)
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
if (q.trim().length < 2) { setResults([]); return }
|
||||
if (q.trim().length < 2) return
|
||||
debounceRef.current = setTimeout(() => {
|
||||
transitApi.geocode(q, { lang: language, near: near || undefined })
|
||||
.then((d: { results: TransitPlaceResult[] }) => setResults(d.results || []))
|
||||
.catch(() => setResults([]))
|
||||
.then((d: { results: TransitPlaceResult[] }) => { if (id === requestId.current) setResults(d.results || []) })
|
||||
.catch(() => { if (id === requestId.current) setResults([]) })
|
||||
}, 300)
|
||||
}
|
||||
|
||||
const display = value ? value.name : text
|
||||
const query = text.trim().toLowerCase()
|
||||
const saved = quickPicks.filter(p => p.name.toLowerCase().includes(query))
|
||||
const seen = new Set(saved.map(pickedPlaceKey))
|
||||
const external = results.filter(p => {
|
||||
const key = pickedPlaceKey(p)
|
||||
if (seen.has(key)) return false
|
||||
seen.add(key)
|
||||
return true
|
||||
})
|
||||
const suggestions: (PickedPlace & { area?: string | null })[] = value ? [] : [...saved, ...external]
|
||||
|
||||
const pick = (p: PickedPlace) => {
|
||||
requestId.current += 1
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
onPick({ name: p.name, lat: p.lat, lng: p.lng })
|
||||
setText('')
|
||||
setResults([])
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={rootRef} style={{ position: 'relative', flex: 1, minWidth: 0 }}>
|
||||
@@ -267,34 +300,23 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
style={{ border: 0, background: 'none', outline: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', width: '100%', fontFamily: 'inherit' }}
|
||||
/>
|
||||
</div>
|
||||
{open && listPos && (results.length > 0 || (!value && text.trim().length < 2 && quickPicks.length > 0)) && createPortal(
|
||||
{open && listPos && suggestions.length > 0 && createPortal(
|
||||
// On the page rather than inside the dialog, so a dialog that scrolls or clips
|
||||
// its content cannot cut the list off before anything is typed.
|
||||
<div ref={listRef} className="bg-surface-card border border-edge z-[var(--z-toast)]" style={{ position: 'fixed', left: listPos.left, width: listPos.width, ...(listPos.above ? { bottom: listPos.bottom } : { top: listPos.top }), borderRadius: 10, boxShadow: 'var(--shadow-dropdown)', overflow: 'hidden', maxHeight: listPos.maxHeight, overflowY: 'auto' }}>
|
||||
{results.length > 0
|
||||
? results.map((r, i) => (
|
||||
<button type="button" key={i} onClick={() => { onPick({ name: r.name, lat: r.lat, lng: r.lng }); setText(''); setResults([]); setOpen(false) }}
|
||||
className="text-content"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
|
||||
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
|
||||
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
|
||||
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.name}
|
||||
{r.area && <span className="ms-1.5 text-content-faint">{r.area}</span>}
|
||||
</span>
|
||||
</button>
|
||||
))
|
||||
: quickPicks.map((p, i) => (
|
||||
<button type="button" key={i} onClick={() => { onPick(p); setText(''); setOpen(false) }}
|
||||
className="text-content"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
|
||||
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
|
||||
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
|
||||
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</span>
|
||||
</button>
|
||||
))}
|
||||
{suggestions.map(r => (
|
||||
<button type="button" key={pickedPlaceKey(r)} onClick={() => pick(r)}
|
||||
className="text-content"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
|
||||
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
|
||||
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
|
||||
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.name}
|
||||
{r.area && <span className="ms-1.5 text-content-faint">{r.area}</span>}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,684 @@
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildAssignment, buildDay, buildPlace, buildTrip, buildUser } from '../../../tests/helpers/factories';
|
||||
import { buildPlanner } from '../../../tests/helpers/mobileTrip';
|
||||
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import MTransportFormSheet from '../../mobile/screens/trip/sheets/MTransportFormSheet';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Accommodation, AssignmentsMap, Day, Place } from '../../types';
|
||||
import type { TransitPrefill } from './transitLeg';
|
||||
import { TransportModal } from './TransportModal';
|
||||
|
||||
// Keep the real day selectors, wrappers and shared stop picker. Only the external
|
||||
// geocoder is controlled: a saved private place need not exist in that service.
|
||||
const { geocode, plan } = vi.hoisted(() => ({ geocode: vi.fn(), plan: vi.fn() }));
|
||||
vi.mock('../../api/client', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../api/client')>()),
|
||||
transitApi: { geocode, plan },
|
||||
}));
|
||||
|
||||
type Surface = 'desktop' | 'phone';
|
||||
interface Fixture {
|
||||
days: Day[];
|
||||
places: Place[];
|
||||
assignments: AssignmentsMap;
|
||||
accommodations: Accommodation[];
|
||||
transitPrefill?: TransitPrefill;
|
||||
selectedDayId?: number;
|
||||
}
|
||||
|
||||
function fixture(): Fixture {
|
||||
const days = [
|
||||
buildDay({ id: 101, trip_id: 1, day_number: 1, date: '2027-06-01', title: 'First day' }),
|
||||
buildDay({ id: 205, trip_id: 1, day_number: 2, date: '2027-06-02', title: 'Second day' }),
|
||||
buildDay({ id: 309, trip_id: 1, day_number: 3, date: '2027-06-03', title: 'Empty day' }),
|
||||
];
|
||||
const places = ['First private stop', 'Second private stop', 'Shared private stop'].map((name, i) =>
|
||||
buildPlace({ id: 11 + i, trip_id: 1, name, lat: 52.5 + i / 100, lng: 13.4 })
|
||||
);
|
||||
const visit = (dayId: number, p: Place, order: number) =>
|
||||
buildAssignment({ day_id: dayId, place_id: p.id, place: p, order_index: order });
|
||||
return {
|
||||
days,
|
||||
places,
|
||||
assignments: {
|
||||
'101': [visit(101, places[0], 0), visit(101, places[2], 1)],
|
||||
'205': [visit(205, places[1], 0), visit(205, places[2], 1)],
|
||||
'309': [],
|
||||
},
|
||||
accommodations: [],
|
||||
};
|
||||
}
|
||||
|
||||
function buildStay(id: number, name: string, start: number, end: number): Accommodation {
|
||||
return {
|
||||
id,
|
||||
trip_id: 1,
|
||||
place_id: 1000 + id,
|
||||
start_day_id: start,
|
||||
end_day_id: end,
|
||||
place_name: name,
|
||||
place_lat: 52 + id / 1000,
|
||||
place_lng: 13,
|
||||
} as Accommodation;
|
||||
}
|
||||
|
||||
function longTripFixture(): Fixture {
|
||||
const days = Array.from({ length: 30 }, (_, i) =>
|
||||
buildDay({
|
||||
id: 5000 - i * 97,
|
||||
trip_id: 1,
|
||||
day_number: i + 1,
|
||||
date: new Date(Date.UTC(2027, 2, i + 1)).toISOString().slice(0, 10),
|
||||
title: `Day ${i + 1}`,
|
||||
})
|
||||
);
|
||||
days[28] = { ...days[28], date: null };
|
||||
const stay = (id: number, name: string, start: number, end: number) =>
|
||||
buildStay(id, name, days[start - 1].id, days[end - 1].id);
|
||||
const nearby = Array.from({ length: 4 }, (_, i) => [
|
||||
stay(10 + i * 2, `Nearby before ${i + 1}`, 18 - i, 20 - i),
|
||||
stay(11 + i * 2, `Nearby after ${i + 1}`, 22 + i, 24 + i),
|
||||
]).flat();
|
||||
return {
|
||||
days,
|
||||
places: [],
|
||||
assignments: {},
|
||||
selectedDayId: days[20].id,
|
||||
accommodations: [
|
||||
stay(1, 'First-week hotel created first', 1, 7),
|
||||
stay(2, 'Undated hotel', 29, 30),
|
||||
...nearby.slice().reverse(),
|
||||
{ ...nearby[0], id: 99 },
|
||||
stay(100, 'Morning hotel', 20, 21),
|
||||
stay(101, 'Evening hotel', 21, 22),
|
||||
...Array.from({ length: 10 }, (_, i) => stay(200 + i, `Current stay ${i + 1}`, 19, 23)),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function Harness({ surface, data }: { surface: Surface; data: Fixture }) {
|
||||
const { t } = useTranslation();
|
||||
if (surface === 'phone') {
|
||||
const planner = buildPlanner({
|
||||
t,
|
||||
trip: buildTrip({ id: 1 }),
|
||||
days: data.days,
|
||||
places: data.places,
|
||||
assignments: data.assignments,
|
||||
storedAssignments: data.assignments,
|
||||
tripAccommodations: data.accommodations,
|
||||
showTransportModal: true,
|
||||
transportModalDayId: data.selectedDayId ?? 101,
|
||||
transportModalAutomated: true,
|
||||
transitPrefill: data.transitPrefill ?? null,
|
||||
});
|
||||
return <MTransportFormSheet planner={planner} onOpenExpense={vi.fn()} />;
|
||||
}
|
||||
return (
|
||||
<TransportModal
|
||||
isOpen
|
||||
onClose={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
reservation={null}
|
||||
days={data.days}
|
||||
selectedDayId={data.selectedDayId ?? 101}
|
||||
initialAutomated
|
||||
places={data.places}
|
||||
assignments={data.assignments}
|
||||
accommodations={data.accommodations}
|
||||
transitPrefill={data.transitPrefill}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const inputs = () => screen.getAllByPlaceholderText('Search stop or station…');
|
||||
async function switchDay(user: ReturnType<typeof userEvent.setup>, current: string, next: string) {
|
||||
await user.click(screen.getByText(current));
|
||||
await user.click(screen.getByRole('button', { name: new RegExp(`^${next}`) }));
|
||||
}
|
||||
const pickNames = () => screen.queryAllByRole('button', { name: /private stop/ }).map((b) => b.textContent);
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
geocode.mockReset().mockResolvedValue({ results: [] });
|
||||
plan.mockReset();
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1 }), reservations: [] });
|
||||
});
|
||||
|
||||
describe.each<Surface>(['desktop', 'phone'])('Automated transport day selection: %s', (surface) => {
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, value: surface === 'phone' ? 390 : 1440 });
|
||||
fireEvent(window, new Event('resize'));
|
||||
});
|
||||
|
||||
it('scopes both pickers by day id and keeps a shared place when switching back and forth', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[1]);
|
||||
expect(pickNames()).toEqual(['Second private stop', 'Shared private stop']);
|
||||
await switchDay(user, 'Second day', 'First day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
|
||||
});
|
||||
|
||||
it('keeps all nine eligible day places available in the dropdown', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const stops = Array.from({ length: 9 }, (_, i) => buildPlace({ id: 50 + i, name: `Day stop ${i + 1}` }));
|
||||
data.places.push(...stops);
|
||||
data.assignments['101'] = stops.map((p, i) =>
|
||||
buildAssignment({ day_id: 101, place_id: p.id, place: p, order_index: i })
|
||||
);
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(screen.queryAllByRole('button', { name: /^Day stop/ }).map((b) => b.textContent)).toEqual(
|
||||
stops.map((p) => p.name)
|
||||
);
|
||||
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('finds an assigned private place when the geocoder has no result', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
await user.click(inputs()[0]);
|
||||
await user.type(inputs()[0], 'First private');
|
||||
await waitFor(() => expect(geocode).toHaveBeenCalled());
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(screen.queryByRole('button', { name: 'First private stop' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('ranks matching saved places before external matches and deduplicates by name and both coordinates', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const saved = data.places[0];
|
||||
const other = { name: 'External private stop', lat: 52.8, lng: 13.8, area: 'Berlin' };
|
||||
geocode.mockResolvedValue({
|
||||
results: [
|
||||
other,
|
||||
{ name: saved.name.toUpperCase(), lat: saved.lat, lng: saved.lng, area: 'Duplicate' },
|
||||
{ ...other },
|
||||
{ name: saved.name, lat: saved.lat, lng: 13.9, area: 'Other longitude' },
|
||||
],
|
||||
});
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.type(inputs()[0], 'private');
|
||||
await screen.findByRole('button', { name: /External private stop/ });
|
||||
const rows = screen.getAllByRole('button', { name: /private stop/i });
|
||||
expect(rows.map((row) => row.textContent)).toEqual([
|
||||
'First private stop',
|
||||
'Shared private stop',
|
||||
'External private stopBerlin',
|
||||
'First private stopOther longitude',
|
||||
]);
|
||||
expect(geocode).toHaveBeenCalledTimes(1);
|
||||
await user.click(rows[0]);
|
||||
expect(inputs()[0]).toHaveValue(saved.name);
|
||||
});
|
||||
|
||||
it('limits only other-day stays, keeping current hotels, terminals and every selected-day place first', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const stops = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 50 + i, name: `Day stop ${i + 1}` }));
|
||||
// A same-name stop at a different longitude must not be dropped as a duplicate.
|
||||
stops.push(buildPlace({ id: 62, name: stops[0].name, lat: stops[0].lat, lng: 10 }));
|
||||
data.places.push(...stops);
|
||||
data.assignments['101'] = stops.map((p, i) =>
|
||||
buildAssignment({ day_id: 101, place_id: p.id, place: p, order_index: i })
|
||||
);
|
||||
data.accommodations = Array.from(
|
||||
{ length: 12 },
|
||||
(_, i) =>
|
||||
({
|
||||
id: 70 + i,
|
||||
trip_id: 1,
|
||||
place_id: 70 + i,
|
||||
start_day_id: i === 0 ? 101 : 205,
|
||||
end_day_id: i === 0 ? 101 : 205,
|
||||
place_name: i === 0 ? 'Current hotel' : `Other hotel ${i}`,
|
||||
place_lat: 52 + i / 100,
|
||||
place_lng: 13,
|
||||
}) as Accommodation
|
||||
);
|
||||
// Duplicate stays must not consume another slot of the other-day allowance.
|
||||
data.accommodations.splice(2, 0, { ...data.accommodations[1], id: 90 });
|
||||
seedStore(useTripStore, {
|
||||
reservations: [
|
||||
{
|
||||
id: 81,
|
||||
trip_id: 1,
|
||||
type: 'train',
|
||||
day_id: 101,
|
||||
end_day_id: 101,
|
||||
endpoints: [{ role: 'from', name: 'Current terminal', lat: 52, lng: 13, local_date: '2027-06-01' }],
|
||||
},
|
||||
] as ReturnType<typeof useTripStore.getState>['reservations'],
|
||||
});
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
for (const input of inputs()) {
|
||||
await user.click(input);
|
||||
const rows = screen.getAllByRole('button', { name: /Current hotel|Current terminal|Day stop|Other hotel/ });
|
||||
expect(rows.map((row) => row.textContent)).toEqual([
|
||||
'Current hotel',
|
||||
'Current terminal',
|
||||
...stops.map((p) => p.name),
|
||||
...Array.from({ length: 8 }, (_, i) => `Other hotel ${i + 1}`),
|
||||
]);
|
||||
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps more than eight current-day hotels selectable and searchable despite earlier other-day stays', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const current = Array.from({ length: 12 }, (_, i) => buildStay(200 + i, `Current day hotel ${i + 1}`, 101, 101));
|
||||
const other = Array.from({ length: 9 }, (_, i) => buildStay(100 + i, `Other day hotel ${i + 1}`, 205, 205));
|
||||
data.accommodations = [
|
||||
...other,
|
||||
...current,
|
||||
{ ...current[8], id: 999 },
|
||||
{ ...buildStay(300, 'Unlocated current hotel', 101, 101), place_lat: null },
|
||||
];
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
for (const input of inputs()) {
|
||||
await user.click(input);
|
||||
expect(screen.getAllByRole('button', { name: /^Current day hotel/ }).map((b) => b.textContent)).toEqual(
|
||||
current.map((a) => a.place_name)
|
||||
);
|
||||
expect(screen.getAllByRole('button', { name: /^Other day hotel/ }).map((b) => b.textContent)).toEqual(
|
||||
other.slice(0, 8).map((a) => a.place_name)
|
||||
);
|
||||
expect(screen.queryByRole('button', { name: 'Unlocated current hotel' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'First private stop' })).toBeInTheDocument();
|
||||
}
|
||||
await user.type(inputs()[1], 'current day hotel 12');
|
||||
await user.click(screen.getByRole('button', { name: 'Current day hotel 12' }));
|
||||
expect(inputs()[1]).toHaveValue('Current day hotel 12');
|
||||
});
|
||||
|
||||
it('offers Hotel 09 on Day 3 for the manual-review booking pattern without using mirrored day places', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const a = buildStay(1, 'Hotel A — first night', 101, 205);
|
||||
const b = buildStay(2, 'Hotel B — second night', 205, 309);
|
||||
const sameDay = Array.from({ length: 9 }, (_, i) =>
|
||||
buildStay(3 + i, `Other night hotel ${String(i + 1).padStart(2, '0')}`, 309, 309)
|
||||
);
|
||||
data.accommodations = [a, b, ...sameDay];
|
||||
// Days hides accommodation-owned mirror assignments: hotels must come from the stays themselves.
|
||||
data.assignments['309'] = [];
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await switchDay(user, 'First day', 'Empty day');
|
||||
for (const input of inputs()) {
|
||||
await user.click(input);
|
||||
expect(
|
||||
screen.getAllByRole('button', { name: /Hotel A|Hotel B|Other night hotel/ }).map((row) => row.textContent)
|
||||
).toEqual([b.place_name, ...sameDay.map((stay) => stay.place_name), a.place_name]);
|
||||
}
|
||||
await user.click(screen.getByRole('button', { name: 'Other night hotel 09' }));
|
||||
expect(inputs()[1]).toHaveValue('Other night hotel 09');
|
||||
});
|
||||
|
||||
it('keeps multi-night stays and checkout-day stays uncapped, with bookends before the other current stays', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const other = Array.from({ length: 9 }, (_, i) => buildStay(100 + i, `Future hotel ${i + 1}`, 309, 309));
|
||||
const spanning = Array.from({ length: 10 }, (_, i) => buildStay(200 + i, `Multi-night hotel ${i + 1}`, 101, 309));
|
||||
const checkout = buildStay(300, 'Checks out today', 101, 205);
|
||||
const checkin = buildStay(301, 'Checks in today', 205, 309);
|
||||
data.accommodations = [...other, ...spanning, checkout, checkin];
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(
|
||||
screen
|
||||
.getAllByRole('button', { name: /Multi-night hotel|Checks (in|out) today|Future hotel/ })
|
||||
.map((row) => row.textContent)
|
||||
).toEqual([
|
||||
spanning[0].place_name,
|
||||
checkin.place_name,
|
||||
...spanning.slice(1).map((stay) => stay.place_name),
|
||||
checkout.place_name,
|
||||
...other.slice(0, 8).map((stay) => stay.place_name),
|
||||
]);
|
||||
expect(screen.queryByRole('button', { name: 'Future hotel 9' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not let a first-week hotel take a Day 21 slot from eight closer stays on a 30-day trip', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Harness surface={surface} data={longTripFixture()} />);
|
||||
for (const input of inputs()) {
|
||||
await user.click(input);
|
||||
expect(screen.queryByRole('button', { name: 'First-week hotel created first' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Undated hotel' })).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen
|
||||
.getAllByRole('button', { name: /Morning hotel|Evening hotel|Current stay|Nearby/ })
|
||||
.map((row) => row.textContent)
|
||||
).toEqual([
|
||||
'Morning hotel',
|
||||
'Evening hotel',
|
||||
...Array.from({ length: 10 }, (_, i) => `Current stay ${i + 1}`),
|
||||
...Array.from({ length: 4 }, (_, i) => [`Nearby before ${i + 1}`, `Nearby after ${i + 1}`]).flat(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it('puts undated stays last and orders identical dated intervals by stay id independently of input order', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = longTripFixture();
|
||||
const dated = data.accommodations.find((stay) => stay.place_name === 'Nearby after 1');
|
||||
if (!dated) throw new Error('Missing dated fixture');
|
||||
const undated = data.accommodations.find((stay) => stay.place_name === 'Undated hotel');
|
||||
if (!undated) throw new Error('Missing undated fixture');
|
||||
data.accommodations = [
|
||||
undated,
|
||||
{ ...dated, id: 90, place_name: 'Same dates higher id', place_lng: 14 },
|
||||
{ ...dated, id: 80, place_name: 'Same dates lower id', place_lng: 15 },
|
||||
];
|
||||
const view = render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
const names = () =>
|
||||
screen.getAllByRole('button', { name: /Same dates|Undated hotel/ }).map((row) => row.textContent);
|
||||
expect(names()).toEqual(['Same dates lower id', 'Same dates higher id', 'Undated hotel']);
|
||||
view.rerender(
|
||||
<Harness surface={surface} data={{ ...data, accommodations: data.accommodations.slice().reverse() }} />
|
||||
);
|
||||
expect(names()).toEqual(['Same dates lower id', 'Same dates higher id', 'Undated hotel']);
|
||||
});
|
||||
|
||||
it('refreshes an open dropdown after places are added, removed and reordered', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const view = render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
|
||||
const added = buildPlace({ id: 99, name: 'Added private stop' });
|
||||
const next = {
|
||||
...data,
|
||||
places: [...data.places, added],
|
||||
assignments: {
|
||||
...data.assignments,
|
||||
'101': [
|
||||
{ ...data.assignments['101'][1], order_index: 2 },
|
||||
buildAssignment({ day_id: 101, place_id: added.id, place: added, order_index: 0 }),
|
||||
],
|
||||
},
|
||||
};
|
||||
view.rerender(<Harness surface={surface} data={next} />);
|
||||
expect(pickNames()).toEqual(['Added private stop', 'Shared private stop']);
|
||||
});
|
||||
|
||||
it('keeps place membership tied to ids when days and their dates are reordered', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const view = render(<Harness surface={surface} data={data} />);
|
||||
const reordered = {
|
||||
...data,
|
||||
days: [
|
||||
{ ...data.days[1], day_number: 1, date: data.days[0].date },
|
||||
{ ...data.days[0], day_number: 2, date: data.days[1].date },
|
||||
data.days[2],
|
||||
],
|
||||
};
|
||||
view.rerender(<Harness surface={surface} data={reordered} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual(['Second private stop', 'Shared private stop']);
|
||||
});
|
||||
|
||||
it('does not retain endpoints from an unrelated day after selecting from and to', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
// Make the first day's two endpoints exclusive to that day.
|
||||
data.assignments['205'] = [data.assignments['205'][0]];
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
await user.click(screen.getByRole('button', { name: 'First private stop' }));
|
||||
await user.click(inputs()[1]);
|
||||
await user.click(screen.getByRole('button', { name: 'Shared private stop' }));
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
|
||||
});
|
||||
|
||||
it('clears search state when changing days so the next day offers its own places', async () => {
|
||||
const user = userEvent.setup();
|
||||
geocode.mockResolvedValue({ results: [{ name: 'Old external station', lat: 52, lng: 13, area: null }] });
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
await user.type(inputs()[0], 'Old station');
|
||||
await screen.findByRole('button', { name: 'Old external station' });
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(screen.queryByRole('button', { name: 'Old external station' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Second private stop' })).toBeInTheDocument();
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
|
||||
});
|
||||
|
||||
it('scopes day-plan endpoint, time and walk prefills to the opening day', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
data.transitPrefill = {
|
||||
from: { name: 'Walk end', lat: 52.5, lng: 13.4 },
|
||||
to: { name: 'Next walk start', lat: 52.6, lng: 13.5 },
|
||||
time: '12:15',
|
||||
walk: {
|
||||
dayId: 101,
|
||||
fromWalk: 'Old town',
|
||||
toWalk: 'Harbour',
|
||||
ends: '12:15',
|
||||
endsNextDay: false,
|
||||
endsAtLeast: false,
|
||||
nextStarts: '13:00',
|
||||
},
|
||||
};
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['Walk end', 'Next walk start']);
|
||||
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town');
|
||||
expect(screen.getByDisplayValue('12:15')).toBeInTheDocument();
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
|
||||
expect(screen.queryByTestId('transit-walk-end')).not.toBeInTheDocument();
|
||||
expect(screen.queryByDisplayValue('12:15')).not.toBeInTheDocument();
|
||||
await switchDay(user, 'Second day', 'First day');
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['Walk end', 'Next walk start']);
|
||||
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town');
|
||||
});
|
||||
|
||||
it('drops old itineraries when changing the day', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
const stop = (name: string, time: string) => ({
|
||||
name,
|
||||
lat: 52.5,
|
||||
lng: 13.4,
|
||||
time,
|
||||
scheduledTime: null,
|
||||
track: null,
|
||||
});
|
||||
plan.mockResolvedValue({
|
||||
itineraries: [
|
||||
{
|
||||
startTime: '2027-06-01T07:00:00Z',
|
||||
endTime: '2027-06-01T07:30:00Z',
|
||||
duration: 1800,
|
||||
transfers: 0,
|
||||
walkSeconds: 0,
|
||||
legs: [
|
||||
{
|
||||
mode: 'SUBWAY',
|
||||
from: stop('A', '2027-06-01T07:00:00Z'),
|
||||
to: stop('B', '2027-06-01T07:30:00Z'),
|
||||
duration: 1800,
|
||||
distance: null,
|
||||
headsign: null,
|
||||
line: 'U88',
|
||||
lineColor: null,
|
||||
lineTextColor: null,
|
||||
agency: null,
|
||||
intermediateStops: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
await user.click(screen.getByRole('button', { name: 'First private stop' }));
|
||||
await user.click(inputs()[1]);
|
||||
await user.click(screen.getByRole('button', { name: 'Shared private stop' }));
|
||||
await user.click(screen.getByRole('button', { name: /^Search$/ }));
|
||||
await screen.findByText('U88');
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
expect(screen.queryByText('U88')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Add to day' })).not.toBeInTheDocument();
|
||||
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
|
||||
});
|
||||
|
||||
it('ignores an old geocoder response after the day changes', async () => {
|
||||
const user = userEvent.setup();
|
||||
let finish: (value: { results: { name: string; lat: number; lng: number; area: null }[] }) => void = () => {
|
||||
throw new Error('lookup not started');
|
||||
};
|
||||
geocode.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
})
|
||||
);
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
await user.type(inputs()[0], 'Old station');
|
||||
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[0]);
|
||||
await act(async () => {
|
||||
finish({ results: [{ name: 'Late old station', lat: 52, lng: 13, area: null }] });
|
||||
});
|
||||
expect(screen.queryByRole('button', { name: 'Late old station' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Second private stop' })).toBeInTheDocument();
|
||||
expect(inputs()[0]).toHaveValue('');
|
||||
});
|
||||
|
||||
it('keeps the newest search results when an older lookup answers last', async () => {
|
||||
type Answer = { results: { name: string; lat: number; lng: number; area: null }[] };
|
||||
const pending: ((value: Answer) => void)[] = [];
|
||||
geocode.mockImplementation(() => new Promise<Answer>((resolve) => pending.push(resolve)));
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
fireEvent.focus(inputs()[0]);
|
||||
fireEvent.change(inputs()[0], { target: { value: 'Old' } });
|
||||
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
|
||||
fireEvent.change(inputs()[0], { target: { value: 'New' } });
|
||||
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(2));
|
||||
await act(async () => {
|
||||
pending[1]({ results: [{ name: 'New station', lat: 52.5, lng: 13.4, area: null }] });
|
||||
});
|
||||
await act(async () => {
|
||||
pending[0]({ results: [{ name: 'Old station', lat: 52.6, lng: 13.5, area: null }] });
|
||||
});
|
||||
expect(screen.getByRole('button', { name: 'New station' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Old station' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('ignores a superseded geocoder response after a saved place is picked', async () => {
|
||||
const user = userEvent.setup();
|
||||
let finish: (value: { results: { name: string; lat: number; lng: number; area: null }[] }) => void = () => {
|
||||
throw new Error('lookup not started');
|
||||
};
|
||||
geocode.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
})
|
||||
);
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
fireEvent.change(inputs()[0], { target: { value: 'Old' } });
|
||||
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
|
||||
fireEvent.change(inputs()[0], { target: { value: 'First private' } });
|
||||
fireEvent.focus(inputs()[0]);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'First private stop' }));
|
||||
await act(async () => {
|
||||
finish({ results: [{ name: 'Superseded station', lat: 52, lng: 13, area: null }] });
|
||||
});
|
||||
await user.clear(inputs()[0]);
|
||||
expect(screen.queryByRole('button', { name: 'Superseded station' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'First private stop' })).toBeInTheDocument();
|
||||
expect(geocode).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('offers no unrelated regular places on an empty day', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<Harness surface={surface} data={fixture()} />);
|
||||
await switchDay(user, 'First day', 'Empty day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(pickNames()).toEqual([]);
|
||||
});
|
||||
|
||||
it('offers the active stay and other trip stays intentionally, even on a booking-only day', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
data.assignments['101'] = [];
|
||||
const stay = (id: number, name: string, dayId: number): Accommodation =>
|
||||
({
|
||||
id,
|
||||
trip_id: 1,
|
||||
place_id: id,
|
||||
start_day_id: dayId,
|
||||
end_day_id: dayId,
|
||||
place_name: name,
|
||||
place_lat: 52 + id / 100,
|
||||
place_lng: 13,
|
||||
}) as Accommodation;
|
||||
data.accommodations = [stay(70, 'Current hotel', 101), stay(71, 'Later hotel', 205)];
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(screen.getByRole('button', { name: 'Current hotel' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Later hotel' })).toBeInTheDocument();
|
||||
expect(pickNames()).toEqual([]);
|
||||
});
|
||||
|
||||
it('offers only the selected day transport terminals on a transport-only day', async () => {
|
||||
const user = userEvent.setup();
|
||||
const data = fixture();
|
||||
data.assignments['101'] = [];
|
||||
const endpoint = (role: 'from' | 'to', name: string, date: string) => ({
|
||||
role,
|
||||
name,
|
||||
lat: 52,
|
||||
lng: 13,
|
||||
local_date: date,
|
||||
});
|
||||
seedStore(useTripStore, {
|
||||
reservations: [
|
||||
{
|
||||
id: 81,
|
||||
trip_id: 1,
|
||||
type: 'train',
|
||||
day_id: 101,
|
||||
end_day_id: 205,
|
||||
endpoints: [
|
||||
endpoint('from', 'First terminal', '2027-06-01'),
|
||||
endpoint('to', 'Second terminal', '2027-06-02'),
|
||||
],
|
||||
},
|
||||
] as ReturnType<typeof useTripStore.getState>['reservations'],
|
||||
});
|
||||
render(<Harness surface={surface} data={data} />);
|
||||
await user.click(inputs()[0]);
|
||||
expect(screen.getByRole('button', { name: 'First terminal' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Second terminal' })).not.toBeInTheDocument();
|
||||
await switchDay(user, 'First day', 'Second day');
|
||||
await user.click(inputs()[0]);
|
||||
expect(screen.getByRole('button', { name: 'Second terminal' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'First terminal' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@ import { toLocationPicks } from './locationPicks'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
|
||||
import type { Day, Place, Accommodation, Reservation, TripFile, AssignmentsMap } from '../../types'
|
||||
import { BookingNotesFilesCosts } from './BookingNotesFilesCosts'
|
||||
import { TravelerPicker } from './TravelerPicker'
|
||||
@@ -20,6 +20,7 @@ import type { TripMember } from '../Budget/BudgetPanelMemberChips'
|
||||
import type { BookingExpenseRequest } from './BookingCostsSection.types'
|
||||
import type { BookingReviewDraft } from './parsedItemToDraft'
|
||||
import TransitSearchPanel from './TransitSearchPanel'
|
||||
import { getTransitDayPlaces } from './transitDayPlaces'
|
||||
import type { TransitPrefill } from './transitLeg'
|
||||
import { BookingDialogHeader, StatusPill } from './bookings/BookingDialogShell'
|
||||
import { DialogShell, DialogSection, DialogFooter, FooterSpacer, DialogButton, DeleteButton } from '../shared/DialogShell'
|
||||
@@ -82,10 +83,10 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
||||
const toast = useToast()
|
||||
// The trip's places, offered by every location field of the manual tab (#2468).
|
||||
const locationPicks = useMemo(() => toLocationPicks(places), [places])
|
||||
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const budgetItems = useTripStore(s => s.budgetItems)
|
||||
const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)
|
||||
const { id: tripId } = useParams<{ id: string }>()
|
||||
const isBudgetEnabled = useTripAddonEnabled(Number(tripId), 'budget')
|
||||
// Set right before submitting when the user clicked "create/edit expense", so
|
||||
// the post-save handler knows to open the Costs editor for the saved booking.
|
||||
const expense = useBookingExpenseIntent(() => handleSubmit(), {
|
||||
@@ -287,22 +288,20 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
||||
const transitSearch = () => {
|
||||
const transitDay = days.find(d => d.id === Number(form.start_day_id))
|
||||
if (!transitDay) return <p className="m-0 text-content-faint" style={fs(13, 'body')}>{t('transit.pickDay')}</p>
|
||||
// Quick picks offer the chosen day's itinerary, not the whole trip (#1460).
|
||||
const dayPlaces = (assignments[String(transitDay.id)] || [])
|
||||
.slice().sort((a, b) => a.order_index - b.order_index)
|
||||
.map(a => places.find(p => p.id === a.place_id))
|
||||
.filter((p): p is Place => p != null)
|
||||
const dayPlaces = getTransitDayPlaces(transitDay.id, assignments, places)
|
||||
const dayPrefill = transitDay.id === selectedDayId ? transitPrefill : null
|
||||
return (
|
||||
<TransitSearchPanel
|
||||
key={transitDay.id}
|
||||
day={transitDay}
|
||||
days={days}
|
||||
places={dayPlaces}
|
||||
accommodations={accommodations}
|
||||
onAdd={(payload) => onSave(payload as Record<string, any> & { title: string })}
|
||||
initialFrom={transitPrefill?.from ?? null}
|
||||
initialTo={transitPrefill?.to ?? null}
|
||||
initialTime={transitPrefill?.time ?? null}
|
||||
walk={transitPrefill?.walk ?? null}
|
||||
initialFrom={dayPrefill?.from ?? null}
|
||||
initialTo={dayPrefill?.to ?? null}
|
||||
initialTime={dayPrefill?.time ?? null}
|
||||
walk={dayPrefill?.walk ?? null}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -118,6 +118,19 @@ describe('BookingDetailDialog', () => {
|
||||
expect(screen.getByText('#SEG2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-015: a flight with a stop shows the seat booked on its second leg, once, under that leg', () => {
|
||||
const r = buildReservation({
|
||||
title: 'MXP to JFK', type: 'flight',
|
||||
metadata: JSON.stringify({ class: 'Economy', legs: [{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }] }),
|
||||
});
|
||||
renderDetail(r);
|
||||
const dialog = screen.getByRole('dialog', { name: 'MXP to JFK' });
|
||||
expect(within(dialog).getByText('14C')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('Seat IST → JFK')).toBeInTheDocument();
|
||||
// The tile stands for it; the field grid does not repeat it.
|
||||
expect(within(dialog).queryByText('14C, Economy')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKDETAIL-006: place, accommodation, linked stop, link, travelers and notes', () => {
|
||||
const place = buildPlace({ name: 'Kinkaku-ji', place_time: '10:00' });
|
||||
const a = buildAssignment({ id: 4401, day_id: 1302, place });
|
||||
|
||||
@@ -27,7 +27,7 @@ import { BookingDialogHeader, StatusPill, TypePill } from './BookingDialogShell'
|
||||
import { DeleteButton, DialogButton, DialogFooter, DialogSection as Section, DialogShell, FooterSpacer, PILL } from '../../shared/DialogShell'
|
||||
import FlightLiveCard from '../flightLive/FlightLiveCard'
|
||||
import { useFlightLiveCardLegs } from '../flightLive/useFlightLiveCard'
|
||||
import { getFlightLegs } from '../../../utils/flightLegs'
|
||||
import { bookingSeats, getFlightLegs, seatLabel } from '../../../utils/flightLegs'
|
||||
|
||||
export interface BookingDetailDialogProps {
|
||||
r: Reservation
|
||||
@@ -84,6 +84,7 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
|
||||
const subParts = [meta.airline, meta.flight_number, meta.train_number, facts.endpoints.length >= 2 ? facts.endpoints.map(e => e.code || e.name).join(' → ') : null].filter(Boolean)
|
||||
const sub = subParts.length ? subParts.join(' ') : null
|
||||
|
||||
const seats = bookingSeats(r)
|
||||
const stats: { value: string; label: string }[] = []
|
||||
if (facts.isHotel) {
|
||||
stats.push(...stayStats(facts, meta, t, locale))
|
||||
@@ -100,7 +101,8 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
|
||||
// Under a minute of walking is not worth a tile.
|
||||
if (transit && transit.walk > 59) stats.push({ value: t('transit.min', { count: Math.round(transit.walk / 60) }), label: t('transit.walkLabel') })
|
||||
if (meta.platform) stats.push({ value: meta.platform, label: t('reservations.meta.platform') })
|
||||
if (meta.seat) stats.push({ value: meta.seat, label: t('reservations.meta.seat') })
|
||||
// Each leg's seat under its route on a booking with a stop, not just the first leg's.
|
||||
for (const s of seats) stats.push({ value: s.seat, label: seatLabel(t('reservations.meta.seat'), s.route) })
|
||||
}
|
||||
// Cells already shown as a stat stay out of the field grid below.
|
||||
const shownAsStat = new Set([t('reservations.meta.platform'), t('reservations.meta.seat'), t('reservations.meta.checkIn'), t('reservations.meta.checkOut')])
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { Reservation } from '../../../types'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { BlurredCode } from '../../shared/BookingCode'
|
||||
import { formatMoney } from '../../../utils/formatters'
|
||||
import { bookingSeats } from '../../../utils/flightLegs'
|
||||
import { TransitLegChips } from '../transitDisplay'
|
||||
import { displayTitle, parseMeta, type BookingGroup, type CostTotal } from './bookingsModel'
|
||||
import type { BookingFacts } from './bookingFacts'
|
||||
@@ -82,7 +83,7 @@ function Row({ r, p, facts, files, costs, t, locale }: {
|
||||
const sub = facts.endpoints.length >= 2
|
||||
? facts.endpoints.map(e => e.code || e.name).join(' → ')
|
||||
: facts.accommodation || facts.place || ''
|
||||
const extras: string[] = [meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.airline, meta.train_number, meta.seat, meta.platform].filter(Boolean)
|
||||
const extras: string[] = [meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.airline, meta.train_number, ...bookingSeats(r).map(s => s.seat), meta.platform].filter(Boolean)
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -231,3 +231,14 @@ describe('bookingFacts: codes, links and places', () => {
|
||||
expect(bookingFacts(buildReservation({ url: 'javascript:alert(1)' }), ctx()).url?.href).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('bookingFacts: seats of a flight with a stop', () => {
|
||||
it('FE-PLANNER-BKFACTS-025: the Seat cell holds the seat booked only on the second leg', () => {
|
||||
const r = buildReservation({
|
||||
type: 'flight',
|
||||
metadata: JSON.stringify({ class: 'Economy', legs: [{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }] }),
|
||||
});
|
||||
const facts = bookingFacts(r, ctx());
|
||||
expect(cell(facts, 'reservations.meta.seat')).toBe('14C, Economy');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Day, Reservation, ReservationEndpoint } from '../../../types'
|
||||
import { formatPriceText, formatTime, splitReservationDateTime } from '../../../utils/formatters'
|
||||
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../../utils/flightLegs'
|
||||
import { getFlightLegs, getTrainLegs, seatCells, usesStationRoute } from '../../../utils/flightLegs'
|
||||
import { safeExternalHref } from '../../../utils/safeUrl'
|
||||
import { daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
|
||||
import { bookingDates, daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
|
||||
|
||||
export interface FactsContext {
|
||||
t: (key: string, params?: Record<string, string | number>) => string
|
||||
@@ -84,6 +84,7 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
|
||||
const eps = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
|
||||
const from = eps.find(e => e.role === 'from')
|
||||
const to = eps.find(e => e.role === 'to')
|
||||
const dates = bookingDates(r, c.days)
|
||||
const startTime = startDt.time || from?.local_time || null
|
||||
const endTime = endDt.time || to?.local_time || null
|
||||
// A stay backed by an accommodation says its times as check-in and check-out;
|
||||
@@ -101,7 +102,8 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
|
||||
if (!hasEndpoints && meta.arrival_airport) cells.push({ label: t('reservations.meta.to'), value: meta.arrival_airport })
|
||||
if (meta.train_number) cells.push({ label: t('reservations.meta.trainNumber'), value: meta.train_number })
|
||||
if (meta.platform) cells.push({ label: t('reservations.meta.platform'), value: meta.platform })
|
||||
if (meta.seat) cells.push({ label: t('reservations.meta.seat'), value: meta.class ? `${meta.seat}, ${meta.class}` : meta.seat })
|
||||
// One seat per leg on a booking with a stop, each under its route; otherwise the booking's own.
|
||||
cells.push(...seatCells(r, t('reservations.meta.seat'), meta.class ? `, ${meta.class}` : ''))
|
||||
if (!c.hasLinkedCost && meta.price != null && meta.price !== '') {
|
||||
cells.push({ label: t('reservations.price'), value: formatPriceText(meta.price, meta.priceCurrency, c.tripCurrency, locale) })
|
||||
}
|
||||
@@ -124,8 +126,8 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
|
||||
|
||||
return {
|
||||
day, time, startTime, endTime,
|
||||
startDate: startDt.date || from?.local_date || span.start?.date || null,
|
||||
endDate: endDt.date || to?.local_date || span.end?.date || null,
|
||||
startDate: dates.start,
|
||||
endDate: dates.end,
|
||||
cells, endpoints: eps.length >= 2 ? eps : [], legCodes,
|
||||
place: r.location || r.place_name || null,
|
||||
accommodation: r.accommodation_name || null,
|
||||
|
||||
@@ -132,6 +132,23 @@ export function daySpan(r: Reservation, days: Day[]): DaySpan {
|
||||
return { start: byId(r.day_id), end: byId(r.end_day_id) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The calendar dates a booking starts and ends on, as "YYYY-MM-DD", or null where it
|
||||
* knows none: its own date first, then the local date of its first or last stop,
|
||||
* then the date of the day it is linked to. A day-linked transport often carries
|
||||
* only times, so its day stands in.
|
||||
*/
|
||||
export function bookingDates(r: Reservation, days: Day[]): { start: string | null; end: string | null } {
|
||||
const span = daySpan(r, days)
|
||||
const eps = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
|
||||
const from = eps.find(e => e.role === 'from')
|
||||
const to = eps.find(e => e.role === 'to')
|
||||
return {
|
||||
start: splitReservationDateTime(r.reservation_time).date || from?.local_date || span.start?.date || null,
|
||||
end: splitReservationDateTime(r.reservation_end_time).date || to?.local_date || span.end?.date || null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The moment a booking starts, as "YYYY-MM-DDTHH:MM" in its own local time, or null
|
||||
* without any date. A day-linked transport often carries no date in reservation_time,
|
||||
|
||||
@@ -54,6 +54,14 @@ describe('TransitLegs', () => {
|
||||
expect(screen.getByText('BVG')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-009: stop names and a walk target wrap instead of being cut off (#3139)', () => {
|
||||
render(<TransitLegs legs={[ride, walk]} compact />);
|
||||
for (const text of ['Alexanderplatz', 'Eberswalder Str.', 'Walk to Mauerpark']) {
|
||||
expect(screen.getByText(text)).not.toHaveClass('truncate');
|
||||
expect(screen.getByText(text)).toHaveClass('break-words');
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKTRANSIT-006: a walk reads as one and leaves out the ride facts', () => {
|
||||
render(<TransitLegs legs={[walk]} compact />);
|
||||
expect(screen.getByText('Walk to Mauerpark')).toBeInTheDocument();
|
||||
|
||||
@@ -48,9 +48,11 @@ export function TransitLegs({ legs, compact = false }: { legs: TransitLegDisplay
|
||||
}}>{leg.line || leg.mode}</span>
|
||||
)}
|
||||
<div className={`flex min-w-0 flex-1 flex-col ${compact ? 'gap-1' : 'gap-1.5'}`}>
|
||||
<div className="flex min-w-0 items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
|
||||
{walk ? <span className="truncate text-content-muted">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
|
||||
<><span className="truncate">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span className="truncate">{leg.to?.name}</span></>
|
||||
{/* Detail views show a stop name whole: the names wrap and the
|
||||
arrow moves to the next line with them when it has to (#3139). */}
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
|
||||
{walk ? <span className="min-w-0 break-words text-content-muted [overflow-wrap:anywhere]">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
|
||||
<><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.to?.name}</span></>
|
||||
)}
|
||||
</div>
|
||||
<TransitMetaBadges size={compact ? 'sm' : 'md'} items={[
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// FE-PLANNER-HOURS-001 to FE-PLANNER-HOURS-003
|
||||
// FE-PLANNER-HOURS-001 to FE-PLANNER-HOURS-007
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { cleanWeek, emptyWeek, hoursLines, periodsFromWeek, readWeek, weekdayNames, weekFromPeriods, writeWeek } from './placeHours'
|
||||
import { ALL_DAY, cleanWeek, emptyWeek, hoursLines, isAllDay, periodsFromWeek, readWeek, weekdayNames, weekFromPeriods, writeWeek } from './placeHours'
|
||||
|
||||
const week = JSON.stringify([
|
||||
{ closed: false, open: '09:00', close: '17:00' },
|
||||
@@ -61,5 +61,27 @@ describe('typing and taking over (#2472)', () => {
|
||||
expect(weekFromPeriods(null)).toBeNull()
|
||||
expect(weekFromPeriods([])).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-PLANNER-HOURS-006: a place open around the clock reads as all day, from the lookup and by hand', () => {
|
||||
const p = (day: number, h: number, m = 0) => ({ day, hour: h, minute: m })
|
||||
// Google writes a place open all week as one period on Sunday that never closes.
|
||||
expect(weekFromPeriods([{ open: p(0, 0), close: null }])).toEqual(Array.from({ length: 7 }, () => ({ closed: false, ...ALL_DAY })))
|
||||
// A day from midnight to the next midnight is the same.
|
||||
expect(weekFromPeriods([{ open: p(1, 0), close: p(2, 0) }])?.[0]).toEqual({ closed: false, ...ALL_DAY })
|
||||
expect(isAllDay({ closed: false, open: '00:00', close: '23:59' })).toBe(true)
|
||||
expect(isAllDay({ closed: false, open: '00:00', close: '00:00' })).toBe(true)
|
||||
expect(isAllDay({ closed: false, open: '00:00', close: '22:00' })).toBe(false)
|
||||
expect(isAllDay({ closed: true })).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-HOURS-007: the inspector names an all-day day instead of 00:00 to 23:59', () => {
|
||||
const week = emptyWeek()
|
||||
week[0] = { closed: false, ...ALL_DAY }
|
||||
week[1] = { closed: false, open: '09:00', close: '17:00' }
|
||||
const lines = hoursLines(writeWeek(week), 'en', 'Closed', 'Open 24 hours') ?? []
|
||||
expect(lines[0]).toBe('Monday: Open 24 hours')
|
||||
expect(lines[1]).toBe('Tuesday: 09:00 – 17:00')
|
||||
// Without the label the times stay, as before.
|
||||
expect(hoursLines(writeWeek(week), 'en', 'Closed')?.[0]).toBe('Monday: 00:00 – 23:59')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -26,12 +26,21 @@ export function weekdayNames(locale: string | undefined, width: 'long' | 'short'
|
||||
* looked-up hours (#2472): "Monday: 09:00 – 17:00", or the closed word. Null
|
||||
* when the place has no hours of its own, so the looked-up ones take over.
|
||||
*/
|
||||
export function hoursLines(raw: string | null | undefined, locale: string | undefined, closedLabel: string): string[] | null {
|
||||
/** Open around the clock, written the way the editor and the lookup both store it. */
|
||||
export const ALL_DAY = { open: '00:00', close: '23:59' } as const
|
||||
|
||||
/** A day open around the clock: 00:00 to 23:59, or to 00:00 as some sources write it. */
|
||||
export function isAllDay(day: PlaceOpeningHours[number]): boolean {
|
||||
return !day.closed && day.open === ALL_DAY.open && (day.close === ALL_DAY.close || day.close === ALL_DAY.open)
|
||||
}
|
||||
|
||||
export function hoursLines(raw: string | null | undefined, locale: string | undefined, closedLabel: string, allDayLabel?: string): string[] | null {
|
||||
const week = parsePlaceHours(raw)
|
||||
if (!hasPlaceHours(week)) return null
|
||||
const names = weekdayNames(locale)
|
||||
return week!.map((day, i) => {
|
||||
if (day.closed) return `${names[i]}: ${closedLabel}`
|
||||
if (allDayLabel && isAllDay(day)) return `${names[i]}: ${allDayLabel}`
|
||||
if (!day.open && !day.close) return `${names[i]}: –`
|
||||
return `${names[i]}: ${day.open ?? '…'} – ${day.close ?? '…'}`
|
||||
})
|
||||
@@ -80,11 +89,14 @@ interface Point { day: number; hour: number; minute: number }
|
||||
* column shows, so a place edited later starts from them instead of from
|
||||
* nothing. One range per day, the earliest opening to the latest closing, which
|
||||
* is what the editor can hold; a day the provider names no period for is
|
||||
* closed. A period that never closes is open around the clock. Null when the
|
||||
* provider gave no periods at all.
|
||||
* closed. A period that never closes is open around the clock: Google writes a
|
||||
* place open all week as one such period on Sunday, so that alone opens every
|
||||
* day. A span of a whole day or more is open around the clock too. Null when
|
||||
* the provider gave no periods at all.
|
||||
*/
|
||||
export function weekFromPeriods(periods: { open: Point; close?: Point | null }[] | null | undefined): PlaceOpeningHours | null {
|
||||
if (!periods?.length) return null
|
||||
if (periods.length === 1 && !periods[0].close) return Array.from({ length: PLACE_HOURS_DAYS }, () => ({ closed: false, ...ALL_DAY }))
|
||||
// Minutes after the day's own midnight; a close past midnight counts on top of 24h.
|
||||
const span: ({ open: number; close: number } | null)[] = Array.from({ length: PLACE_HOURS_DAYS }, () => null)
|
||||
for (const period of periods) {
|
||||
@@ -96,6 +108,10 @@ export function weekFromPeriods(periods: { open: Point; close?: Point | null }[]
|
||||
span[i] = cur ? { open: Math.min(cur.open, open), close: Math.max(cur.close, close) } : { open, close }
|
||||
}
|
||||
const clock = (m: number) => `${String(Math.floor(m / 60) % 24).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`
|
||||
const week: PlaceOpeningHours = span.map(s => (s ? { closed: false, open: clock(s.open), close: clock(s.close) } : { closed: true }))
|
||||
const week: PlaceOpeningHours = span.map(s => {
|
||||
if (!s) return { closed: true }
|
||||
if (s.open === 0 && s.close >= 24 * 60 - 1) return { closed: false, ...ALL_DAY }
|
||||
return { closed: false, open: clock(s.open), close: clock(s.close) }
|
||||
})
|
||||
return week
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { AssignmentsMap, Place } from '../../types';
|
||||
|
||||
/** Resolve the chosen day's places by day id, in itinerary order (#1460). */
|
||||
export function getTransitDayPlaces(dayId: number, assignments: AssignmentsMap, places: Place[]): Place[] {
|
||||
return (assignments[String(dayId)] ?? [])
|
||||
.slice()
|
||||
.sort((a, b) => a.order_index - b.order_index)
|
||||
.map((a) => places.find((p) => p.id === a.place_id))
|
||||
.filter((p): p is Place => p != null);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user