mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 21:33:19 +00:00
Compare commits
236 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 965b519f23 | |||
| 3ec7cc73b2 | |||
| 493571c559 | |||
| 4212fcdfc8 | |||
| 28f750f7c4 | |||
| 8c9cf4a80c | |||
| b33d592325 | |||
| 590b174dd1 | |||
| 2a833c4ba9 | |||
| a5de1bc52d | |||
| 1b20214a7f | |||
| 3e8496dce6 | |||
| ea1b75e639 | |||
| c0f6551cf4 | |||
| 1fdf74e7f2 | |||
| c7de823c78 | |||
| 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 |
@@ -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 }}
|
||||
@@ -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.
|
||||
|
||||
@@ -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]
|
||||
|
||||
+924
-747
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.
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The log line for a page of the server that came back with an error status.
|
||||
* "HTTP 503" on the address screen cannot tell the server, a proxy in front of
|
||||
* it and something on the phone apart, so the line names the page and the
|
||||
* headers that say who answered (#3014).
|
||||
*/
|
||||
final class PageErrorLog {
|
||||
|
||||
/** The headers that name whoever answered a page, in the order they are logged. */
|
||||
private static final String[] SENDER_HEADERS = { "Server", "Via", "CF-Ray", "Content-Type" };
|
||||
|
||||
private PageErrorLog() {}
|
||||
|
||||
/**
|
||||
* For example "Page answered HTTP 503 Service Unavailable for
|
||||
* https://trek.example.com/login (server: cloudflare, cf-ray: 8f1a2b3c4d5e6f70-FRA)".
|
||||
* The address goes without its query and fragment, where a sign-in page
|
||||
* carries a challenge or a code. A header the answer did not have is left
|
||||
* out, and an answer with none of them says so: no server sends a page
|
||||
* without at least its type, so that points at something on the phone.
|
||||
*/
|
||||
static String describe(String url, int status, String reason, Map<String, String> headers) {
|
||||
StringBuilder line = new StringBuilder("Page answered HTTP ").append(status);
|
||||
if (reason != null && !reason.trim().isEmpty()) line.append(' ').append(reason.trim());
|
||||
line.append(" for ").append(withoutQuery(url));
|
||||
List<String> senders = new ArrayList<>();
|
||||
for (String name : SENDER_HEADERS) {
|
||||
String value = header(headers, name);
|
||||
if (value != null && !value.trim().isEmpty()) senders.add(name.toLowerCase(Locale.ROOT) + ": " + value.trim());
|
||||
}
|
||||
line.append(senders.isEmpty() ? " (no server headers)" : " (" + String.join(", ", senders) + ")");
|
||||
return line.toString();
|
||||
}
|
||||
|
||||
/** A header by name, whatever case the answer wrote it in. */
|
||||
private static String header(Map<String, String> headers, String name) {
|
||||
if (headers == null) return null;
|
||||
for (Map.Entry<String, String> entry : headers.entrySet()) {
|
||||
if (name.equalsIgnoreCase(entry.getKey())) return entry.getValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String withoutQuery(String url) {
|
||||
if (url == null) return "";
|
||||
int end = url.length();
|
||||
int query = url.indexOf('?');
|
||||
if (query >= 0) end = query;
|
||||
int fragment = url.indexOf('#');
|
||||
if (fragment >= 0 && fragment < end) end = fragment;
|
||||
return url.substring(0, end);
|
||||
}
|
||||
}
|
||||
@@ -202,14 +202,23 @@ class TrekWebViewClient extends BridgeWebViewClient {
|
||||
* none, as Cloudflare does with a 403, sends the app to the address screen,
|
||||
* which says so and offers to add one. Any other 4xx page (a proxy's block
|
||||
* page, a certificate it refused) stays up with the bar and its way out, so
|
||||
* the app is never stuck on a page without TREK's UI.
|
||||
* the app is never stuck on a page without TREK's UI. Each one is logged
|
||||
* with its address and whoever answered it (PageErrorLog).
|
||||
*/
|
||||
@Override
|
||||
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
|
||||
int status = errorResponse.getStatusCode();
|
||||
if (!request.isForMainFrame()) {
|
||||
super.onReceivedHttpError(view, request, errorResponse);
|
||||
} else if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
|
||||
return;
|
||||
}
|
||||
Log.w("TrekShell", PageErrorLog.describe(
|
||||
request.getUrl().toString(),
|
||||
status,
|
||||
errorResponse.getReasonPhrase(),
|
||||
errorResponse.getResponseHeaders()
|
||||
));
|
||||
if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
|
||||
TrekServerStore.setFailure(view.getContext(), "HTTP " + status);
|
||||
onUnreachable.run();
|
||||
} else if (status >= 400) {
|
||||
|
||||
@@ -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"))
|
||||
},
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.liketrek.trek
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/** The log line for a page that came back with an error status (#3014). */
|
||||
class PageErrorLogTest {
|
||||
|
||||
@Test
|
||||
fun namesThePageItsStatusAndWhoAnswered() {
|
||||
val line = PageErrorLog.describe(
|
||||
"https://trek.example.com/login?redirect=%2F#top",
|
||||
503,
|
||||
"Service Unavailable",
|
||||
mapOf(
|
||||
"server" to "cloudflare",
|
||||
"CF-RAY" to "8f1a2b3c4d5e6f70-FRA",
|
||||
"content-type" to "text/html; charset=UTF-8",
|
||||
"Set-Cookie" to "session=secret",
|
||||
),
|
||||
)
|
||||
|
||||
// Any case of a header name is read, only the naming headers are logged,
|
||||
// and the query with its sign-in state is left off.
|
||||
assertEquals(
|
||||
"Page answered HTTP 503 Service Unavailable for https://trek.example.com/login " +
|
||||
"(server: cloudflare, cf-ray: 8f1a2b3c4d5e6f70-FRA, content-type: text/html; charset=UTF-8)",
|
||||
line,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAnswerWithoutHeadersSaysSo() {
|
||||
assertEquals(
|
||||
"Page answered HTTP 503 for https://trek.example.com/ (no server headers)",
|
||||
PageErrorLog.describe("https://trek.example.com/", 503, null, emptyMap()),
|
||||
)
|
||||
assertEquals(
|
||||
"Page answered HTTP 502 Bad Gateway for (no server headers)",
|
||||
PageErrorLog.describe(null, 502, "Bad Gateway", null),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFragmentBeforeAQuestionMarkEndsTheAddressThere() {
|
||||
assertEquals(
|
||||
"Page answered HTTP 500 for https://trek.example.com/trips/4 (via: 1.1 proxy)",
|
||||
PageErrorLog.describe("https://trek.example.com/trips/4#a?b", 500, " ", mapOf("Via" to "1.1 proxy")),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,6 +121,9 @@ class TrekBridgeViewController: CAPBridgeViewController {
|
||||
right: max(0, safe.right - (window.bounds.maxX - frame.maxX))
|
||||
)
|
||||
let corner = cornerElement(in: frame, window: window)
|
||||
if corner != .zero, cornerWindowSizes.insert(sizeKey(window.bounds.size)).inserted {
|
||||
setNeedsStatusBarAppearanceUpdate()
|
||||
}
|
||||
if !force, insets == publishedSafeArea, corner == publishedCorner { return }
|
||||
publishedSafeArea = insets
|
||||
publishedCorner = corner
|
||||
@@ -139,15 +142,36 @@ class TrekBridgeViewController: CAPBridgeViewController {
|
||||
|
||||
private var publishedCorner: UIEdgeInsets?
|
||||
|
||||
// MARK: - The status bar beside a corner element
|
||||
|
||||
/// The window sizes on which a corner element was seen. On an iPhone Duo
|
||||
/// that element is the status capsule, so the app hides the status bar
|
||||
/// there to take the capsule away; whatever still covers the corner stays
|
||||
/// in the safe area the page keeps clear of. A size stays in the set
|
||||
/// once seen: with the bar hidden the next measure may find no corner, and
|
||||
/// showing the bar again would bring the capsule back and start over. The
|
||||
/// folded and the unfolded display differ in size, so each keeps its own
|
||||
/// answer, and a device without such an element never hides its bar.
|
||||
private var cornerWindowSizes = Set<String>()
|
||||
|
||||
private func sizeKey(_ size: CGSize) -> String {
|
||||
"\(Int(size.width.rounded()))x\(Int(size.height.rounded()))"
|
||||
}
|
||||
|
||||
override var prefersStatusBarHidden: Bool {
|
||||
if super.prefersStatusBarHidden { return true }
|
||||
guard let size = view.window?.bounds.size else { return false }
|
||||
return cornerWindowSizes.contains(sizeKey(size))
|
||||
}
|
||||
|
||||
/// An element in a top corner of the screen, such as the status capsule of
|
||||
/// an iPhone Duo: how far down it reaches (top) and how wide it is on its
|
||||
/// side (left/right), in the web view's coordinates; zero where there is
|
||||
/// none. iOS 26 tells a corner apart from a whole edge: the safe area with
|
||||
/// the corner avoided vertically reaches lower than the one avoiding it
|
||||
/// horizontally, which in turn is wider on the corner's side. The page puts
|
||||
/// its top bar beside the element and starts its content below it, using
|
||||
/// the full width (mobile.css), instead of giving up a strip of the whole
|
||||
/// height.
|
||||
/// horizontally, which in turn is wider on the corner's side. The page
|
||||
/// counts it into its safe area (mobile.css): upright its content starts
|
||||
/// below the element, on a wide window it leaves the element's side free.
|
||||
private func cornerElement(in frame: CGRect, window: UIWindow) -> UIEdgeInsets {
|
||||
guard #available(iOS 26.0, *) else { return .zero }
|
||||
let vertical = view.edgeInsets(for: .safeArea(cornerAdaptation: .vertical))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -3,16 +3,16 @@
|
||||
"@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": 127,
|
||||
"complexity": 216,
|
||||
"@typescript-eslint/no-explicit-any": 138,
|
||||
"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": 121,
|
||||
"@typescript-eslint/no-unused-vars": 117,
|
||||
"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": 1875,
|
||||
"@typescript-eslint/no-non-null-assertion": 1872,
|
||||
"@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"]
|
||||
},
|
||||
{
|
||||
@@ -1113,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"]
|
||||
}
|
||||
|
||||
@@ -1542,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,
|
||||
|
||||
@@ -35,7 +35,6 @@
|
||||
"components/Map/nightPauseMarker.ts": 4,
|
||||
"components/Map/ratingBadge.ts": 1,
|
||||
"components/Map/switcherRow.ts": 1,
|
||||
"components/PDF/TripPDF.tsx": 7,
|
||||
"components/PDF/tripMapImage.ts": 1,
|
||||
"components/Packing/PackingListPanelBagCard.tsx": 1,
|
||||
"components/Packing/PackingListPanelCategoryGroup.tsx": 3,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
"src/components/Map/ReservationOverlay.test.tsx": 1,
|
||||
"src/components/Map/transitGeometry.ts": 1,
|
||||
"src/components/Map/useMarkerThumbs.ts": 1,
|
||||
"src/components/PDF/TripPDF.tsx": 38,
|
||||
"src/components/PDF/TripPDF.tsx": 1,
|
||||
"src/components/Planner/DayPlanSidebar.constants.ts": 1,
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 52,
|
||||
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
|
||||
@@ -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,
|
||||
|
||||
@@ -72,7 +72,6 @@
|
||||
"components/Map/ratingBadge.ts": 2,
|
||||
"components/Map/reservationsMapbox.ts": 1,
|
||||
"components/Map/switcherRow.ts": 1,
|
||||
"components/PDF/TripPDF.tsx": 44,
|
||||
"components/Packing/PackingListPanelBagModal.tsx": 2,
|
||||
"components/Packing/PackingListPanelCategoryGroup.tsx": 5,
|
||||
"components/Packing/PackingListPanelHeader.tsx": 3,
|
||||
@@ -146,7 +145,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,
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
@@ -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. */
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -245,7 +245,7 @@ describe('trip route map in the PDF', () => {
|
||||
expect(html).toContain('<svg class="trip-map-svg"')
|
||||
// Between the cover and the days, which is where it is meant to read.
|
||||
expect(html.indexOf('class="trip-map"')).toBeGreaterThan(html.indexOf('class="cover"'))
|
||||
expect(html.indexOf('class="trip-map"')).toBeLessThan(html.indexOf('class="day-section"'))
|
||||
expect(html.indexOf('class="trip-map"')).toBeLessThan(html.indexOf('class="day-section'))
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-MAP-011: prefers the real basemap when it renders', async () => {
|
||||
|
||||
@@ -37,6 +37,41 @@ function plannedStat(html: string): number | null {
|
||||
return match ? Number(match[1]) : null
|
||||
}
|
||||
|
||||
/** The days of the document, without the cover and the overview's booking list before them. */
|
||||
function daysOf(html: string): string {
|
||||
return html.slice(html.indexOf('<table class="day-section'))
|
||||
}
|
||||
|
||||
const textOf = (el: Element | null | undefined) => el?.textContent?.trim() ?? ''
|
||||
|
||||
/**
|
||||
* Each booking on the days' timelines, read the way it prints: the span label over the
|
||||
* title, the start and end in the time column, one line per leg (its route, then its
|
||||
* facts, then its own code, as one string) and the codes of the whole booking.
|
||||
*/
|
||||
function bookingsOf(html: string) {
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html')
|
||||
return [...doc.querySelectorAll('.timeline .tl-booking')].map(item => ({
|
||||
kicker: textOf(item.querySelector('.note-kicker')),
|
||||
title: textOf(item.querySelector('.note-text')),
|
||||
start: textOf(item.querySelector('.tl-start')),
|
||||
end: textOf(item.querySelector('.tl-end')),
|
||||
lines: [...item.querySelectorAll('.note-line')].map(line =>
|
||||
[...line.children].map(part => textOf(part)).filter(Boolean).join(' · ')),
|
||||
codes: [...item.querySelectorAll('.note-extra .code-chip')].map(code => textOf(code)),
|
||||
}))
|
||||
}
|
||||
|
||||
/** Every line printed under the bookings' titles, across the days. */
|
||||
const bookingLines = (html: string) => bookingsOf(html).flatMap(b => b.lines)
|
||||
|
||||
/** The booking of that title and span label, as bookingsOf reads it. */
|
||||
function bookingCard(html: string, title: string, kicker = '') {
|
||||
const card = bookingsOf(html).find(b => b.title === title && b.kicker === kicker)
|
||||
if (!card) throw new Error(`no booking "${title}" labelled "${kicker}"`)
|
||||
return card
|
||||
}
|
||||
|
||||
// ── Setup ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -175,8 +210,8 @@ describe('downloadTripPDF', () => {
|
||||
expect(srcdoc).toContain('<table class="day-section')
|
||||
expect(srcdoc).toContain('<thead class="day-header">')
|
||||
expect(srcdoc).toContain('<tbody class="day-body-group">')
|
||||
// The dark bar (background/padding/flex) lives in an inner wrapper inside the thead.
|
||||
expect(srcdoc).toContain('class="day-header-bar"')
|
||||
// The header (number, date, title, figures) lives in an inner wrapper inside the thead.
|
||||
expect(srcdoc).toContain('<thead class="day-header"><tr><td><div class="day-head">')
|
||||
// Day content still renders inside the new structure.
|
||||
expect(srcdoc).toContain('Rome Day')
|
||||
expect(srcdoc).toContain('Colosseum')
|
||||
@@ -188,10 +223,10 @@ describe('downloadTripPDF', () => {
|
||||
const srcdoc = iframe!.srcdoc
|
||||
// The thead is repeated on every overflow page, so the spacing below the header bar
|
||||
// must be declared on its cell...
|
||||
expect(srcdoc).toContain('.day-header > tr > td { padding-bottom: 12px; }')
|
||||
expect(srcdoc).toContain('.day-header > tr > td { padding: 0 var(--gutter) 5mm; }')
|
||||
// ...and not as a block-start padding on .day-body, which the print engine only paints
|
||||
// on the first fragment of the (fragmented) body cell.
|
||||
expect(srcdoc).toContain('.day-body { padding: 0 28px 6px; }')
|
||||
expect(srcdoc).toContain('.day-body { padding: 0 var(--gutter) 4mm; }')
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-006: escHtml prevents XSS in trip title', async () => {
|
||||
@@ -255,8 +290,27 @@ describe('downloadTripPDF', () => {
|
||||
const iframe = getIframe()
|
||||
expect(iframe!.srcdoc).toContain('Flight to Rome')
|
||||
expect(iframe!.srcdoc).toContain('ABC123')
|
||||
// Single-leg flight keeps its full-route subtitle.
|
||||
expect(iframe!.srcdoc).toContain('Air Italia · AI123 · CDG → FCO')
|
||||
// Single-leg flight keeps its full route, then airline and number as badges.
|
||||
expect(bookingLines(iframe!.srcdoc)).toContain('CDG → FCO · Air Italia · AI123')
|
||||
})
|
||||
|
||||
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 lines = bookingLines(getIframe()?.srcdoc ?? '')
|
||||
expect(lines).toContain('CDG → FCO · Air Italia · AI123 · reservations.meta.seat 31A')
|
||||
expect(lines).toContain('BER → HND · Lufthansa · LH2 · reservations.meta.seat 14C')
|
||||
expect(lines).toContain('FRA → BER · Lufthansa · LH1')
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-013f: the stop a booked night wrote is not listed, so a morning flight prints before the hotel (#2434)', async () => {
|
||||
@@ -310,15 +364,14 @@ describe('downloadTripPDF', () => {
|
||||
const iframe = getIframe()
|
||||
|
||||
// Without the landing time the reader cannot tell what is left of the day.
|
||||
expect(iframe!.srcdoc).toContain('14:30 – 16:45')
|
||||
expect(bookingCard(iframe!.srcdoc, 'Flight to Rome')).toMatchObject({ start: '14:30', end: '16:45' })
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-013d: a flight without a landing time still shows its departure', async () => {
|
||||
await downloadTripPDF(richArgs)
|
||||
const iframe = getIframe()
|
||||
|
||||
expect(iframe!.srcdoc).toContain('14:30')
|
||||
expect(iframe!.srcdoc).not.toContain('14:30 –')
|
||||
expect(bookingCard(iframe!.srcdoc, 'Flight to Rome')).toMatchObject({ start: '14:30', end: '' })
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-013e: an overnight flight keeps its arrival on the arrival day (#1310)', async () => {
|
||||
@@ -332,16 +385,16 @@ describe('downloadTripPDF', () => {
|
||||
})
|
||||
const iframe = getIframe()
|
||||
|
||||
expect(iframe!.srcdoc).not.toContain('14:30 – 06:15')
|
||||
expect(iframe!.srcdoc).toContain('06:15')
|
||||
const html = iframe!.srcdoc
|
||||
expect(bookingCard(html, 'Flight to Rome', 'reservations.span.departure')).toMatchObject({ start: '14:30', end: '' })
|
||||
expect(bookingCard(html, 'Flight to Rome', 'reservations.span.arrival')).toMatchObject({ start: '06:15' })
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-013b: renders every flight number for a multi-leg flight', async () => {
|
||||
await downloadTripPDF({ ...richArgs, reservations: [multiLegFlight] })
|
||||
const iframe = getIframe()
|
||||
// One subtitle line per leg, each with its own flight number and segment route.
|
||||
expect(iframe!.srcdoc).toContain('Lufthansa · LH1 · FRA → BER')
|
||||
expect(iframe!.srcdoc).toContain('Lufthansa · LH2 · BER → HND')
|
||||
// One line per leg, each with its own flight number and segment route.
|
||||
expect(bookingLines(iframe!.srcdoc)).toEqual(['FRA → BER · Lufthansa · LH1', 'BER → HND · Lufthansa · LH2'])
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-014: renders cover image when trip has cover_image', async () => {
|
||||
@@ -741,11 +794,9 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
}]))
|
||||
const html = srcdoc()
|
||||
|
||||
expect(html).toContain('reservations.span.start: Nordic Cruise')
|
||||
expect(html).toContain('reservations.span.ongoing: Nordic Cruise')
|
||||
expect(html).toContain('reservations.span.end: Nordic Cruise')
|
||||
expect(html).toContain('09:00')
|
||||
expect(html).toContain('18:00')
|
||||
expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.start').start).toBe('09:00')
|
||||
expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.ongoing').start).toBe('')
|
||||
expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.end').start).toBe('18:00')
|
||||
})
|
||||
|
||||
it('FE-W5PDF-002: a multi-day flight uses departure/arrival wording', async () => {
|
||||
@@ -756,8 +807,8 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
}]))
|
||||
const html = srcdoc()
|
||||
|
||||
expect(html).toContain('reservations.span.departure: Red Eye')
|
||||
expect(html).toContain('reservations.span.arrival: Red Eye')
|
||||
expect(bookingCard(html, 'Red Eye', 'reservations.span.departure').start).toBe('23:00')
|
||||
expect(bookingCard(html, 'Red Eye', 'reservations.span.arrival').start).toBe('06:00')
|
||||
})
|
||||
|
||||
it('FE-W5PDF-003: a multi-day car hire is labelled pickup/return and skips the middle day', async () => {
|
||||
@@ -767,8 +818,10 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
}]))
|
||||
const html = srcdoc()
|
||||
|
||||
expect(html).toContain('reservations.span.pickup: Rental')
|
||||
expect(html).toContain('reservations.span.return: Rental')
|
||||
expect(bookingsOf(html).map(b => [b.kicker, b.title])).toEqual([
|
||||
['reservations.span.pickup', 'Rental'],
|
||||
['reservations.span.return', 'Rental'],
|
||||
])
|
||||
expect(html).not.toContain('reservations.span.active')
|
||||
})
|
||||
|
||||
@@ -779,8 +832,10 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
}]))
|
||||
const html = srcdoc()
|
||||
|
||||
expect(html).toContain('reservations.span.dropOff: Airport Parking')
|
||||
expect(html).toContain('reservations.span.pickup: Airport Parking')
|
||||
expect(bookingsOf(html).map(b => [b.kicker, b.title])).toEqual([
|
||||
['reservations.span.dropOff', 'Airport Parking'],
|
||||
['reservations.span.pickup', 'Airport Parking'],
|
||||
])
|
||||
expect(html).not.toContain('reservations.span.ongoing')
|
||||
// Day B holds nothing else, so it prints the empty-day hint rather than the booking.
|
||||
expect(html).toContain('dayplan.emptyDay')
|
||||
@@ -809,7 +864,7 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
}]))
|
||||
const html = srcdoc()
|
||||
|
||||
expect(html).toContain('ICE 599 · reservations.meta.platform 7 · reservations.meta.seat 21A · FRA → BER')
|
||||
expect(bookingLines(html)).toEqual(['FRA → BER · ICE 599 · reservations.meta.platform 7 · reservations.meta.seat 21A'])
|
||||
})
|
||||
|
||||
it('FE-W5PDF-006: a multi-leg train renders one line per leg', async () => {
|
||||
@@ -824,8 +879,7 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
}]))
|
||||
const html = srcdoc()
|
||||
|
||||
expect(html).toContain('IC 1 · reservations.meta.platform 3 · BER → MUC')
|
||||
expect(html).toContain('EC 2 · MUC → ZRH')
|
||||
expect(bookingLines(html)).toEqual(['BER → MUC · IC 1 · reservations.meta.platform 3', 'MUC → ZRH · EC 2'])
|
||||
})
|
||||
|
||||
it('FE-W5PDF-007: restaurant, event, tour and unknown types get their own subtitles', async () => {
|
||||
@@ -837,7 +891,8 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
]))
|
||||
const html = srcdoc()
|
||||
|
||||
expect(html).toContain('4 guests')
|
||||
// The party size needs no word: it prints beside the people icon.
|
||||
expect(bookingCard(html, 'Dinner').lines).toEqual(['4'])
|
||||
expect(html).toContain('Arena')
|
||||
expect(html).toContain('GuideCo')
|
||||
expect(html).toContain('Mystery')
|
||||
@@ -870,8 +925,7 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
}]))
|
||||
const html = srcdoc()
|
||||
|
||||
expect(html).toContain('AirX · X1')
|
||||
expect(html).toContain('AirX · X2 · AAA → BBB')
|
||||
expect(bookingLines(html)).toEqual(['AirX · X1', 'AAA → BBB · AirX · X2'])
|
||||
})
|
||||
|
||||
it('FE-W5PDF-030: a stopover flight prints the booking code of each segment that has one (#1943)', async () => {
|
||||
@@ -886,11 +940,12 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
}]))
|
||||
const html = srcdoc()
|
||||
|
||||
expect(html).toContain('LH · LH1 · FRA → BER · ABC123')
|
||||
// Each leg is its own card, the way the day plan shows it, with its own line.
|
||||
const legs = bookingsOf(html).filter(b => b.title === 'Layover')
|
||||
expect(legs.map(leg => leg.lines)).toEqual([['FRA → BER · LH · LH1 · ABC123'], ['BER → HND · ANA · NH2']])
|
||||
// A segment without one keeps the line it had before, and the booking's own
|
||||
// reference still prints once for the whole card.
|
||||
expect(html).toContain('ANA · NH2 · BER → HND')
|
||||
expect(html).toContain('Code: BOOK1')
|
||||
// reference still prints on its card.
|
||||
expect(legs[0].codes).toEqual(['BOOK1'])
|
||||
})
|
||||
|
||||
it('FE-W5PDF-010: a single-leg flight with waypoints joins the whole route', async () => {
|
||||
@@ -900,7 +955,7 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
metadata: { airline: 'LH', flight_number: 'LH7' },
|
||||
}]))
|
||||
|
||||
expect(srcdoc()).toContain('LH · LH7 · FRA → Berlin → HND')
|
||||
expect(bookingLines(srcdoc())).toEqual(['FRA → Berlin → HND · LH · LH7'])
|
||||
})
|
||||
|
||||
it('FE-W5PDF-011: an assignment without a place contributes nothing', async () => {
|
||||
@@ -984,9 +1039,11 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
await downloadTripPDF(spanArgs([]))
|
||||
const html = srcdoc()
|
||||
|
||||
expect(html.indexOf('Earlier Inn')).toBeLessThan(html.indexOf('Later Inn'))
|
||||
const days = daysOf(html)
|
||||
expect(days.indexOf('Earlier Inn')).toBeGreaterThan(-1)
|
||||
expect(days.indexOf('Earlier Inn')).toBeLessThan(days.indexOf('Later Inn'))
|
||||
// the shared days list two hotels, so they lose the single-column class
|
||||
expect(html).toContain('class="day-accommodations "')
|
||||
expect(html).toContain('class="day-accommodations"')
|
||||
})
|
||||
|
||||
it('FE-W5PDF-017: a trip without dated days prints no date range and no day dates', async () => {
|
||||
@@ -999,7 +1056,7 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
|
||||
expect(html).not.toContain('class="cover-dates"')
|
||||
expect(html).not.toContain('class="day-date"')
|
||||
expect(html).toContain('class="cover-circle-ph"')
|
||||
expect(html).toContain('<section class="cover cover-plain">')
|
||||
})
|
||||
|
||||
it('FE-W5PDF-018: the print button asks the preview frame to print', async () => {
|
||||
@@ -1026,7 +1083,7 @@ describe('downloadTripPDF remaining branches', () => {
|
||||
trip: { id: 1, title: 'Cover Trip', description: null, cover_image: '/uploads/cover.svg' } as any,
|
||||
})
|
||||
expect(srcdoc()).not.toContain('/uploads/cover.svg')
|
||||
expect(srcdoc()).toContain('class="cover-circle-ph"')
|
||||
expect(srcdoc()).toContain('<section class="cover cover-plain">')
|
||||
})
|
||||
|
||||
it('FE-W5PDF-020: plugin sections render their paragraphs and tables', async () => {
|
||||
@@ -1062,7 +1119,7 @@ describe('downloadTripPDF defaults', () => {
|
||||
|
||||
// no translator, no days, no places, no notes
|
||||
expect(html).toContain('pdf.travelPlan')
|
||||
expect(html).toContain('<div class="cover-title">My Trip</div>')
|
||||
expect(html).toContain('<h1 class="cover-title">My Trip</h1>')
|
||||
expect(html).toContain('<div class="cover-stat-num">0</div>')
|
||||
})
|
||||
|
||||
@@ -1127,11 +1184,9 @@ describe('downloadTripPDF defaults', () => {
|
||||
reservations: [{ id: 1, title: 'Overnight Bus', type: 'bus', day_id: 1, end_day_id: 2, reservation_time: '22:00', reservation_end_time: null }] as any[],
|
||||
})
|
||||
const html = srcdoc()
|
||||
const endSection = html.slice(html.indexOf('End Day'))
|
||||
|
||||
expect(html).toContain('reservations.span.start: Overnight Bus')
|
||||
expect(endSection).toContain('reservations.span.end: Overnight Bus')
|
||||
expect(endSection).not.toContain('22:00')
|
||||
expect(bookingCard(html, 'Overnight Bus', 'reservations.span.start').start).toBe('22:00')
|
||||
expect(bookingCard(html, 'Overnight Bus', 'reservations.span.end')).toMatchObject({ start: '', end: '' })
|
||||
})
|
||||
|
||||
it('FE-W5PDF-027: an export without a locale still renders, with lang="en"', async () => {
|
||||
@@ -1198,12 +1253,16 @@ describe('page breaks between days (#1292)', () => {
|
||||
expect(toggle()!.style.background).toContain('--border-primary')
|
||||
})
|
||||
|
||||
it('FE-PDF-BREAK-003: the first day never carries a break of its own', async () => {
|
||||
// The first day opens the plan after the cover and the overview, so it always starts a
|
||||
// sheet; the switch decides only whether the days after it do.
|
||||
it('FE-PDF-BREAK-003: the first day never carries the switchable break', async () => {
|
||||
await downloadTripPDF(twoDays)
|
||||
const html = getIframe()!.srcdoc
|
||||
|
||||
expect(html.indexOf('<table class="day-section">')).toBeGreaterThan(-1)
|
||||
expect(html.indexOf('<table class="day-section day-first"')).toBeGreaterThan(-1)
|
||||
expect(html.match(/day-section day-break/g)).toHaveLength(1)
|
||||
expect(html).toContain('.day-first { break-before: page; }')
|
||||
expect(html).toContain('.pdf-flow .day-break { break-before: auto; }')
|
||||
})
|
||||
|
||||
it('FE-PDF-BREAK-004: turning the breaks off is remembered and shown at once', async () => {
|
||||
@@ -1286,8 +1345,8 @@ describe('a printed day follows the plan (#1978)', () => {
|
||||
const d2 = { id: 22, day_number: 2, title: 'Day Two', date: '2025-06-02' } as any
|
||||
const srcdoc = () => getIframe()!.srcdoc
|
||||
|
||||
/** Where each needle first appears, so order can be asserted without parsing. */
|
||||
const positions = (html: string, needles: string[]) => needles.map(n => html.indexOf(n))
|
||||
/** Where each needle first appears in the days, so order can be asserted without parsing. */
|
||||
const positions = (html: string, needles: string[]) => needles.map(n => daysOf(html).indexOf(n))
|
||||
|
||||
it('orders the day by the clock, not by the order the API sent rows in', async () => {
|
||||
await downloadTripPDF({
|
||||
@@ -1371,7 +1430,7 @@ describe('a printed day follows the plan (#1978)', () => {
|
||||
dayId: 21,
|
||||
}).map(item => (item.type === 'place' ? item.data.place.name : item.data.title))
|
||||
|
||||
const seen = expected.map(name => html.indexOf(name))
|
||||
const seen = expected.map(name => daysOf(html).indexOf(name))
|
||||
for (const at of seen) expect(at).toBeGreaterThan(-1)
|
||||
expect(seen).toEqual([...seen].sort((a, b) => a - b))
|
||||
})
|
||||
@@ -1454,18 +1513,20 @@ describe('downloadTripPDF — large text', () => {
|
||||
expect(html).not.toContain('pdf-large-text"')
|
||||
expect(largeToggle().getAttribute('aria-checked')).toBe('false')
|
||||
// One scale and one set of greys, at today's values unless the class is on.
|
||||
expect(html).toContain('--pdf-text: 1;')
|
||||
expect(html).toContain('--t: 1;')
|
||||
expect(html).toContain('body.pdf-large-text {')
|
||||
expect(html).toContain('.place-name { font-size: calc(11.5px * var(--pdf-text));')
|
||||
expect(html).toContain('.note-text { font-size: calc(9.5px * var(--pdf-text)); color: var(--pdf-ink);')
|
||||
expect(html).toContain('.place-name { flex: 1; font-size: calc(12px * var(--t));')
|
||||
expect(html).toContain('.note-text { font-size: calc(9.5px * var(--t)); color: var(--ink);')
|
||||
})
|
||||
|
||||
it('FE-PDF-LARGE-002: the clock and the booking code of a transport scale with the rest', async () => {
|
||||
await downloadTripPDF(richArgs)
|
||||
const html = previewFrame().srcdoc
|
||||
|
||||
expect(html).toContain('<span class="note-clock">')
|
||||
expect(html).toContain('<div class="note-time note-code">Code: ABC123</div>')
|
||||
// The clock sits in the time column and the code in its chip, both on the scale.
|
||||
expect(bookingCard(html, 'Flight to Rome')).toMatchObject({ start: '14:30', codes: ['ABC123'] })
|
||||
expect(html).toContain('.tl-start { display: block; font-size: calc(9.5px * var(--t));')
|
||||
expect(html).toContain('font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.04em;')
|
||||
expect(html).not.toContain('font-size:10px;')
|
||||
})
|
||||
|
||||
@@ -1530,14 +1591,14 @@ describe('downloadTripPDF — photos at thumbnail size', () => {
|
||||
await downloadTripPDF(withImage('/uploads/colosseum.jpg'))
|
||||
const html = previewFrame().srcdoc
|
||||
|
||||
expect(html).toContain(`<img class="place-thumb" src="${JPEG}" />`)
|
||||
expect(html).toContain(`<img class="place-thumb" src="${JPEG}" alt="" />`)
|
||||
expect(html).not.toContain('colosseum.jpg')
|
||||
})
|
||||
|
||||
it('FE-PDF-THUMB-002: a photo from another origin keeps its URL', async () => {
|
||||
await downloadTripPDF(withImage('https://images.example.com/colosseum.jpg'))
|
||||
|
||||
expect(previewFrame().srcdoc).toContain('<img class="place-thumb" src="https://images.example.com/colosseum.jpg" />')
|
||||
expect(previewFrame().srcdoc).toContain('<img class="place-thumb" src="https://images.example.com/colosseum.jpg" alt="" />')
|
||||
})
|
||||
|
||||
it('FE-PDF-THUMB-003: a closed export dialog stops the photos and opens nothing', async () => {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -8,13 +8,15 @@ import { http, HttpResponse } from 'msw';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { shrinkPdfImages } from './pdfImages';
|
||||
import { bakePdfCover, shrinkPdfImages, STRIP_PX } from './pdfImages';
|
||||
|
||||
const origin = window.location.origin;
|
||||
const JPEG = 'data:image/jpeg;base64,c21hbGw=';
|
||||
|
||||
let bitmapSize = { width: 1200, height: 800 };
|
||||
let drawn: { width: number; height: number }[] = [];
|
||||
let drawCalls: unknown[][] = [];
|
||||
let stops: [number, string][] = [];
|
||||
let inFlight = 0;
|
||||
let mostInFlight = 0;
|
||||
|
||||
@@ -24,7 +26,11 @@ function fakeContext(this: HTMLCanvasElement, type: string) {
|
||||
return {
|
||||
fillStyle: '',
|
||||
fillRect: vi.fn(),
|
||||
drawImage: vi.fn(() => drawn.push({ width: this.width, height: this.height })),
|
||||
drawImage: vi.fn((...args: unknown[]) => {
|
||||
drawCalls.push(args);
|
||||
drawn.push({ width: this.width, height: this.height });
|
||||
}),
|
||||
createLinearGradient: vi.fn(() => ({ addColorStop: (at: number, colour: string) => stops.push([at, colour]) })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -35,6 +41,8 @@ function imageResponse(type = 'image/jpeg') {
|
||||
beforeEach(() => {
|
||||
bitmapSize = { width: 1200, height: 800 };
|
||||
drawn = [];
|
||||
drawCalls = [];
|
||||
stops = [];
|
||||
inFlight = 0;
|
||||
mostInFlight = 0;
|
||||
vi.stubGlobal(
|
||||
@@ -64,19 +72,27 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('shrinkPdfImages', () => {
|
||||
it('FE-PDFIMAGES-001: a same-origin photo comes back as a JPEG with its short side at 156 px', async () => {
|
||||
it('FE-PDFIMAGES-001: a same-origin photo comes back as a JPEG with its short side at 222 px', async () => {
|
||||
const url = `${origin}/uploads/places/a.jpg`;
|
||||
const shrunk = await shrinkPdfImages([url]);
|
||||
|
||||
expect(shrunk.get(url)).toBe(JPEG);
|
||||
expect(drawn).toEqual([{ width: 234, height: 156 }]);
|
||||
expect(drawn).toEqual([{ width: 333, height: 222 }]);
|
||||
expect(HTMLCanvasElement.prototype.toDataURL).toHaveBeenCalledWith('image/jpeg', expect.any(Number));
|
||||
});
|
||||
|
||||
it('FE-PDFIMAGES-001b: a photo is decoded near thumbnail size, not in full', async () => {
|
||||
await shrinkPdfImages([`${origin}/uploads/places/a.jpg`]);
|
||||
|
||||
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 312, resizeQuality: 'medium' });
|
||||
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 444, resizeQuality: 'medium' });
|
||||
});
|
||||
|
||||
it('FE-PDFIMAGES-001c: the photo strip of a day asks for a larger copy, decoded at twice its size', async () => {
|
||||
const url = `${origin}/uploads/places/a.jpg`;
|
||||
await shrinkPdfImages([url], undefined, STRIP_PX);
|
||||
|
||||
expect(drawn).toEqual([{ width: 720, height: 480 }]);
|
||||
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 960, resizeQuality: 'medium' });
|
||||
});
|
||||
|
||||
it('FE-PDFIMAGES-002: a photo from another origin keeps its URL and is never fetched', async () => {
|
||||
@@ -135,3 +151,35 @@ describe('shrinkPdfImages', () => {
|
||||
expect(shrunk.has(url)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bakePdfCover', () => {
|
||||
it('FE-PDFIMAGES-010: the photo is cropped to the page and the shade painted into one JPEG', async () => {
|
||||
bitmapSize = { width: 4000, height: 2252 };
|
||||
const url = `${origin}/uploads/places/cover.jpg`;
|
||||
const baked = await bakePdfCover(url, [
|
||||
[0, 0.35],
|
||||
[0.92, 0.82],
|
||||
]);
|
||||
|
||||
expect(baked).toBe(JPEG);
|
||||
// Decoded at the page's height, not in full.
|
||||
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 1754, resizeQuality: 'medium' });
|
||||
// A4 at 150 dpi, the landscape photo scaled to the page height and centred.
|
||||
expect(drawn).toEqual([{ width: 1240, height: 1754 }]);
|
||||
const [, x, y, width, height] = drawCalls[0] as number[];
|
||||
expect(height).toBeCloseTo(1754, 0);
|
||||
expect(width).toBeCloseTo((4000 * 1754) / 2252, 0);
|
||||
expect(x).toBeCloseTo((1240 - width) / 2, 3);
|
||||
expect(y).toBeCloseTo(0, 3);
|
||||
expect(stops).toEqual([
|
||||
[0, 'rgba(10, 10, 14, 0.35)'],
|
||||
[0.92, 'rgba(10, 10, 14, 0.82)'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PDFIMAGES-011: a cover from another origin or one that cannot be read is left to print as before', async () => {
|
||||
expect(await bakePdfCover('https://elsewhere.example/cover.jpg', [[0, 0.5]])).toBeNull();
|
||||
expect(await bakePdfCover(`${origin}/uploads/missing.jpg`, [[0, 0.5]])).toBeNull();
|
||||
expect(drawn).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,16 +12,16 @@
|
||||
* than FETCH_TIMEOUT_MS.
|
||||
*/
|
||||
|
||||
/** The short side of a copy: three times the 52 px thumbnail, sharp at print resolution. */
|
||||
const THUMB_PX = 156;
|
||||
/** The short side of a place card's copy: three times its 74 px photo, sharp at print resolution. */
|
||||
const THUMB_PX = 222;
|
||||
/** The short side of a copy for the photo strip that opens a day, which runs the width of the page. */
|
||||
export const STRIP_PX = 480;
|
||||
const JPEG_QUALITY = 0.72;
|
||||
/**
|
||||
* Photos in flight at once: a trip of hundreds should neither queue one by one nor
|
||||
* decode all at once. Kept low for the phone, where each decode costs memory.
|
||||
*/
|
||||
const CONCURRENCY = 3;
|
||||
/** Height a photo is decoded at: twice THUMB_PX, so a portrait one still has room to shrink. */
|
||||
const DECODE_PX = THUMB_PX * 2;
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
/** Anything larger is not read into memory for a thumbnail; it keeps its URL. */
|
||||
const MAX_BYTES = 20 * 1024 * 1024;
|
||||
@@ -31,14 +31,18 @@ const MAX_BYTES = 20 * 1024 * 1024;
|
||||
* missing from the result prints as it is. Stops starting new photos once
|
||||
* `signal` aborts, and returns what it has.
|
||||
*/
|
||||
export async function shrinkPdfImages(urls: Iterable<string>, signal?: AbortSignal): Promise<Map<string, string>> {
|
||||
export async function shrinkPdfImages(
|
||||
urls: Iterable<string>,
|
||||
signal?: AbortSignal,
|
||||
shortSide = THUMB_PX
|
||||
): Promise<Map<string, string>> {
|
||||
const shrunk = new Map<string, string>();
|
||||
const queue = [...new Set(urls)].filter(isSameOrigin);
|
||||
if (queue.length === 0 || !canShrink()) return shrunk;
|
||||
|
||||
const worker = async () => {
|
||||
for (let url = queue.shift(); url !== undefined && !signal?.aborted; url = queue.shift()) {
|
||||
const copy = await shrinkImage(url, signal);
|
||||
const copy = await shrinkImage(url, shortSide, signal);
|
||||
if (copy) shrunk.set(url, copy);
|
||||
}
|
||||
};
|
||||
@@ -61,7 +65,24 @@ function canShrink(): boolean {
|
||||
return typeof createImageBitmap === 'function' && document.createElement('canvas').getContext('2d') !== null;
|
||||
}
|
||||
|
||||
async function shrinkImage(url: string, signal?: AbortSignal): Promise<string | null> {
|
||||
async function shrinkImage(url: string, shortSide: number, signal?: AbortSignal): Promise<string | null> {
|
||||
// Decoded at twice the short side, so a portrait photo still has room to shrink.
|
||||
const bitmap = await fetchBitmap(url, shortSide * 2, signal);
|
||||
if (!bitmap) return null;
|
||||
try {
|
||||
return toJpeg(bitmap, shortSide);
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The photo at `url` decoded at `height` pixels, or null when it cannot be had. Decoded
|
||||
* near the size it is drawn at: a 48 MP phone photo decoded in full holds about 190 MB,
|
||||
* which can end the web view on a phone. Browsers without the option decode in full and
|
||||
* the canvas scales down as before.
|
||||
*/
|
||||
async function fetchBitmap(url: string, height: number, signal?: AbortSignal): Promise<ImageBitmap | null> {
|
||||
// A controller and a timer rather than AbortSignal.timeout/any, which Safari only
|
||||
// has from 16 and 17.4 on; a throw there would cost the whole export.
|
||||
const fetching = new AbortController();
|
||||
@@ -73,15 +94,7 @@ async function shrinkImage(url: string, signal?: AbortSignal): Promise<string |
|
||||
if (!res.ok || Number(res.headers.get('content-length') ?? 0) > MAX_BYTES) return null;
|
||||
const blob = await res.blob();
|
||||
if (!blob.type.startsWith('image/') || blob.size > MAX_BYTES) return null;
|
||||
// Decoded near thumbnail size: a 48 MP phone photo decoded in full holds about
|
||||
// 190 MB, which can end the web view on a phone. Browsers without the option
|
||||
// decode in full and toJpeg scales down as before.
|
||||
const bitmap = await createImageBitmap(blob, { resizeHeight: DECODE_PX, resizeQuality: 'medium' });
|
||||
try {
|
||||
return toJpeg(bitmap);
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
return await createImageBitmap(blob, { resizeHeight: height, resizeQuality: 'medium' });
|
||||
} catch {
|
||||
// Offline, timed out, aborted or undecodable: the photo prints from its URL.
|
||||
return null;
|
||||
@@ -91,9 +104,58 @@ async function shrinkImage(url: string, signal?: AbortSignal): Promise<string |
|
||||
}
|
||||
}
|
||||
|
||||
/** The bitmap with its short side at THUMB_PX, or null when it is that small already. */
|
||||
function toJpeg(bitmap: ImageBitmap): string | null {
|
||||
const scale = THUMB_PX / Math.min(bitmap.width, bitmap.height);
|
||||
/** The cover page in pixels: A4 at 150 dpi, enough for a photo behind the type. */
|
||||
const COVER_W = 1240;
|
||||
const COVER_H = 1754;
|
||||
const COVER_QUALITY = 0.82;
|
||||
|
||||
/** One stop of the shade over the cover photo: how far down the page, 0 to 1, and how dark. */
|
||||
export type ShadeStop = readonly [at: number, alpha: number];
|
||||
|
||||
/**
|
||||
* The cover photo cropped to the page with its shade painted in, as one JPEG at print
|
||||
* size. A page-sized photo under a translucent gradient is composited again by every
|
||||
* viewer on every redraw, which made the first pages stutter in the preview and in the
|
||||
* saved file; one flat picture is drawn once. Null for a photo from another origin or
|
||||
* one that cannot be read: the cover then prints the photo and the shade as before.
|
||||
*/
|
||||
export async function bakePdfCover(
|
||||
url: string,
|
||||
shade: readonly ShadeStop[],
|
||||
signal?: AbortSignal
|
||||
): Promise<string | null> {
|
||||
if (!isSameOrigin(url) || !canShrink()) return null;
|
||||
const bitmap = await fetchBitmap(url, COVER_H, signal);
|
||||
if (!bitmap) return null;
|
||||
try {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = COVER_W;
|
||||
canvas.height = COVER_H;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return null;
|
||||
// Cropped the way background-size: cover crops it, around the middle.
|
||||
const scale = Math.max(COVER_W / bitmap.width, COVER_H / bitmap.height);
|
||||
const width = bitmap.width * scale;
|
||||
const height = bitmap.height * scale;
|
||||
ctx.drawImage(bitmap, (COVER_W - width) / 2, (COVER_H - height) / 2, width, height);
|
||||
const gradient = ctx.createLinearGradient(0, 0, 0, COVER_H);
|
||||
for (const [at, alpha] of shade) gradient.addColorStop(at, `rgba(10, 10, 14, ${alpha})`);
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.fillRect(0, 0, COVER_W, COVER_H);
|
||||
const baked = canvas.toDataURL('image/jpeg', COVER_QUALITY);
|
||||
return baked.startsWith('data:image/jpeg') ? baked : null;
|
||||
} catch {
|
||||
// A canvas the browser will not draw or encode (out of memory on a phone, say):
|
||||
// the cover then prints the photo and its shade as separate layers, as before.
|
||||
return null;
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** The bitmap with its short side at `shortSide`, or null when it is that small already. */
|
||||
function toJpeg(bitmap: ImageBitmap, shortSide: number): string | null {
|
||||
const scale = shortSide / Math.min(bitmap.width, bitmap.height);
|
||||
if (!Number.isFinite(scale) || scale >= 1) return null;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
/**
|
||||
* FE-PDFPREVIEW-001 to FE-PDFPREVIEW-007: the trip PDF's preview and the control
|
||||
* FE-PDFPREVIEW-001 to FE-PDFPREVIEW-009: the trip PDF's preview and the control
|
||||
* that saves it. An iPhone or iPad ignores print() in the Home Screen app, so
|
||||
* there the preview hands the export to Safari instead of offering a button that
|
||||
* does nothing.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { LARGE_TEXT_KEY, PAGE_BREAK_KEY, openPdfPreview, type PdfPreviewOptions } from './pdfPreview';
|
||||
import {
|
||||
COORDINATES_KEY,
|
||||
DETAILS_KEY,
|
||||
LARGE_TEXT_KEY,
|
||||
OVERVIEW_KEY,
|
||||
PAGE_BREAK_KEY,
|
||||
PHOTOS_KEY,
|
||||
openPdfPreview,
|
||||
type PdfPreviewOptions,
|
||||
} from './pdfPreview';
|
||||
|
||||
const tr = (key: string) => key;
|
||||
|
||||
@@ -20,6 +29,10 @@ function open(overrides: Partial<PdfPreviewOptions> = {}) {
|
||||
showTransportNotes: true,
|
||||
hasTransportNotes: false,
|
||||
largeText: false,
|
||||
photos: true,
|
||||
overview: true,
|
||||
coordinates: true,
|
||||
details: true,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
@@ -111,4 +124,43 @@ describe('openPdfPreview', () => {
|
||||
}
|
||||
expect(document.getElementById('pdf-large-text-toggle')?.getAttribute('aria-checked')).toBe('true');
|
||||
});
|
||||
|
||||
it('FE-PDFPREVIEW-008: the switches sit in a row of their own under the title and the actions', () => {
|
||||
open({ hasTransportNotes: true });
|
||||
const row = document.getElementById('pdf-settings-row');
|
||||
const ids = [...(row?.querySelectorAll('[role="switch"]') ?? [])].map((toggle) => toggle.id);
|
||||
expect(ids).toEqual([
|
||||
'pdf-daybreak-toggle',
|
||||
'pdf-large-text-toggle',
|
||||
'pdf-overview-toggle',
|
||||
'pdf-photos-toggle',
|
||||
'pdf-coordinates-toggle',
|
||||
'pdf-details-toggle',
|
||||
'pdf-transport-notes-toggle',
|
||||
]);
|
||||
// The header keeps only the title and its two actions.
|
||||
expect(row?.previousElementSibling?.querySelector('[role="switch"]')).toBeNull();
|
||||
expect(row?.previousElementSibling?.querySelector('#pdf-print-btn')).not.toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['pdf-overview-toggle', OVERVIEW_KEY, 'pdf-no-overview'],
|
||||
['pdf-photos-toggle', PHOTOS_KEY, 'pdf-no-photos'],
|
||||
['pdf-coordinates-toggle', COORDINATES_KEY, 'pdf-no-coords'],
|
||||
['pdf-details-toggle', DETAILS_KEY, 'pdf-no-details'],
|
||||
])('FE-PDFPREVIEW-009: %s hides its part of the open document at once and is remembered', (id, key, hidden) => {
|
||||
open();
|
||||
const toggle = document.getElementById(id);
|
||||
const body = document.querySelector<HTMLIFrameElement>('#pdf-preview-overlay iframe')?.contentDocument?.body;
|
||||
expect(toggle?.getAttribute('aria-checked')).toBe('true');
|
||||
|
||||
toggle?.click();
|
||||
expect(toggle?.getAttribute('aria-checked')).toBe('false');
|
||||
expect(localStorage.getItem(key)).toBe('0');
|
||||
if (body) expect(body.classList.contains(hidden)).toBe(true);
|
||||
|
||||
toggle?.click();
|
||||
expect(localStorage.getItem(key)).toBe('1');
|
||||
if (body) expect(body.classList.contains(hidden)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,6 +25,17 @@ export const TRANSPORT_NOTES_KEY = 'trek_pdf_transport_notes';
|
||||
*/
|
||||
export const LARGE_TEXT_KEY = 'trek_pdf_large_text';
|
||||
|
||||
/**
|
||||
* What the document shows besides the plan itself, each on by default and each a
|
||||
* switch in the preview: the photos of the places and stays, the overview pages
|
||||
* (route map, the days at a glance, bookings and stays), the coordinates under the
|
||||
* addresses, and the contact lines, opening hours and companions of a place.
|
||||
*/
|
||||
export const PHOTOS_KEY = 'trek_pdf_photos';
|
||||
export const OVERVIEW_KEY = 'trek_pdf_overview';
|
||||
export const COORDINATES_KEY = 'trek_pdf_coordinates';
|
||||
export const DETAILS_KEY = 'trek_pdf_details';
|
||||
|
||||
/* The overlay is imperative DOM, so the switch from Settings/ToggleSwitch is
|
||||
rebuilt here rather than rendered — as static markup it would carry no
|
||||
behaviour. Same geometry and the same tokens, so it reads as the same control. */
|
||||
@@ -52,6 +63,10 @@ export interface PdfPreviewOptions {
|
||||
/** The transport-notes switch only shows when there is a note to hide. */
|
||||
hasTransportNotes: boolean;
|
||||
largeText: boolean;
|
||||
photos: boolean;
|
||||
overview: boolean;
|
||||
coordinates: boolean;
|
||||
details: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -84,6 +99,10 @@ export function openPdfPreview({
|
||||
showTransportNotes,
|
||||
hasTransportNotes,
|
||||
largeText,
|
||||
photos,
|
||||
overview,
|
||||
coordinates,
|
||||
details,
|
||||
}: PdfPreviewOptions): void {
|
||||
// Open in modal with srcdoc iframe (no URL loading = no X-Frame-Options issue)
|
||||
const overlay = document.createElement('div');
|
||||
@@ -104,10 +123,7 @@ export function openPdfPreview({
|
||||
'display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;padding:10px 16px;border-bottom:1px solid var(--border-primary);flex-shrink:0;';
|
||||
header.innerHTML = `
|
||||
<span style="font-size:13px;font-weight:600;color:var(--text-primary);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escapeHtml(title)}</span>
|
||||
<div style="display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:8px">
|
||||
${hasTransportNotes ? previewSwitch('pdf-transport-notes-toggle', tr('pdf.transportNotes'), showTransportNotes) : ''}
|
||||
${previewSwitch('pdf-daybreak-toggle', tr('pdf.pageBreakPerDay'), breaksPerDay)}
|
||||
${previewSwitch('pdf-large-text-toggle', tr('pdf.largeText'), largeText)}
|
||||
<div style="display:flex;align-items:center;justify-content:flex-end;gap:8px">
|
||||
${save.html}
|
||||
<button type="button" id="pdf-close-btn" style="background:none;border:none;cursor:pointer;color:var(--text-faint);display:flex;padding:4px;border-radius:6px">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
@@ -115,6 +131,23 @@ export function openPdfPreview({
|
||||
</div>
|
||||
`;
|
||||
|
||||
// The document's switches in a row of their own under the header: the layout first,
|
||||
// then what it shows, so the header keeps only the title and the actions.
|
||||
const settings = document.createElement('div');
|
||||
settings.id = 'pdf-settings-row';
|
||||
settings.style.cssText =
|
||||
'display:flex;align-items:center;flex-wrap:wrap;gap:8px 18px;padding:8px 16px;border-bottom:1px solid var(--border-primary);background:var(--bg-secondary);flex-shrink:0;';
|
||||
settings.innerHTML = [
|
||||
previewSwitch('pdf-daybreak-toggle', tr('pdf.pageBreakPerDay'), breaksPerDay),
|
||||
previewSwitch('pdf-large-text-toggle', tr('pdf.largeText'), largeText),
|
||||
'<span aria-hidden="true" style="width:1px;align-self:stretch;background:var(--border-primary)"></span>',
|
||||
previewSwitch('pdf-overview-toggle', tr('pdf.showOverview'), overview),
|
||||
previewSwitch('pdf-photos-toggle', tr('pdf.showPhotos'), photos),
|
||||
previewSwitch('pdf-coordinates-toggle', tr('collections.coordinates'), coordinates),
|
||||
previewSwitch('pdf-details-toggle', tr('pdf.showDetails'), details),
|
||||
hasTransportNotes ? previewSwitch('pdf-transport-notes-toggle', tr('pdf.transportNotes'), showTransportNotes) : '',
|
||||
].join('');
|
||||
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.style.cssText = 'flex:1;width:100%;border:none;';
|
||||
// No script runs inside the document (print is parent-initiated), so withhold
|
||||
@@ -123,6 +156,7 @@ export function openPdfPreview({
|
||||
iframe.srcdoc = html;
|
||||
|
||||
card.appendChild(header);
|
||||
card.appendChild(settings);
|
||||
if (save.hint) {
|
||||
const hint = document.createElement('p');
|
||||
hint.id = 'pdf-safari-hint';
|
||||
@@ -145,18 +179,18 @@ export function openPdfPreview({
|
||||
|
||||
// Each choice differs by one class on <body>, so switching is instant in the
|
||||
// preview and there is no need to re-fetch photos or rebuild the document.
|
||||
wirePreviewSwitch(header, 'pdf-daybreak-toggle', (on) => {
|
||||
rememberPdfSwitch(PAGE_BREAK_KEY, on);
|
||||
iframe.contentDocument?.body.classList.toggle('pdf-flow', !on);
|
||||
});
|
||||
wirePreviewSwitch(header, 'pdf-transport-notes-toggle', (on) => {
|
||||
rememberPdfSwitch(TRANSPORT_NOTES_KEY, on);
|
||||
iframe.contentDocument?.body.classList.toggle('pdf-no-transport-notes', !on);
|
||||
});
|
||||
wirePreviewSwitch(header, 'pdf-large-text-toggle', (on) => {
|
||||
rememberPdfSwitch(LARGE_TEXT_KEY, on);
|
||||
iframe.contentDocument?.body.classList.toggle('pdf-large-text', on);
|
||||
});
|
||||
const bodyClass = (id: string, key: string, className: string, addWhenOn: boolean) =>
|
||||
wirePreviewSwitch(settings, id, (on) => {
|
||||
rememberPdfSwitch(key, on);
|
||||
iframe.contentDocument?.body.classList.toggle(className, addWhenOn ? on : !on);
|
||||
});
|
||||
bodyClass('pdf-daybreak-toggle', PAGE_BREAK_KEY, 'pdf-flow', false);
|
||||
bodyClass('pdf-transport-notes-toggle', TRANSPORT_NOTES_KEY, 'pdf-no-transport-notes', false);
|
||||
bodyClass('pdf-large-text-toggle', LARGE_TEXT_KEY, 'pdf-large-text', true);
|
||||
bodyClass('pdf-overview-toggle', OVERVIEW_KEY, 'pdf-no-overview', false);
|
||||
bodyClass('pdf-photos-toggle', PHOTOS_KEY, 'pdf-no-photos', false);
|
||||
bodyClass('pdf-coordinates-toggle', COORDINATES_KEY, 'pdf-no-coords', false);
|
||||
bodyClass('pdf-details-toggle', DETAILS_KEY, 'pdf-no-details', false);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildTripMapSvg } from './tripMapSvg'
|
||||
import { buildTripMapSvg, drawnPoints } from './tripMapSvg'
|
||||
import type { TripOverviewDay } from '../Map/tripRouteGeometry'
|
||||
|
||||
const day = (over: Partial<TripOverviewDay> = {}): TripOverviewDay => ({
|
||||
@@ -78,3 +78,25 @@ describe('buildTripMapSvg', () => {
|
||||
expect(svg).toContain('width="720"')
|
||||
})
|
||||
})
|
||||
|
||||
// A routed road carries a point every few metres; drawn as it came, a trip map held
|
||||
// tens of thousands of them and stuttered in every viewer.
|
||||
describe('drawnPoints', () => {
|
||||
// One degree is one map pixel, so the tolerance reads in degrees here.
|
||||
const flat = (lat: number, lng: number): [number, number] => [lng, -lat]
|
||||
|
||||
it('FE-PDF-MAPSVG-020: a dense straight road keeps only its ends', () => {
|
||||
const road = Array.from({ length: 5000 }, (_, i) => [0, i / 10] as [number, number])
|
||||
expect(drawnPoints(road, flat)).toBe('0,0 499.9,0')
|
||||
})
|
||||
|
||||
it('FE-PDF-MAPSVG-021: a turn is kept, a wobble under the tolerance is not', () => {
|
||||
const road: [number, number][] = [[0, 0], [-0.1, 50], [0, 100], [-60, 100], [-0.2, 100.1]]
|
||||
expect(drawnPoints(road, flat)).toBe('0,0 100,0 100,60 100.1,0.2')
|
||||
})
|
||||
|
||||
it('FE-PDF-MAPSVG-022: points that round onto the same pixel are drawn once', () => {
|
||||
const road: [number, number][] = [[0, 0], [0, 0.01], [0, 0.02], [0, 0.04]]
|
||||
expect(drawnPoints(road, flat)).toBe('0,0')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -125,6 +125,55 @@ export interface RouteOverlayOptions {
|
||||
formatDistance: (km: number) => string
|
||||
}
|
||||
|
||||
/** How far, in map pixels, a point may sit off the line its neighbours make before it is kept. */
|
||||
const SIMPLIFY_TOLERANCE = 0.35
|
||||
|
||||
/**
|
||||
* A run projected onto the map and thinned for drawing. A routed road carries a point
|
||||
* every few metres: at the scale of a trip map that is tens of thousands of points, most
|
||||
* rounding onto the same pixel, each drawn twice (casing and line) and drawn again by
|
||||
* every viewer on every scroll, which made the page stutter. Points that round onto the
|
||||
* one before are dropped, then every point closer than SIMPLIFY_TOLERANCE to the line
|
||||
* through the points kept around it (Douglas-Peucker). The shape on paper is the same.
|
||||
*/
|
||||
export function drawnPoints(line: [number, number][], project: (lat: number, lng: number) => [number, number]): string {
|
||||
const round = (n: number) => Math.round(n * 10) / 10
|
||||
const pts: [number, number][] = []
|
||||
for (const [lat, lng] of line) {
|
||||
const [x, y] = project(lat, lng)
|
||||
const point: [number, number] = [round(x), round(y)]
|
||||
const prev = pts[pts.length - 1]
|
||||
if (!prev || prev[0] !== point[0] || prev[1] !== point[1]) pts.push(point)
|
||||
}
|
||||
const keep = new Uint8Array(pts.length)
|
||||
keep[0] = 1
|
||||
keep[pts.length - 1] = 1
|
||||
const ranges: [number, number][] = [[0, pts.length - 1]]
|
||||
for (let range = ranges.pop(); range; range = ranges.pop()) {
|
||||
const [from, to] = range
|
||||
if (to - from < 2) continue
|
||||
const [ax, ay] = pts[from]
|
||||
const [bx, by] = pts[to]
|
||||
const dx = bx - ax
|
||||
const dy = by - ay
|
||||
const length = Math.hypot(dx, dy)
|
||||
let farthest = -1
|
||||
let distance = 0
|
||||
for (let i = from + 1; i < to; i++) {
|
||||
const [px, py] = pts[i]
|
||||
const d = length === 0 ? Math.hypot(px - ax, py - ay) : Math.abs(dy * px - dx * py + bx * ay - by * ax) / length
|
||||
if (d > distance) {
|
||||
distance = d
|
||||
farthest = i
|
||||
}
|
||||
}
|
||||
if (farthest < 0 || distance <= SIMPLIFY_TOLERANCE) continue
|
||||
keep[farthest] = 1
|
||||
ranges.push([from, farthest], [farthest, to])
|
||||
}
|
||||
return pts.filter((_, i) => keep[i]).map(p => p.join(',')).join(' ')
|
||||
}
|
||||
|
||||
/**
|
||||
* The routes, their stops and the scale bar — everything drawn *over* the ground.
|
||||
*
|
||||
@@ -138,7 +187,7 @@ export function buildRouteOverlay(days: TripOverviewDay[], opts: RouteOverlayOpt
|
||||
const drawn = days.filter(d => [...d.lines, ...(d.tourLines ?? [])].some(line => line.length > 1))
|
||||
|
||||
const routes = drawn.flatMap(day => day.lines.filter(l => l.length > 1).map(line => {
|
||||
const pts = line.map(([lat, lng]) => project(lat, lng).map(round).join(',')).join(' ')
|
||||
const pts = drawnPoints(line, project)
|
||||
// The day's own darkened casing rather than a flat white one: it is what keeps a
|
||||
// warm colour readable over water and forest, and it matches what the map draws.
|
||||
return `<polyline points="${pts}" fill="none" stroke="${strokeColour(day.color.casing)}" stroke-width="5.5" stroke-linecap="round" stroke-linejoin="round"/>`
|
||||
@@ -147,7 +196,7 @@ export function buildRouteOverlay(days: TripOverviewDay[], opts: RouteOverlayOpt
|
||||
|
||||
// Where each run starts and ends — the stops, rather than every vertex of the road.
|
||||
const tours = drawn.flatMap(day => (day.tourLines ?? []).filter(line => line.length > 1).map(line => {
|
||||
const pts = line.map(([lat, lng]) => project(lat, lng).map(round).join(',')).join(' ')
|
||||
const pts = drawnPoints(line, project)
|
||||
return `<polyline points="${pts}" fill="none" stroke="#ffffff" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>`
|
||||
+ `<polyline points="${pts}" fill="none" stroke="#14805e" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/>`
|
||||
}))
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
/**
|
||||
* FE-PDFDAY-001 to FE-PDFDAY-012: one day of the trip PDF, built piece by piece.
|
||||
* The whole export is covered by TripPDF.test.ts; these pin what each card prints
|
||||
* from the data it is given, the trip's full place included.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { Accommodation, Assignment, Category, Day, DayNote, Place } from '../../types';
|
||||
import { dayHeader, noteItem, photoStrip, placeItem, staysBlock, type PdfDayContext } from './tripPdfDay';
|
||||
|
||||
const day = { id: 10, day_number: 3, title: 'Kyoto', date: '2026-05-06' } as Day; // a Wednesday
|
||||
|
||||
const category = { id: 4, name: 'Temple', icon: 'landmark', color: '#c2410c' } as Category;
|
||||
|
||||
/** Monday first, like the stored week; Wednesday has hours, Thursday is closed. */
|
||||
const week = JSON.stringify([
|
||||
{ closed: false, open: '08:00', close: '18:00' },
|
||||
{ closed: false, open: '08:00', close: '18:00' },
|
||||
{ closed: false, open: '09:00', close: '17:30' },
|
||||
{ closed: true },
|
||||
{ closed: false, open: '08:00', close: '18:00' },
|
||||
{ closed: false, open: '08:00', close: '18:00' },
|
||||
{ closed: false, open: '08:00', close: '18:00' },
|
||||
]);
|
||||
|
||||
const fullPlace = {
|
||||
id: 7,
|
||||
name: 'Kiyomizu-dera',
|
||||
category_id: 4,
|
||||
address: '1 Chome-294 Kiyomizu, Kyoto',
|
||||
lat: 34.994856,
|
||||
lng: 135.785046,
|
||||
rating_avg: 4.64,
|
||||
rating_count: 12,
|
||||
email: 'info@kiyomizudera.or.jp',
|
||||
phone: '+81 75-551-1234',
|
||||
website: 'https://www.kiyomizudera.or.jp/en/',
|
||||
opening_hours: week,
|
||||
reservation_notes: 'Tickets at the west gate',
|
||||
tags: [{ name: 'Must see', color: '#16a34a' }],
|
||||
} as unknown as Place;
|
||||
|
||||
function context(over: Partial<PdfDayContext> = {}): PdfDayContext {
|
||||
return {
|
||||
tr: (key, params) => (params ? `${key}:${JSON.stringify(params)}` : key),
|
||||
fmtTime: (value) => value ?? '',
|
||||
locale: 'en-US',
|
||||
tripCurrency: 'JPY',
|
||||
categories: [category],
|
||||
placesById: new Map([[fullPlace.id, fullPlace]]),
|
||||
photoOf: () => null,
|
||||
markdown: (text) => `<p>${text}</p>`,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
/** The assignment as the API hands it over: a projection of its place, without the rating, e-mail or hours. */
|
||||
function assignment(over: Record<string, unknown> = {}): Assignment {
|
||||
return {
|
||||
id: 200,
|
||||
day_id: 10,
|
||||
order_index: 0,
|
||||
notes: 'Go early',
|
||||
participants: [
|
||||
{ user_id: 1, username: 'mia' },
|
||||
{ user_id: 2, username: 'leo' },
|
||||
],
|
||||
place: {
|
||||
id: 7,
|
||||
name: 'Kiyomizu-dera',
|
||||
category_id: 4,
|
||||
address: '1 Chome-294 Kiyomizu, Kyoto',
|
||||
lat: 34.994856,
|
||||
lng: 135.785046,
|
||||
place_time: '09:30',
|
||||
end_time: '11:00',
|
||||
duration_minutes: 90,
|
||||
price: 500,
|
||||
currency: null,
|
||||
description: 'Wooden **stage** over the hill',
|
||||
notes: null,
|
||||
tags: [{ name: 'Must see', color: '#16a34a' }],
|
||||
...over,
|
||||
},
|
||||
} as unknown as Assignment;
|
||||
}
|
||||
|
||||
const parse = (html: string) => new DOMParser().parseFromString(html, 'text/html');
|
||||
const texts = (doc: Document, selector: string) =>
|
||||
[...doc.querySelectorAll(selector)].map((el) => el.textContent?.replace(/\s+/g, ' ').trim());
|
||||
|
||||
describe('placeItem', () => {
|
||||
it('FE-PDFDAY-001: prints the stop with its number, times, facts, address and coordinates', () => {
|
||||
const doc = parse(placeItem(assignment(), 2, day, context()));
|
||||
|
||||
expect(texts(doc, '.tl-marker')).toEqual(['2']);
|
||||
expect(texts(doc, '.tl-start')).toEqual(['09:30']);
|
||||
expect(texts(doc, '.tl-end')).toEqual(['11:00']);
|
||||
expect(texts(doc, '.place-name')).toEqual(['Kiyomizu-dera']);
|
||||
expect(texts(doc, '.cat-badge')).toEqual(['Temple']);
|
||||
const facts = texts(doc, '.facts .chip');
|
||||
expect(facts[0]).toBe('1 h 30 min');
|
||||
expect(facts[1]).toMatch(/500/);
|
||||
expect(facts.slice(2)).toEqual(['4.6 (12)', 'Must see']);
|
||||
expect(texts(doc, '.info-row .info-text')).toEqual(['1 Chome-294 Kiyomizu, Kyoto', '34.99486, 135.78505']);
|
||||
expect(doc.querySelector('.coords')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PDFDAY-002: reads the rating, e-mail, hours and reservation note off the trip place', () => {
|
||||
const doc = parse(placeItem(assignment(), 1, day, context()));
|
||||
|
||||
// The day is a Wednesday: its hours, not Monday's.
|
||||
expect(texts(doc, '.details .detail')).toEqual([
|
||||
'inspector.openingHours 09:00 – 17:30',
|
||||
'+81 75-551-1234',
|
||||
'kiyomizudera.or.jp',
|
||||
'info@kiyomizudera.or.jp',
|
||||
'inspector.participants: mia, leo',
|
||||
]);
|
||||
expect(texts(doc, '.place-note')).toEqual(['Tickets at the west gate', 'Go early']);
|
||||
expect(doc.querySelector('.place-text')?.innerHTML).toBe('<p>Wooden **stage** over the hill</p>');
|
||||
});
|
||||
|
||||
it('FE-PDFDAY-003: a day the place is closed says so', () => {
|
||||
const thursday = { ...day, date: '2026-05-07' } as Day;
|
||||
const doc = parse(placeItem(assignment(), 1, thursday, context()));
|
||||
|
||||
expect(texts(doc, '.details .detail')[0]).toBe('inspector.openingHours inspector.closed');
|
||||
});
|
||||
|
||||
it('FE-PDFDAY-004: a place with neither photo nor extras prints its category tile and nothing empty', () => {
|
||||
const bare = {
|
||||
id: 201,
|
||||
day_id: 10,
|
||||
order_index: 0,
|
||||
place: { id: 99, name: 'Corner shop', category_id: 4, lat: null, lng: null },
|
||||
} as unknown as Assignment;
|
||||
const doc = parse(placeItem(bare, 1, { ...day, date: null } as Day, context()));
|
||||
|
||||
expect(doc.querySelector('.place-thumb-fallback')).not.toBeNull();
|
||||
expect(doc.querySelector('.place-card')?.getAttribute('style')).toBe('--cat:#c2410c');
|
||||
for (const empty of ['.facts', '.info-row', '.details', '.place-note', '.place-text', '.tl-start', '.tl-end']) {
|
||||
expect(doc.querySelector(empty)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-PDFDAY-005: the photo the export picked prints, and a hostile name and tag colour stay inert', () => {
|
||||
const hostile = assignment({
|
||||
name: '<img src=x onerror=alert(1)>',
|
||||
tags: [{ name: 'x', color: 'red;background:url(x)' }],
|
||||
});
|
||||
const html = placeItem(hostile, 1, day, context({ photoOf: () => 'data:image/jpeg;base64,AAA' }));
|
||||
const doc = parse(html);
|
||||
|
||||
expect(doc.querySelector('img.place-thumb')?.getAttribute('src')).toBe('data:image/jpeg;base64,AAA');
|
||||
expect(doc.querySelectorAll('img')).toHaveLength(1);
|
||||
expect(texts(doc, '.place-name')).toEqual(['<img src=x onerror=alert(1)>']);
|
||||
expect(doc.querySelector('.chip-tag')?.getAttribute('style')).toBe('--tag:#6b6b75');
|
||||
});
|
||||
});
|
||||
|
||||
describe('noteItem', () => {
|
||||
it('FE-PDFDAY-006: a coloured note carries its colour as the edge, an unknown colour none', () => {
|
||||
const note = {
|
||||
id: 1,
|
||||
day_id: 10,
|
||||
text: 'Buy <tickets>',
|
||||
time: '08:00',
|
||||
icon: 'Ticket',
|
||||
color: '#2563eb',
|
||||
} as DayNote;
|
||||
const tinted = parse(noteItem(note));
|
||||
expect(tinted.querySelector('.note-card')?.className).toBe('note-card note-tinted');
|
||||
expect(tinted.querySelector('.note-card')?.getAttribute('style')).toBe('--note:#2563eb');
|
||||
expect(texts(tinted, '.note-text')).toEqual(['Buy <tickets>']);
|
||||
// The note's time field is its free second line, kept in the card, not a clock.
|
||||
expect(texts(tinted, '.note-time')).toEqual(['08:00']);
|
||||
expect(tinted.querySelector('.tl-start')).toBeNull();
|
||||
|
||||
const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote));
|
||||
expect(plain.querySelector('.note-card')?.className).toBe('note-card');
|
||||
expect(plain.querySelector('.note-time')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('staysBlock', () => {
|
||||
const stay = {
|
||||
id: 1,
|
||||
start_day_id: 10,
|
||||
end_day_id: 12,
|
||||
place_name: 'Hotel Gion',
|
||||
place_address: 'Gion 1',
|
||||
check_in: '15:00',
|
||||
check_out: '10:00',
|
||||
confirmation: 'HX-42',
|
||||
notes: 'Late arrival',
|
||||
place_image: null,
|
||||
} as unknown as Accommodation;
|
||||
|
||||
it('FE-PDFDAY-007: the arrival day gets the full card with time, address, notes and code', () => {
|
||||
const doc = parse(staysBlock([stay], day, context()));
|
||||
|
||||
expect(doc.querySelector('.day-accommodations')?.className).toBe('day-accommodations single');
|
||||
expect(texts(doc, '.stay-kicker')).toEqual(['reservations.meta.checkIn 15:00']);
|
||||
expect(texts(doc, '.stay-name')).toEqual(['Hotel Gion']);
|
||||
expect(texts(doc, '.stay-line')).toEqual(['Gion 1', 'Late arrival']);
|
||||
expect(texts(doc, '.code-chip')).toEqual(['HX-42']);
|
||||
});
|
||||
|
||||
it('FE-PDFDAY-008: a night in between is one quiet line, the leaving day the check-out', () => {
|
||||
const middle = parse(staysBlock([stay], { ...day, id: 11 } as Day, context()));
|
||||
expect(middle.querySelector('.stay-quiet')).not.toBeNull();
|
||||
expect(texts(middle, '.stay-kicker')).toEqual(['reservations.meta.linkAccommodation']);
|
||||
expect(middle.querySelector('.stay-line')).toBeNull();
|
||||
|
||||
const leaving = parse(staysBlock([stay], { ...day, id: 12 } as Day, context()));
|
||||
expect(texts(leaving, '.stay-kicker')).toEqual(['reservations.meta.checkOut 10:00']);
|
||||
expect(leaving.querySelector('.code-chip')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PDFDAY-009: no stay prints nothing, two drop the single-column class', () => {
|
||||
expect(staysBlock([], day, context())).toBe('');
|
||||
const doc = parse(staysBlock([stay, { ...stay, id: 2, place_name: 'Ryokan' } as Accommodation], day, context()));
|
||||
expect(doc.querySelector('.day-accommodations')?.className).toBe('day-accommodations');
|
||||
});
|
||||
});
|
||||
|
||||
describe('dayHeader', () => {
|
||||
it('FE-PDFDAY-010: the number, date and title, with only the figures the day has', () => {
|
||||
const doc = parse(dayHeader(day, { stops: 4, distance: '12 km', cost: '¥3,000' }, context()));
|
||||
|
||||
expect(texts(doc, '.day-tag-lbl')).toEqual(['pdf.day']);
|
||||
expect(texts(doc, '.day-tag-num')).toEqual(['3']);
|
||||
expect(texts(doc, '.day-date')[0]).toMatch(/May/);
|
||||
expect(texts(doc, '.day-title')).toEqual(['Kyoto']);
|
||||
expect(texts(doc, '.meta-pill, .day-cost')).toEqual(['4', '12 km', '¥3,000']);
|
||||
|
||||
const untitled = parse(
|
||||
dayHeader({ ...day, title: null, date: null } as Day, { stops: 0, distance: null, cost: null }, context())
|
||||
);
|
||||
expect(texts(untitled, '.day-title')).toEqual(['dayplan.dayN:{"n":3}']);
|
||||
expect(untitled.querySelector('.day-date')).toBeNull();
|
||||
expect(untitled.querySelector('.day-meta')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('photoStrip', () => {
|
||||
it('FE-PDFDAY-011: up to three photos, each named on its label; none prints nothing', () => {
|
||||
expect(photoStrip([])).toBe('');
|
||||
const doc = parse(
|
||||
photoStrip([
|
||||
{ url: 'https://a.example/1.jpg', caption: 'Gate <one>' },
|
||||
{ url: 'https://a.example/2.jpg', caption: 'Stage' },
|
||||
])
|
||||
);
|
||||
|
||||
expect(doc.querySelector('.day-strip')?.className).toBe('day-strip day-strip-2');
|
||||
expect(texts(doc, '.glass-label')).toEqual(['Gate <one>', 'Stage']);
|
||||
expect([...doc.querySelectorAll('img')].map((img) => img.getAttribute('src'))).toEqual([
|
||||
'https://a.example/1.jpg',
|
||||
'https://a.example/2.jpg',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,434 @@
|
||||
import { parsePlaceHours } from '@trek/shared';
|
||||
|
||||
import type { Accommodation, Assignment, Category, Day, DayNote, Place, Reservation } from '../../types';
|
||||
import { getDisplayTimeForDay, getSpanPhase } from '../../utils/dayMerge';
|
||||
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../utils/flightLegs';
|
||||
import { formatMoney, splitReservationDateTime } from '../../utils/formatters';
|
||||
import type { TransportLegDetail } from '../Planner/transportDetailModel';
|
||||
import { escHtml, hexColour, safeImg, shortDate, websiteHost } from './tripPdfHtml';
|
||||
import { bookingIcon, bookingTint, categoryIcon, glyph, noteIcon } from './tripPdfIcons';
|
||||
|
||||
/*
|
||||
* One day of the trip PDF: its header, where the night is spent, and the day's plan
|
||||
* as a timeline, times on the left, a rail in the day's colour, and a card for every
|
||||
* stop, booking and note.
|
||||
*/
|
||||
|
||||
type Translate = (key: string, params?: Record<string, string | number>) => string;
|
||||
|
||||
/** A booking as the day merge hands it over, a leg of a multi-leg booking included. */
|
||||
export type PdfBooking = Reservation & { __leg?: TransportLegDetail & { total?: number } };
|
||||
|
||||
/** What the day's markup needs from the export around it. */
|
||||
export interface PdfDayContext {
|
||||
tr: Translate;
|
||||
fmtTime: (value?: string | null) => string;
|
||||
locale: string | undefined;
|
||||
tripCurrency: string;
|
||||
categories: readonly Category[];
|
||||
/** The trip's full places by id: an assignment carries only a projection of its place. */
|
||||
placesById: ReadonlyMap<number, Place>;
|
||||
/** The picture to print for a place, already shrunk where it could be; null for none. */
|
||||
photoOf: (place: Assignment['place']) => string | null;
|
||||
/** A place's description or notes as sanitized markdown. */
|
||||
markdown: (text: string) => string;
|
||||
}
|
||||
|
||||
const NEUTRAL = '#6b6b75';
|
||||
|
||||
function metadataOf(r: PdfBooking): Record<string, unknown> {
|
||||
if (!r.metadata) return {};
|
||||
try {
|
||||
const parsed: unknown = typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata;
|
||||
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
const text = (value: unknown): string => (typeof value === 'string' || typeof value === 'number' ? String(value) : '');
|
||||
|
||||
/** "1 h 30 min", or null for no duration at all. */
|
||||
function durationLabel(minutes: number | null | undefined): string | null {
|
||||
if (typeof minutes !== 'number' || !Number.isFinite(minutes) || minutes <= 0) return null;
|
||||
const whole = Math.round(minutes);
|
||||
const h = Math.floor(whole / 60);
|
||||
const m = whole % 60;
|
||||
if (h === 0) return `${m} min`;
|
||||
return m === 0 ? `${h} h` : `${h} h ${m} min`;
|
||||
}
|
||||
|
||||
function timeColumn(start: string, end: string): string {
|
||||
return `<div class="tl-time">${start ? `<span class="tl-start">${escHtml(start)}</span>` : ''}${
|
||||
end ? `<span class="tl-end">${escHtml(end)}</span>` : ''
|
||||
}</div>`;
|
||||
}
|
||||
|
||||
function item(kind: string, time: string, marker: string, body: string, style = ''): string {
|
||||
return `<li class="tl-item tl-${kind}"${style ? ` style="${style}"` : ''}>${time}<div class="tl-rail"><span class="tl-marker">${marker}</span></div><div class="tl-body">${body}</div></li>`;
|
||||
}
|
||||
|
||||
// ── Bookings ──────────────────────────────────────────────────────────────
|
||||
|
||||
/** "Departure", "Pick-up" and the like, for a booking that spans days; null on its single day. */
|
||||
function spanLabel(r: PdfBooking, phase: string, tr: Translate): string | null {
|
||||
if (phase === 'single') return null;
|
||||
// Each key spelled out, so the key check can follow every branch to its string.
|
||||
const start = phase === 'start';
|
||||
const end = phase === 'end';
|
||||
if (r.type === 'flight') return tr(`reservations.span.${start ? 'departure' : end ? 'arrival' : 'inTransit'}`);
|
||||
if (r.type === 'car') return tr(`reservations.span.${start ? 'pickup' : end ? 'return' : 'active'}`);
|
||||
// Parking reuses span.pickup for its end day: you drop the car off and collect it
|
||||
// again later, so the rental car's wording carries over without a second key.
|
||||
if (r.type === 'parking') return tr(`reservations.span.${start ? 'dropOff' : end ? 'pickup' : 'ongoing'}`);
|
||||
return tr(`reservations.span.${start ? 'start' : end ? 'end' : 'ongoing'}`);
|
||||
}
|
||||
|
||||
function stopsOf(r: PdfBooking, label: 'code' | 'name'): string[] {
|
||||
return (r.endpoints || [])
|
||||
.slice()
|
||||
.sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
|
||||
.map((e) => (label === 'code' ? e.code || e.name : e.name) || '')
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/** One line under a booking's title: the way it goes, its facts as badges and its own booking code. */
|
||||
interface BookingLine {
|
||||
route: string;
|
||||
facts: string[];
|
||||
code: string;
|
||||
/** A table's party size, printed with the people icon so it needs no word. */
|
||||
people?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The lines under a booking's title. A multi-leg flight or train gets one per leg, each
|
||||
* with its own number and booking code, since that is the code the gate asks for
|
||||
* (#1943); a leg row prints its own leg; everything else gets one line or none.
|
||||
*/
|
||||
function bookingLines(r: PdfBooking, tr: Translate): BookingLine[] {
|
||||
const meta = metadataOf(r);
|
||||
const route = (from?: string | null, to?: string | null) =>
|
||||
from || to ? [from, to].filter(Boolean).join(' → ') : '';
|
||||
const seat = (value: unknown) => (text(value) ? `${tr('reservations.meta.seat')} ${text(value)}` : '');
|
||||
const platform = (value: unknown) => (text(value) ? `${tr('reservations.meta.platform')} ${text(value)}` : '');
|
||||
const line = (way: string, facts: unknown[], code: unknown = ''): BookingLine => ({
|
||||
route: way,
|
||||
facts: facts.map(text).filter(Boolean),
|
||||
code: text(code),
|
||||
});
|
||||
const filled = (lines: BookingLine[]) => lines.filter((l) => l.route || l.facts.length || l.code);
|
||||
|
||||
if (r.__leg) {
|
||||
const l = r.__leg;
|
||||
const source = (usesStationRoute(r.type) ? getTrainLegs(r) : getFlightLegs(r))[l.index];
|
||||
return filled([
|
||||
line(
|
||||
route(l.from, l.to),
|
||||
[l.airline, l.flight_number, l.train_number, platform(l.platform), seat(l.seat)],
|
||||
source?.confirmation_number
|
||||
),
|
||||
]);
|
||||
}
|
||||
if (r.type === 'flight') {
|
||||
const legs = getFlightLegs(r);
|
||||
if (legs.length > 1) {
|
||||
return filled(
|
||||
legs.map((l) => line(route(l.from, l.to), [l.airline, l.flight_number, seat(l.seat)], l.confirmation_number))
|
||||
);
|
||||
}
|
||||
const stops = stopsOf(r, 'code');
|
||||
const way = stops.length >= 2 ? stops.join(' → ') : route(text(meta.departure_airport), text(meta.arrival_airport));
|
||||
return filled([line(way, [meta.airline, meta.flight_number, seat(meta.seat)])]);
|
||||
}
|
||||
if (r.type === 'train') {
|
||||
const legs = getTrainLegs(r);
|
||||
if (legs.length > 1) {
|
||||
return filled(
|
||||
legs.map((l) =>
|
||||
line(route(l.from, l.to), [l.train_number, platform(l.platform), seat(l.seat)], l.confirmation_number)
|
||||
)
|
||||
);
|
||||
}
|
||||
const stops = stopsOf(r, 'code');
|
||||
return filled([
|
||||
line(stops.length >= 2 ? stops.join(' → ') : '', [meta.train_number, platform(meta.platform), seat(meta.seat)]),
|
||||
]);
|
||||
}
|
||||
if (r.type === 'car') {
|
||||
// A rental with stops is a drive, and the printout is what people take into the car
|
||||
// (#1797). Consecutive repeats collapse, and a chain of one place is no route: the
|
||||
// ordinary rental is picked up and returned at the same desk.
|
||||
const stops = stopsOf(r, 'name').filter((name, i, all) => name !== all[i - 1]);
|
||||
return new Set(stops).size >= 2 ? [line(stops.join(' → '), [])] : [];
|
||||
}
|
||||
if (r.type === 'restaurant') return text(meta.party_size) ? [{ ...line('', []), people: text(meta.party_size) }] : [];
|
||||
if (r.type === 'event') return filled([line('', [meta.venue])]);
|
||||
if (r.type === 'tour') return filled([line('', [meta.operator])]);
|
||||
return [];
|
||||
}
|
||||
|
||||
function bookingLineHtml(l: BookingLine): string {
|
||||
return `<div class="note-line">${l.route ? `<span class="route">${escHtml(l.route)}</span>` : ''}${
|
||||
l.people ? `<span class="chip">${glyph('people', 9)}${escHtml(l.people)}</span>` : ''
|
||||
}${l.facts
|
||||
.map((fact) => `<span class="chip">${escHtml(fact)}</span>`)
|
||||
.join('')}${l.code ? `<span class="code-chip">${glyph('key', 9)}${escHtml(l.code)}</span>` : ''}</div>`;
|
||||
}
|
||||
|
||||
/** A booking's lines on their own, for the booking list of the overview. */
|
||||
export function bookingLinesHtml(r: PdfBooking, tr: Translate): string {
|
||||
return bookingLines(r, tr).map(bookingLineHtml).join('');
|
||||
}
|
||||
|
||||
/** A booking on the day's timeline. Sets `flags.transportNote` when it prints a note. */
|
||||
export function bookingItem(r: PdfBooking, day: Day, ctx: PdfDayContext, flags: { transportNote: boolean }): string {
|
||||
const { tr, fmtTime } = ctx;
|
||||
const phase = getSpanPhase(r, day.id);
|
||||
const span = spanLabel(r, phase, tr);
|
||||
// Start and end the way the day plan draws them (#1310). The landing time only on a
|
||||
// booking that begins and ends this day: across a span the arrival belongs to the
|
||||
// arrival day, which shows it as its own time.
|
||||
const start = fmtTime(splitReservationDateTime(getDisplayTimeForDay(r, day.id)).time);
|
||||
const end = phase === 'single' ? fmtTime(splitReservationDateTime(r.reservation_end_time).time) : '';
|
||||
const note = typeof r.notes === 'string' ? r.notes.trim() : '';
|
||||
if (note) flags.transportNote = true;
|
||||
const meta = metadataOf(r);
|
||||
const location = r.location || text(meta.location);
|
||||
const status =
|
||||
r.status === 'confirmed' ? tr('reservations.confirmed') : r.status === 'pending' ? tr('reservations.pending') : '';
|
||||
const tint = hexColour(bookingTint(r.type), NEUTRAL);
|
||||
|
||||
const extras = [
|
||||
r.confirmation_number
|
||||
? `<span class="code-chip note-code">${glyph('key', 9)}${escHtml(r.confirmation_number)}</span>`
|
||||
: '',
|
||||
status ? `<span class="chip">${escHtml(status)}</span>` : '',
|
||||
].filter(Boolean);
|
||||
|
||||
const card = `<div class="note-card booking-card">
|
||||
<span class="note-icon">${bookingIcon(r.type)}</span>
|
||||
<div class="note-body">
|
||||
${span ? `<div class="note-kicker">${escHtml(span)}</div>` : ''}
|
||||
<div class="note-text">${escHtml(r.title)}</div>
|
||||
${bookingLines(r, tr).map(bookingLineHtml).join('')}
|
||||
${location ? `<div class="note-time">${escHtml(location)}</div>` : ''}
|
||||
${extras.length ? `<div class="note-extra">${extras.join('')}</div>` : ''}
|
||||
${note ? `<div class="note-time transport-note">${escHtml(note)}</div>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
return item('booking', timeColumn(start, end), bookingIcon(r.type, 11), card, `--kind:${tint}`);
|
||||
}
|
||||
|
||||
// ── Notes ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A day note. A coloured note carries its colour as the rule along its edge and its
|
||||
* icon (#1629), not as a fill: a tint costs ink and reads as grey on a mono printer.
|
||||
*/
|
||||
export function noteItem(note: DayNote): string {
|
||||
const colour = note.color ? hexColour(note.color, '') : '';
|
||||
// A note's `time` is the free line the day plan prints under its text, not a clock,
|
||||
// so it stays in the card and the time column stays empty.
|
||||
const subtitle = typeof note.time === 'string' ? note.time.trim() : '';
|
||||
const card = `<div class="note-card${colour ? ' note-tinted' : ''}"${colour ? ` style="--note:${colour}"` : ''}>
|
||||
<span class="note-icon">${noteIcon(note.icon)}</span>
|
||||
<div class="note-body"><div class="note-text">${escHtml(note.text)}</div>${
|
||||
subtitle ? `<div class="note-time">${escHtml(subtitle)}</div>` : ''
|
||||
}</div>
|
||||
</div>`;
|
||||
return item('note', timeColumn('', ''), '', card);
|
||||
}
|
||||
|
||||
// ── Places ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** The day's opening hours of a place, Monday first like the stored week; null when unknown. */
|
||||
function hoursOnDay(place: Partial<Place>, day: Day, ctx: PdfDayContext): string | null {
|
||||
const week = parsePlaceHours(place.opening_hours);
|
||||
if (!week || !day.date) return null;
|
||||
const weekday = (new Date(day.date + 'T00:00:00Z').getUTCDay() + 6) % 7;
|
||||
const hours = week[weekday];
|
||||
if (!hours) return null;
|
||||
if (hours.closed) return ctx.tr('inspector.closed');
|
||||
if (!hours.open && !hours.close) return null;
|
||||
return [ctx.fmtTime(hours.open), ctx.fmtTime(hours.close)].filter(Boolean).join(' – ');
|
||||
}
|
||||
|
||||
function placeFacts(place: Assignment['place'] & Partial<Place>, ctx: PdfDayContext): string[] {
|
||||
const facts: string[] = [];
|
||||
const duration = durationLabel(place.duration_minutes);
|
||||
if (duration) facts.push(`<span class="chip">${glyph('duration', 9)}${escHtml(duration)}</span>`);
|
||||
const price = Number(place.price);
|
||||
if (Number.isFinite(price) && price > 0) {
|
||||
facts.push(
|
||||
`<span class="chip chip-green">${glyph('price', 9)}${escHtml(formatMoney(price, place.currency || ctx.tripCurrency, ctx.locale || 'en'))}</span>`
|
||||
);
|
||||
}
|
||||
if (typeof place.rating_avg === 'number' && place.rating_avg > 0) {
|
||||
const count = place.rating_count ? ` (${place.rating_count})` : '';
|
||||
facts.push(`<span class="chip chip-rating">${glyph('star', 9)}${place.rating_avg.toFixed(1)}${count}</span>`);
|
||||
}
|
||||
for (const tag of place.tags || []) {
|
||||
if (!tag.name) continue;
|
||||
facts.push(
|
||||
`<span class="chip chip-tag" style="--tag:${hexColour(tag.color, NEUTRAL)}">${escHtml(tag.name)}</span>`
|
||||
);
|
||||
}
|
||||
return facts;
|
||||
}
|
||||
|
||||
function placeDetails(
|
||||
place: Assignment['place'] & Partial<Place>,
|
||||
assignment: Assignment,
|
||||
day: Day,
|
||||
ctx: PdfDayContext
|
||||
): string[] {
|
||||
const details: string[] = [];
|
||||
const hours = hoursOnDay(place, day, ctx);
|
||||
if (hours)
|
||||
details.push(
|
||||
`<span class="detail">${glyph('hours', 9)}${escHtml(ctx.tr('inspector.openingHours'))} ${escHtml(hours)}</span>`
|
||||
);
|
||||
if (place.phone) details.push(`<span class="detail">${glyph('phone', 9)}${escHtml(place.phone)}</span>`);
|
||||
if (place.website)
|
||||
details.push(`<span class="detail">${glyph('web', 9)}${escHtml(websiteHost(place.website))}</span>`);
|
||||
if (place.email) details.push(`<span class="detail">${glyph('mail', 9)}${escHtml(place.email)}</span>`);
|
||||
const people = (assignment.participants || []).map((p) => p.username).filter(Boolean);
|
||||
if (people.length) {
|
||||
details.push(
|
||||
`<span class="detail">${glyph('people', 9)}${escHtml(ctx.tr('inspector.participants'))}: ${escHtml(people.join(', '))}</span>`
|
||||
);
|
||||
}
|
||||
return details;
|
||||
}
|
||||
|
||||
/** A planned place on the day's timeline, numbered like the stops on the map. */
|
||||
export function placeItem(assignment: Assignment, number: number, day: Day, ctx: PdfDayContext): string {
|
||||
// The assignment carries a projection of its place; the rating, the e-mail, the
|
||||
// hours and the reservation note are only on the trip's own place.
|
||||
const place: Assignment['place'] & Partial<Place> = {
|
||||
...ctx.placesById.get(assignment.place.id),
|
||||
...assignment.place,
|
||||
};
|
||||
const category = ctx.categories.find((c) => c.id === place.category_id);
|
||||
const catColour = hexColour(category?.color, NEUTRAL);
|
||||
const photo = ctx.photoOf(assignment.place);
|
||||
const media = photo
|
||||
? `<img class="place-thumb" src="${escHtml(photo)}" alt="" />`
|
||||
: `<div class="place-thumb-fallback">${categoryIcon(category?.icon)}</div>`;
|
||||
const facts = placeFacts(place, ctx);
|
||||
const details = placeDetails(place, assignment, day, ctx);
|
||||
const hasPosition = place.lat != null && place.lng != null;
|
||||
const notes = [place.notes, place.reservation_notes, assignment.notes].filter(
|
||||
(value): value is string => typeof value === 'string' && value.trim() !== ''
|
||||
);
|
||||
|
||||
const card = `<div class="place-card" style="--cat:${catColour}">
|
||||
${media}
|
||||
<div class="place-info">
|
||||
<div class="place-name-row">
|
||||
<span class="place-name">${escHtml(place.name)}</span>
|
||||
${category ? `<span class="cat-badge">${escHtml(category.name)}</span>` : ''}
|
||||
</div>
|
||||
${facts.length ? `<div class="facts">${facts.join('')}</div>` : ''}
|
||||
${place.address ? `<div class="info-row">${glyph('pin')}<span class="info-text">${escHtml(place.address)}</span></div>` : ''}
|
||||
${
|
||||
hasPosition
|
||||
? `<div class="info-row coords">${glyph('coords')}<span class="info-text muted">${Number(place.lat).toFixed(5)}, ${Number(place.lng).toFixed(5)}</span></div>`
|
||||
: ''
|
||||
}
|
||||
${place.description ? `<div class="place-text">${ctx.markdown(place.description)}</div>` : ''}
|
||||
${notes.map((note) => `<div class="place-note">${ctx.markdown(note)}</div>`).join('')}
|
||||
${details.length ? `<div class="details">${details.join('')}</div>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
const start = ctx.fmtTime(place.place_time);
|
||||
const end = ctx.fmtTime(place.end_time);
|
||||
return item('place', timeColumn(start, end), String(number), card);
|
||||
}
|
||||
|
||||
// ── Stays ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Where the day's night is spent. The day of arrival and the day of leaving get the
|
||||
* full card with the time, the address and the booking code; the nights in between a
|
||||
* quiet line, since the same hotel on every page is the plan's least news.
|
||||
*/
|
||||
export function staysBlock(stays: readonly Accommodation[], day: Day, ctx: PdfDayContext): string {
|
||||
if (!stays.length) return '';
|
||||
const cards = stays.map((stay) => {
|
||||
const isCheckIn = day.id === stay.start_day_id;
|
||||
const isCheckOut = day.id === stay.end_day_id;
|
||||
const name = stay.place_name || stay.reservation_title || '';
|
||||
const photo = safeImg(stay.place_image);
|
||||
const media = `<span class="stay-media">${photo ? `<img src="${escHtml(photo)}" alt="" />` : glyph(isCheckOut ? 'checkOut' : isCheckIn ? 'checkIn' : 'bed', 16)}</span>`;
|
||||
if (!isCheckIn && !isCheckOut) {
|
||||
return `<div class="day-accommodation stay-quiet">${media}<div class="stay-main">
|
||||
<div class="stay-kicker">${escHtml(ctx.tr('reservations.meta.linkAccommodation'))}</div>
|
||||
<div class="stay-name">${escHtml(name)}</div>
|
||||
</div></div>`;
|
||||
}
|
||||
const label = ctx.tr(isCheckIn ? 'reservations.meta.checkIn' : 'reservations.meta.checkOut');
|
||||
const time = ctx.fmtTime(isCheckIn ? stay.check_in : stay.check_out);
|
||||
const extras = [
|
||||
isCheckIn && stay.confirmation
|
||||
? `<span class="code-chip">${glyph('key', 9)}${escHtml(stay.confirmation)}</span>`
|
||||
: '',
|
||||
].filter(Boolean);
|
||||
return `<div class="day-accommodation">${media}<div class="stay-main">
|
||||
<div class="stay-kicker">${escHtml(label)}${time ? ` <span class="num">${escHtml(time)}</span>` : ''}</div>
|
||||
<div class="stay-name">${escHtml(name)}</div>
|
||||
${stay.place_address ? `<div class="stay-line">${escHtml(stay.place_address)}</div>` : ''}
|
||||
${stay.notes ? `<div class="stay-line">${escHtml(stay.notes)}</div>` : ''}
|
||||
${extras.length ? `<div class="stay-extra">${extras.join('')}</div>` : ''}
|
||||
</div></div>`;
|
||||
});
|
||||
return `<div class="day-accommodations${stays.length === 1 ? ' single' : ''}">${cards.join('')}</div>`;
|
||||
}
|
||||
|
||||
// ── Header ────────────────────────────────────────────────────────────────
|
||||
|
||||
interface DayHeaderFacts {
|
||||
stops: number;
|
||||
distance: string | null;
|
||||
cost: string | null;
|
||||
}
|
||||
|
||||
/** The day's header: its number in the day's colour, the date, the title and its figures. */
|
||||
export function dayHeader(day: Day, facts: DayHeaderFacts, ctx: PdfDayContext): string {
|
||||
const n = day.day_number ?? 0;
|
||||
const pills = [
|
||||
facts.stops > 0 ? `<span class="meta-pill">${glyph('pin', 9)}${facts.stops}</span>` : '',
|
||||
facts.distance ? `<span class="meta-pill">${glyph('route', 9)}${escHtml(facts.distance)}</span>` : '',
|
||||
facts.cost ? `<span class="day-cost">${glyph('price', 9)}${facts.cost}</span>` : '',
|
||||
].filter(Boolean);
|
||||
return `<div class="day-head">
|
||||
<span class="day-tag"><span class="day-tag-lbl">${escHtml(ctx.tr('pdf.day'))}</span><span class="day-tag-num">${n}</span></span>
|
||||
<div class="day-head-main">
|
||||
${day.date ? `<div class="day-date">${escHtml(shortDate(day.date, ctx.locale))}</div>` : ''}
|
||||
<div class="day-title">${escHtml(day.title || ctx.tr('dayplan.dayN', { n }))}</div>
|
||||
</div>
|
||||
${pills.length ? `<div class="day-meta">${pills.join('')}</div>` : ''}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// ── Photo strip ───────────────────────────────────────────────────────────
|
||||
|
||||
interface StripPhoto {
|
||||
url: string;
|
||||
caption: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The strip that opens a day: up to three of its photographed stops side by side, the
|
||||
* first one widest, each named on a frosted label. Nothing for a day without photos.
|
||||
*/
|
||||
export function photoStrip(photos: readonly StripPhoto[]): string {
|
||||
if (!photos.length) return '';
|
||||
return `<div class="day-strip day-strip-${photos.length}">${photos
|
||||
.map(
|
||||
(p) =>
|
||||
`<figure class="day-strip-photo"><img src="${escHtml(p.url)}" alt="" /><figcaption class="glass-label">${escHtml(p.caption)}</figcaption></figure>`
|
||||
)
|
||||
.join('')}</div>`;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* The small text and URL helpers every part of the trip PDF builds its markup with.
|
||||
* The document is an HTML string assembled outside React, so every value that comes
|
||||
* from the trip goes through escHtml before it lands in it.
|
||||
*/
|
||||
|
||||
/** Text for element content or a double-quoted attribute. */
|
||||
export function escHtml(value: unknown): string {
|
||||
if (value === null || value === undefined || value === '') return '';
|
||||
return String(value).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
/**
|
||||
* The style attribute is decoded back into raw quotes before the CSS is parsed, so
|
||||
* escHtml alone cannot stop a cover_image from closing the url() and appending its own
|
||||
* declaration. Percent-encoding is transparent to the fetch.
|
||||
*/
|
||||
export function cssUrl(url: string): string {
|
||||
return url.replace(/["'()\\\s]/g, (c) => '%' + (c.codePointAt(0) ?? 0).toString(16).padStart(2, '0'));
|
||||
}
|
||||
|
||||
/**
|
||||
* A colour that goes into a style attribute built by string concatenation. Anything
|
||||
* that is not a plain hex triple is not a colour and gets the fallback instead of a
|
||||
* chance to close the declaration.
|
||||
*/
|
||||
export function hexColour(value: unknown, fallback: string): string {
|
||||
return /^#[0-9a-f]{6}$/i.test(String(value)) ? String(value) : fallback;
|
||||
}
|
||||
|
||||
/** A path on this server as an absolute URL, so the print frame can load it. */
|
||||
export function absUrl(url: string | null | undefined): string | null {
|
||||
if (!url) return null;
|
||||
if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('data:')) return url;
|
||||
return window.location.origin + (url.startsWith('/') ? '' : '/') + url;
|
||||
}
|
||||
|
||||
/**
|
||||
* A picture the document may load: any web URL, the in-app place-photo proxy (it
|
||||
* streams a JPEG under a path without an extension) and uploaded files with an image
|
||||
* extension. Anything else prints as the fallback tile.
|
||||
*/
|
||||
export function safeImg(url: string | null | undefined): string | null {
|
||||
if (!url) return null;
|
||||
if (url.startsWith('https://') || url.startsWith('http://')) return url;
|
||||
if (url.startsWith('/api/maps/place-photo/')) return absUrl(url);
|
||||
return /\.(jpe?g|png|gif|webp|bmp|tiff?)(\?.*)?$/i.test(url) ? absUrl(url) : null;
|
||||
}
|
||||
|
||||
/** "Mon, 5 May" in the reader's language; empty for a day without a date. */
|
||||
export function shortDate(date: string | null | undefined, locale: string | undefined): string {
|
||||
if (!date) return '';
|
||||
return new Date(date + 'T00:00:00Z').toLocaleDateString(locale, {
|
||||
weekday: 'short',
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
timeZone: 'UTC',
|
||||
});
|
||||
}
|
||||
|
||||
/** "3 May – 24 May 2026" over the dated days, or null when none has a date. */
|
||||
export function longDateRange(
|
||||
days: readonly { date?: string | null; day_number?: number }[],
|
||||
locale: string | undefined
|
||||
): string | null {
|
||||
const dated = days.filter((d) => d.date).sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0));
|
||||
if (!dated.length) return null;
|
||||
const first = new Date(dated[0].date + 'T00:00:00Z');
|
||||
const last = new Date(dated[dated.length - 1].date + 'T00:00:00Z');
|
||||
const from = first.toLocaleDateString(locale, { day: 'numeric', month: 'long', timeZone: 'UTC' });
|
||||
const to = last.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' });
|
||||
return `${from} – ${to}`;
|
||||
}
|
||||
|
||||
/** The host of a website, which is what fits on a printed line. */
|
||||
export function websiteHost(url: string): string {
|
||||
try {
|
||||
return new URL(/^https?:\/\//i.test(url) ? url : `https://${url}`).host.replace(/^www\./, '');
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import { createElement } from 'react';
|
||||
|
||||
import { renderIconMarkup } from '../../utils/iconMarkup';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
|
||||
import {
|
||||
AlertTriangle,
|
||||
BedDouble,
|
||||
Bike,
|
||||
Bookmark,
|
||||
Bus,
|
||||
CableCar,
|
||||
Camera,
|
||||
Car,
|
||||
CarTaxiFront,
|
||||
Clock,
|
||||
Coffee,
|
||||
Crosshair,
|
||||
FileText,
|
||||
Flag,
|
||||
Globe,
|
||||
Heart,
|
||||
Hourglass,
|
||||
Info,
|
||||
KeyRound,
|
||||
Lightbulb,
|
||||
LogIn,
|
||||
LogOut,
|
||||
Mail,
|
||||
MapPin,
|
||||
Navigation,
|
||||
ParkingSquare,
|
||||
Phone,
|
||||
Plane,
|
||||
Route,
|
||||
Sailboat,
|
||||
Ship,
|
||||
ShoppingBag,
|
||||
Star,
|
||||
StickyNote,
|
||||
Store,
|
||||
Tag,
|
||||
Ticket,
|
||||
Train,
|
||||
Users,
|
||||
Utensils,
|
||||
Wallet,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
|
||||
/*
|
||||
* Every icon of the trip PDF as SVG markup. They draw in currentColor, so the
|
||||
* stylesheet decides their colour, which keeps the palette in one place.
|
||||
*/
|
||||
|
||||
function iconSvg(Icon: LucideIcon, size: number, strokeWidth = 1.9): string {
|
||||
return renderIconMarkup(createElement(Icon, { size, strokeWidth, color: 'currentColor', 'aria-hidden': 'true' }));
|
||||
}
|
||||
|
||||
/** The small glyphs of the facts, contact lines and stay rows. */
|
||||
const GLYPHS = {
|
||||
pin: MapPin,
|
||||
coords: Crosshair,
|
||||
clock: Clock,
|
||||
duration: Hourglass,
|
||||
price: Wallet,
|
||||
star: Star,
|
||||
phone: Phone,
|
||||
web: Globe,
|
||||
mail: Mail,
|
||||
hours: Store,
|
||||
people: Users,
|
||||
note: StickyNote,
|
||||
tag: Tag,
|
||||
route: Route,
|
||||
bed: BedDouble,
|
||||
checkIn: LogIn,
|
||||
checkOut: LogOut,
|
||||
key: KeyRound,
|
||||
} satisfies Record<string, LucideIcon>;
|
||||
|
||||
type PdfGlyph = keyof typeof GLYPHS;
|
||||
|
||||
export function glyph(name: PdfGlyph, size = 10): string {
|
||||
return iconSvg(GLYPHS[name], size);
|
||||
}
|
||||
|
||||
const NOTE_ICONS: Record<string, LucideIcon> = {
|
||||
FileText,
|
||||
Info,
|
||||
Clock,
|
||||
MapPin,
|
||||
Navigation,
|
||||
Train,
|
||||
Plane,
|
||||
Bus,
|
||||
Car,
|
||||
Ship,
|
||||
Coffee,
|
||||
Ticket,
|
||||
Star,
|
||||
Heart,
|
||||
Camera,
|
||||
Flag,
|
||||
Lightbulb,
|
||||
AlertTriangle,
|
||||
ShoppingBag,
|
||||
Bookmark,
|
||||
};
|
||||
|
||||
/** A day note's own icon, the note icon for one that names none. */
|
||||
export function noteIcon(iconId: string | null | undefined, size = 13): string {
|
||||
return iconSvg((iconId && NOTE_ICONS[iconId]) || FileText, size);
|
||||
}
|
||||
|
||||
const BOOKING_ICONS: Record<string, LucideIcon> = {
|
||||
flight: Plane,
|
||||
train: Train,
|
||||
bus: Bus,
|
||||
car: Car,
|
||||
taxi: CarTaxiFront,
|
||||
bicycle: Bike,
|
||||
cruise: Ship,
|
||||
ferry: Sailboat,
|
||||
cable_car: CableCar,
|
||||
transport_other: Route,
|
||||
restaurant: Utensils,
|
||||
event: Ticket,
|
||||
tour: Users,
|
||||
parking: ParkingSquare,
|
||||
other: FileText,
|
||||
};
|
||||
|
||||
/** A booking's type icon; a type the export does not know gets the ticket. */
|
||||
export function bookingIcon(type: string | null | undefined, size = 14): string {
|
||||
return iconSvg((type && BOOKING_ICONS[type]) || Ticket, size);
|
||||
}
|
||||
|
||||
/** The tint of each booking type, the same hues the day plan gives them. */
|
||||
const BOOKING_TINTS: Record<string, string> = {
|
||||
flight: '#3b82f6',
|
||||
train: '#0891b2',
|
||||
bus: '#059669',
|
||||
car: '#64748b',
|
||||
taxi: '#ca8a04',
|
||||
bicycle: '#65a30d',
|
||||
cruise: '#0284c7',
|
||||
ferry: '#0d9488',
|
||||
cable_car: '#dc2626',
|
||||
transport_other: '#64748b',
|
||||
restaurant: '#e11d48',
|
||||
event: '#d97706',
|
||||
tour: '#059669',
|
||||
parking: '#2563eb',
|
||||
other: '#64748b',
|
||||
};
|
||||
|
||||
export function bookingTint(type: string | null | undefined): string {
|
||||
return (type && BOOKING_TINTS[type]) || BOOKING_TINTS.flight;
|
||||
}
|
||||
|
||||
/** A category's icon for the tile a place without a photo prints. */
|
||||
export function categoryIcon(iconName: string | null | undefined, size = 22): string {
|
||||
return iconSvg(getCategoryIcon(iconName), size, 1.7);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* FE-PDFOVERVIEW-001 to FE-PDFOVERVIEW-005: the trip PDF's cover and overview pages,
|
||||
* built from the figures the export hands them.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { coverHtml, coverRouteSvg, glanceHtml, ledgerHtml, type GlanceRow, type LedgerRow } from './tripPdfOverview';
|
||||
|
||||
const tr = (key: string) => key;
|
||||
const parse = (html: string) => new DOMParser().parseFromString(html, 'text/html');
|
||||
const texts = (doc: Document, selector: string) =>
|
||||
[...doc.querySelectorAll(selector)].map((el) => el.textContent?.replace(/\s+/g, ' ').trim());
|
||||
|
||||
describe('coverHtml', () => {
|
||||
const base = {
|
||||
title: 'Autumn <in> Japan',
|
||||
description: 'Temples and trains',
|
||||
range: '1 November – 22 November 2026',
|
||||
logo: 'https://trek.example/logo-light.svg',
|
||||
stats: [
|
||||
{ value: '22', label: 'days' },
|
||||
{ value: '1,234 km', label: 'pdf.distanceLabel' },
|
||||
],
|
||||
route: [],
|
||||
ribbon: [],
|
||||
ribbonEnds: null,
|
||||
tr,
|
||||
};
|
||||
|
||||
it('FE-PDFOVERVIEW-001: the photo, the escaped title, the dates and a tile per figure', () => {
|
||||
const doc = parse(coverHtml({ ...base, image: 'https://cdn.example/cover.jpg' }));
|
||||
|
||||
expect(doc.querySelector('section')?.className).toBe('cover');
|
||||
expect(doc.querySelector('.cover-bg')?.getAttribute('style')).toBe(
|
||||
"background-image:url('https://cdn.example/cover.jpg')"
|
||||
);
|
||||
expect(texts(doc, '.cover-title')).toEqual(['Autumn <in> Japan']);
|
||||
expect(texts(doc, '.cover-dates')).toEqual(['1 November – 22 November 2026']);
|
||||
expect(texts(doc, '.cover-desc')).toEqual(['Temples and trains']);
|
||||
expect(texts(doc, '.cover-stat-num')).toEqual(['22', '1,234 km']);
|
||||
expect(texts(doc, '.cover-top .eyebrow')).toEqual(['pdf.travelPlan']);
|
||||
});
|
||||
|
||||
it('FE-PDFOVERVIEW-002: without a photo the cover is plain, and a hostile url cannot leave url()', () => {
|
||||
const plain = parse(coverHtml({ ...base, image: null, description: null, range: null }));
|
||||
expect(plain.querySelector('section')?.className).toBe('cover cover-plain');
|
||||
expect(plain.querySelector('.cover-bg')?.hasAttribute('style')).toBe(false);
|
||||
expect(plain.querySelector('.cover-desc')).toBeNull();
|
||||
expect(plain.querySelector('.cover-dates')).toBeNull();
|
||||
|
||||
const hostile = parse(coverHtml({ ...base, image: "https://a/x.jpg');background:url('https://b/leak.jpg" }));
|
||||
const style = hostile.querySelector('.cover-bg')?.getAttribute('style') ?? '';
|
||||
expect(style.match(/url\(/g)).toHaveLength(1);
|
||||
expect(style).not.toContain("');");
|
||||
});
|
||||
});
|
||||
|
||||
describe('the cover route and day band', () => {
|
||||
const base = { title: 'Japan', description: null, range: null, image: null, logo: null, stats: [], tr };
|
||||
|
||||
it('FE-PDFOVERVIEW-006: the route is drawn day by day in its colours, the band has a segment per day', () => {
|
||||
const doc = parse(
|
||||
coverHtml({
|
||||
...base,
|
||||
route: [
|
||||
{
|
||||
colour: '#ff0000',
|
||||
lines: [
|
||||
[
|
||||
[35.68, 139.76],
|
||||
[35.0, 135.77],
|
||||
],
|
||||
],
|
||||
},
|
||||
{
|
||||
colour: '#00ff00',
|
||||
lines: [
|
||||
[
|
||||
[35.0, 135.77],
|
||||
[34.69, 135.5],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
ribbon: ['#ff0000', '#00ff00', '#0000ff'],
|
||||
ribbonEnds: ['Sun, Nov 1', 'Tue, Nov 3'],
|
||||
})
|
||||
);
|
||||
|
||||
const coloured = [...doc.querySelectorAll('.cover-route-svg path[stroke]')].map((p) => p.getAttribute('stroke'));
|
||||
expect(coloured).toEqual(['#ff0000', '#00ff00']);
|
||||
expect(doc.querySelectorAll('.cover-route-glow path')).toHaveLength(2);
|
||||
expect(texts(doc, '.cover-route-lbl')).toEqual(['pdf.mapTitle']);
|
||||
expect(doc.querySelectorAll('.cover-ribbon span')).toHaveLength(3);
|
||||
expect(texts(doc, '.cover-ribbon-ends span')).toEqual(['Sun, Nov 1', 'Tue, Nov 3']);
|
||||
// Every point lands inside the drawing.
|
||||
const numbers = [...doc.querySelectorAll('.cover-route-svg path[stroke]')].flatMap((p) =>
|
||||
(p.getAttribute('d') ?? '').split(/[ML ]/).filter(Boolean).map(Number)
|
||||
);
|
||||
for (const n of numbers) expect(n).toBeGreaterThanOrEqual(0);
|
||||
for (const n of numbers) expect(n).toBeLessThanOrEqual(240);
|
||||
});
|
||||
|
||||
it('FE-PDFOVERVIEW-007: nothing routed, one point or one spot draws no card, one day no band', () => {
|
||||
expect(coverRouteSvg([])).toBe('');
|
||||
expect(coverRouteSvg([{ colour: '#ff0000', lines: [[[1, 1]]] }])).toBe('');
|
||||
expect(
|
||||
coverRouteSvg([
|
||||
{
|
||||
colour: '#ff0000',
|
||||
lines: [
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
],
|
||||
],
|
||||
},
|
||||
])
|
||||
).toBe('');
|
||||
|
||||
const doc = parse(coverHtml({ ...base, route: [], ribbon: ['#ff0000'], ribbonEnds: null }));
|
||||
expect(doc.querySelector('.cover-route')).toBeNull();
|
||||
expect(doc.querySelector('.cover-ribbon')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PDFOVERVIEW-008: a long road is thinned to a drawable number of points', () => {
|
||||
const road = Array.from({ length: 20000 }, (_, i) => [45 + i / 20000, 7 + i / 10000] as [number, number]);
|
||||
const svg = coverRouteSvg([{ colour: '#ff0000', lines: [road] }]);
|
||||
const d = /<path d="([^"]+)" stroke=/.exec(svg)?.[1] ?? '';
|
||||
expect(d.split('L').length).toBeLessThanOrEqual(1700);
|
||||
});
|
||||
});
|
||||
|
||||
describe('glanceHtml', () => {
|
||||
const row = (over: Partial<GlanceRow> = {}): GlanceRow => ({
|
||||
number: 1,
|
||||
colour: '#0a84ff',
|
||||
date: 'Sun, Nov 1',
|
||||
title: 'Tokyo',
|
||||
stops: 3,
|
||||
stay: 'Hotel Gracery',
|
||||
cost: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
it('FE-PDFOVERVIEW-003: one row per day in its colour, the cost column only when a day has one', () => {
|
||||
const without = parse(glanceHtml([row(), row({ number: 2, stops: 0 })], tr));
|
||||
expect(texts(without, 'thead th')).toEqual(['pdf.day', 'common.date', 'pdf.plan', 'pdf.stay', '']);
|
||||
expect(texts(without, 'tbody tr:first-child td')).toEqual(['1', 'Sun, Nov 1', 'Tokyo', 'Hotel Gracery', '3']);
|
||||
// A day without stops leaves the cell empty rather than printing a zero.
|
||||
expect(texts(without, 'tbody tr:last-child td').slice(-1)[0]).toBe('');
|
||||
expect(without.querySelector('tbody tr')?.getAttribute('style')).toBe('--day:#0a84ff');
|
||||
|
||||
const withCost = parse(glanceHtml([row(), row({ number: 2, cost: '¥3,000' })], tr));
|
||||
expect(texts(withCost, 'thead th').slice(-1)[0]).toBe('pdf.costLabel');
|
||||
expect(texts(withCost, 'tbody tr:last-child td').slice(-1)[0]).toBe('¥3,000');
|
||||
|
||||
expect(glanceHtml([], tr)).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ledgerHtml', () => {
|
||||
it('FE-PDFOVERVIEW-004: each booking and stay with its date and the code to show', () => {
|
||||
const rows: LedgerRow[] = [
|
||||
{
|
||||
icon: '<svg></svg>',
|
||||
tint: '#3b82f6',
|
||||
title: 'LH716 <FRA>',
|
||||
sub: '<span>FRA → HND</span>',
|
||||
when: 'Sat, Oct 31',
|
||||
code: 'ABC123',
|
||||
},
|
||||
{
|
||||
icon: '<svg></svg>',
|
||||
tint: '#17171c',
|
||||
title: 'Hotel Gracery',
|
||||
sub: '',
|
||||
when: 'Sun, Nov 1 – Wed, Nov 4',
|
||||
code: null,
|
||||
},
|
||||
];
|
||||
const doc = parse(ledgerHtml(rows, tr));
|
||||
|
||||
expect(texts(doc, '.sec-title')).toEqual(['pdf.bookings']);
|
||||
expect(texts(doc, '.ledger-title')).toEqual(['LH716 <FRA>', 'Hotel Gracery']);
|
||||
expect(texts(doc, '.ledger-sub')).toEqual(['FRA → HND']);
|
||||
expect(texts(doc, '.ledger-when .code-chip')).toEqual(['ABC123']);
|
||||
expect(doc.querySelectorAll('.ledger-when')[1]?.textContent).toBe('Sun, Nov 1 – Wed, Nov 4');
|
||||
expect(doc.querySelectorAll('.code-chip')).toHaveLength(1);
|
||||
expect(doc.querySelector('.ledger-row')?.getAttribute('style')).toBe('--kind:#3b82f6');
|
||||
});
|
||||
|
||||
it('FE-PDFOVERVIEW-005: a trip without bookings or stays prints no list at all', () => {
|
||||
expect(ledgerHtml([], tr)).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
import type { ShadeStop } from './pdfImages';
|
||||
import { cssUrl, escHtml } from './tripPdfHtml';
|
||||
import { glyph } from './tripPdfIcons';
|
||||
|
||||
/*
|
||||
* The trip PDF's first pages: the cover, then the overview with the route map, every
|
||||
* day at a glance and the list of bookings and stays with their codes.
|
||||
*/
|
||||
|
||||
type Translate = (key: string, params?: Record<string, string | number>) => string;
|
||||
|
||||
export interface CoverStat {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** One day of the route as the cover draws it: its colour and its roads, `[lat, lng]`. */
|
||||
interface CoverRouteDay {
|
||||
colour: string;
|
||||
lines: readonly (readonly [number, number])[][];
|
||||
}
|
||||
|
||||
interface CoverInput {
|
||||
title: string;
|
||||
description: string | null;
|
||||
range: string | null;
|
||||
/** The cover photo, already checked to be one the document may load. */
|
||||
image: string | null;
|
||||
/** Whether the shade is already painted into `image`, so none is laid over it. */
|
||||
baked?: boolean;
|
||||
/** The light TREK logo, absolute. */
|
||||
logo: string | null;
|
||||
stats: readonly CoverStat[];
|
||||
/** The routed days, drawn as the trip's shape; empty when nothing was routed. */
|
||||
route: readonly CoverRouteDay[];
|
||||
/** Every day's colour in trip order, for the band under the title. */
|
||||
ribbon: readonly string[];
|
||||
/** The first and the last day's short date, under the band's ends. */
|
||||
ribbonEnds: readonly [string, string] | null;
|
||||
tr: Translate;
|
||||
}
|
||||
|
||||
/**
|
||||
* The shade over the cover photo, top to bottom: a little at the top for the logo, clear
|
||||
* through the middle, dark at the foot for the title and the figures. Painted into the
|
||||
* photo when the export could bake it, laid over it as a gradient when not.
|
||||
*/
|
||||
export const COVER_SHADE: readonly ShadeStop[] = [
|
||||
[0, 0.35],
|
||||
[0.22, 0],
|
||||
[0.36, 0],
|
||||
[0.92, 0.82],
|
||||
];
|
||||
|
||||
/** The cover shade as a CSS gradient, for a photo the export could not bake. */
|
||||
export function coverShadeCss(): string {
|
||||
return `linear-gradient(180deg, ${COVER_SHADE.map(([at, alpha]) => `rgba(10, 10, 14, ${alpha}) ${at * 100}%`).join(', ')})`;
|
||||
}
|
||||
|
||||
const ROUTE_W = 240;
|
||||
const ROUTE_H = 170;
|
||||
const ROUTE_PAD = 14;
|
||||
/** Points drawn at most: a road trip routes to tens of thousands, the shape needs far fewer. */
|
||||
const ROUTE_MAX_POINTS = 1600;
|
||||
|
||||
type LatLng = readonly [number, number];
|
||||
|
||||
/**
|
||||
* The trip's roads as one small drawing, each day in its colour on a soft glow, with a
|
||||
* ring where the trip starts and a dot where it ends. Projected flat with the longitude
|
||||
* scaled to the middle latitude, which is true enough at the size of a trip. Empty when
|
||||
* there is no shape to draw.
|
||||
*/
|
||||
export function coverRouteSvg(days: readonly CoverRouteDay[]): string {
|
||||
const lines = days.flatMap((d) => d.lines.filter((l) => l.length > 1).map((l) => ({ colour: d.colour, points: l })));
|
||||
const points = lines.flatMap((l) => l.points);
|
||||
if (!lines.length) return '';
|
||||
const lats = points.map((p) => p[0]);
|
||||
const midLat = (Math.min(...lats) + Math.max(...lats)) / 2;
|
||||
const k = Math.cos((midLat * Math.PI) / 180);
|
||||
const xs = points.map((p) => p[1] * k);
|
||||
const ys = points.map((p) => -p[0]);
|
||||
const minX = Math.min(...xs);
|
||||
const minY = Math.min(...ys);
|
||||
const w = Math.max(...xs) - minX;
|
||||
const h = Math.max(...ys) - minY;
|
||||
const scale = Math.min(
|
||||
w > 0 ? (ROUTE_W - 2 * ROUTE_PAD) / w : Infinity,
|
||||
h > 0 ? (ROUTE_H - 2 * ROUTE_PAD) / h : Infinity
|
||||
);
|
||||
if (!Number.isFinite(scale)) return '';
|
||||
const offX = (ROUTE_W - w * scale) / 2;
|
||||
const offY = (ROUTE_H - h * scale) / 2;
|
||||
const x = (p: LatLng) => (offX + (p[1] * k - minX) * scale).toFixed(1);
|
||||
const y = (p: LatLng) => (offY + (-p[0] - minY) * scale).toFixed(1);
|
||||
const step = Math.max(1, Math.ceil(points.length / ROUTE_MAX_POINTS));
|
||||
const path = (line: readonly LatLng[]) =>
|
||||
line
|
||||
.filter((_, i) => i % step === 0 || i === line.length - 1)
|
||||
.map((p, i) => `${i ? 'L' : 'M'}${x(p)} ${y(p)}`)
|
||||
.join('');
|
||||
const drawn = lines.map((l) => ({ colour: l.colour, d: path(l.points) }));
|
||||
const first = lines[0];
|
||||
const last = lines[lines.length - 1];
|
||||
const start = first.points[0];
|
||||
const end = last.points[last.points.length - 1];
|
||||
return `<svg class="cover-route-svg" viewBox="0 0 ${ROUTE_W} ${ROUTE_H}" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
|
||||
<g class="cover-route-glow" fill="none" stroke="currentColor" stroke-width="4.6" stroke-linecap="round" stroke-linejoin="round">${drawn
|
||||
.map((l) => `<path d="${l.d}"/>`)
|
||||
.join('')}</g>
|
||||
<g fill="none" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">${drawn
|
||||
.map((l) => `<path d="${l.d}" stroke="${l.colour}"/>`)
|
||||
.join('')}</g>
|
||||
<circle class="cover-route-start" cx="${x(start)}" cy="${y(start)}" r="4.2" stroke="${first.colour}" stroke-width="2.2"/>
|
||||
<circle class="cover-route-end" cx="${x(end)}" cy="${y(end)}" r="4.2" fill="${last.colour}" stroke-width="1.6"/>
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
/** The cover: the trip's photo left bright, the title, the dates and its figures. */
|
||||
export function coverHtml({
|
||||
title,
|
||||
description,
|
||||
range,
|
||||
image,
|
||||
baked = false,
|
||||
logo,
|
||||
stats,
|
||||
route,
|
||||
ribbon,
|
||||
ribbonEnds,
|
||||
tr,
|
||||
}: CoverInput): string {
|
||||
const routeSvg = coverRouteSvg(route);
|
||||
const routeCard = routeSvg
|
||||
? `<div class="cover-route"><div class="cover-route-lbl">${escHtml(tr('pdf.mapTitle'))}</div>${routeSvg}</div>`
|
||||
: '';
|
||||
const ends = ribbonEnds
|
||||
? `<div class="cover-ribbon-ends"><span>${escHtml(ribbonEnds[0])}</span><span>${escHtml(ribbonEnds[1])}</span></div>`
|
||||
: '';
|
||||
const band =
|
||||
ribbon.length > 1
|
||||
? `<div class="cover-ribbon">${ribbon.map((c) => `<span style="background:${c}"></span>`).join('')}</div>${ends}`
|
||||
: '';
|
||||
return `<section class="cover${image ? '' : ' cover-plain'}">
|
||||
<div class="cover-bg"${image ? ` style="background-image:url('${escHtml(cssUrl(image))}')"` : ''}></div>
|
||||
${baked ? '' : '<div class="cover-shade"></div>'}
|
||||
<div class="cover-top">
|
||||
${logo ? `<img src="${escHtml(logo)}" alt="TREK" />` : '<span></span>'}
|
||||
<span class="eyebrow">${escHtml(tr('pdf.travelPlan'))}</span>
|
||||
</div>
|
||||
<div class="cover-body">
|
||||
<div class="cover-main">
|
||||
<div class="cover-head">
|
||||
${range ? `<div class="cover-dates">${escHtml(range)}</div>` : ''}
|
||||
<h1 class="cover-title">${escHtml(title)}</h1>
|
||||
${description ? `<p class="cover-desc">${escHtml(description)}</p>` : ''}
|
||||
</div>
|
||||
${routeCard}
|
||||
</div>
|
||||
${band}
|
||||
<div class="cover-stats">${stats
|
||||
.map(
|
||||
(s) =>
|
||||
`<div class="cover-stat"><div class="cover-stat-num">${escHtml(s.value)}</div><div class="cover-stat-lbl">${escHtml(s.label)}</div></div>`
|
||||
)
|
||||
.join('')}</div>
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
export interface GlanceRow {
|
||||
number: number;
|
||||
colour: string;
|
||||
date: string;
|
||||
title: string;
|
||||
stops: number;
|
||||
stay: string;
|
||||
cost: string | null;
|
||||
}
|
||||
|
||||
/** Every day in one table: its colour, date and title, where the night is spent and what it costs. */
|
||||
export function glanceHtml(rows: readonly GlanceRow[], tr: Translate): string {
|
||||
if (!rows.length) return '';
|
||||
const withCost = rows.some((r) => r.cost);
|
||||
return `<div class="sec-block">
|
||||
<div class="sec-head"><span class="sec-title">${escHtml(tr('pdf.atAGlance'))}</span></div>
|
||||
<table class="glance">
|
||||
<thead><tr>
|
||||
<th>${escHtml(tr('pdf.day'))}</th>
|
||||
<th>${escHtml(tr('common.date'))}</th>
|
||||
<th>${escHtml(tr('pdf.plan'))}</th>
|
||||
<th>${escHtml(tr('pdf.stay'))}</th>
|
||||
<th class="glance-stops">${glyph('pin', 9)}</th>
|
||||
${withCost ? `<th class="glance-end">${escHtml(tr('pdf.costLabel'))}</th>` : ''}
|
||||
</tr></thead>
|
||||
<tbody>${rows
|
||||
.map(
|
||||
(r) => `<tr style="--day:${r.colour}">
|
||||
<td><span class="glance-day">${r.number}</span></td>
|
||||
<td class="num glance-date">${escHtml(r.date)}</td>
|
||||
<td class="glance-title">${escHtml(r.title)}</td>
|
||||
<td>${escHtml(r.stay)}</td>
|
||||
<td class="num glance-stops">${r.stops || ''}</td>
|
||||
${withCost ? `<td class="num">${r.cost ?? ''}</td>` : ''}
|
||||
</tr>`
|
||||
)
|
||||
.join('')}</tbody>
|
||||
</table>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
export interface LedgerRow {
|
||||
/** The type's icon, already markup. */
|
||||
icon: string;
|
||||
/** The type's tint, a checked hex colour. */
|
||||
tint: string;
|
||||
title: string;
|
||||
/** Markup under the title: the route, the address or the booking's facts. */
|
||||
sub: string;
|
||||
when: string;
|
||||
code: string | null;
|
||||
}
|
||||
|
||||
/** The trip's bookings and stays in date order, each with the code to show at the desk. */
|
||||
export function ledgerHtml(rows: readonly LedgerRow[], tr: Translate): string {
|
||||
if (!rows.length) return '';
|
||||
return `<div class="sec-block ledger-block">
|
||||
<div class="sec-head"><span class="sec-title">${escHtml(tr('pdf.bookings'))}</span></div>
|
||||
<div class="ledger">${rows
|
||||
.map(
|
||||
(r) => `<div class="ledger-row" style="--kind:${r.tint}">
|
||||
<span class="ledger-icon">${r.icon}</span>
|
||||
<div><div class="ledger-title">${escHtml(r.title)}</div>${r.sub ? `<div class="ledger-sub">${r.sub}</div>` : ''}</div>
|
||||
<div class="ledger-when">${escHtml(r.when)}${r.code ? `<div><span class="code-chip">${glyph('key', 9)}${escHtml(r.code)}</span></div>` : ''}</div>
|
||||
</div>`
|
||||
)
|
||||
.join('')}</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
import geist400 from '@fontsource/geist-sans/files/geist-sans-latin-400-normal.woff2?url';
|
||||
import geist500 from '@fontsource/geist-sans/files/geist-sans-latin-500-normal.woff2?url';
|
||||
import geist600 from '@fontsource/geist-sans/files/geist-sans-latin-600-normal.woff2?url';
|
||||
|
||||
import { PDF_MARKDOWN_CSS } from './pdfMarkdown';
|
||||
import { coverShadeCss } from './tripPdfOverview';
|
||||
|
||||
/*
|
||||
* The trip PDF's stylesheet. A print document has a fixed palette rather than the
|
||||
* reader's scheme, so its colours are declared once, as the custom properties at the
|
||||
* top, and every rule below names them. The type follows the app: Poppins for words,
|
||||
* Geist for figures, times and the small capitals.
|
||||
*
|
||||
* Every switch of the preview is one class on <body> (pdfPreview.ts), so turning one
|
||||
* over is instant and needs no rebuild:
|
||||
* pdf-flow days run on instead of each starting a page
|
||||
* pdf-large-text larger type and darker greys
|
||||
* pdf-no-transport-notes the notes of flights, trains and rentals left out
|
||||
* pdf-no-photos no photos on the places and stays
|
||||
* pdf-no-overview no route map, day overview or booking list
|
||||
* pdf-no-coords no coordinates under the addresses
|
||||
* pdf-no-details no contact lines, opening hours or companions
|
||||
*/
|
||||
export function tripPdfCss(): string {
|
||||
return `
|
||||
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 400; src: url('/fonts/Poppins-Regular.ttf') format('truetype'); }
|
||||
@font-face { font-family: 'Poppins'; font-style: italic; font-weight: 400; src: url('/fonts/Poppins-Italic.ttf') format('truetype'); }
|
||||
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 500; src: url('/fonts/Poppins-Medium.ttf') format('truetype'); }
|
||||
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 600; src: url('/fonts/Poppins-SemiBold.ttf') format('truetype'); }
|
||||
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 700; src: url('/fonts/Poppins-Bold.ttf') format('truetype'); }
|
||||
@font-face { font-family: 'Geist PDF'; font-weight: 400; src: url('${geist400}') format('woff2'); }
|
||||
@font-face { font-family: 'Geist PDF'; font-weight: 500; src: url('${geist500}') format('woff2'); }
|
||||
@font-face { font-family: 'Geist PDF'; font-weight: 600; src: url('${geist600}') format('woff2'); }
|
||||
|
||||
:root {
|
||||
--ink: #17171c;
|
||||
--ink-2: #3e3e47;
|
||||
--ink-3: #6a6a74;
|
||||
--ink-4: #9a9aa4;
|
||||
--hair: #e7e5e0;
|
||||
--paper: #ffffff;
|
||||
--wash: #f6f5f2;
|
||||
--wash-2: #eeede8;
|
||||
--night: #141418;
|
||||
--glass: rgba(255, 255, 255, 0.13);
|
||||
--glass-edge: rgba(255, 255, 255, 0.22);
|
||||
--glass-dark: rgba(14, 14, 18, 0.42);
|
||||
--glass-tile: rgba(18, 18, 24, 0.34);
|
||||
--glass-deep: rgba(12, 12, 16, 0.5);
|
||||
--on-night: rgba(255, 255, 255, 0.78);
|
||||
--on-night-2: rgba(255, 255, 255, 0.56);
|
||||
--gold: #b7791f;
|
||||
--day: var(--ink);
|
||||
--t: 1;
|
||||
--sans: 'Poppins', system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
--num: 'Geist PDF', 'Poppins', system-ui, sans-serif;
|
||||
--gutter: 14mm;
|
||||
}
|
||||
body.pdf-large-text {
|
||||
--t: 1.3;
|
||||
--ink-2: #2b2b33;
|
||||
--ink-3: #4b4b55;
|
||||
--ink-4: #62626c;
|
||||
}
|
||||
|
||||
@page { size: A4; margin: 12mm 0 14mm; }
|
||||
@page :first { margin: 0; }
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
html, body { background: var(--paper); }
|
||||
body {
|
||||
font-family: var(--sans); color: var(--ink);
|
||||
font-size: calc(9.5px * var(--t)); line-height: 1.5;
|
||||
-webkit-print-color-adjust: exact; print-color-adjust: exact;
|
||||
}
|
||||
img { display: block; }
|
||||
svg { flex-shrink: 0; }
|
||||
.num { font-family: var(--num); font-variant-numeric: tabular-nums; }
|
||||
.eyebrow {
|
||||
font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600;
|
||||
letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-3);
|
||||
}
|
||||
.page-break { break-before: page; }
|
||||
|
||||
|
||||
/* ── Cover ───────────────────────────────────────────────── */
|
||||
.cover {
|
||||
position: relative; height: 297mm; overflow: hidden;
|
||||
background: var(--night); color: var(--paper); break-after: page;
|
||||
}
|
||||
.cover-bg { position: absolute; inset: 0; background-size: cover; background-position: center; }
|
||||
.cover-plain .cover-bg {
|
||||
background: radial-gradient(120% 80% at 85% 10%, var(--ink-2) 0%, var(--night) 60%);
|
||||
}
|
||||
.cover-shade {
|
||||
position: absolute; inset: 0;
|
||||
background: ${coverShadeCss()};
|
||||
}
|
||||
.cover-top {
|
||||
position: absolute; inset-block-start: 14mm; inset-inline: var(--gutter);
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
}
|
||||
.cover-top img { height: 22px; }
|
||||
.cover-top .eyebrow { color: var(--on-night); }
|
||||
.cover-body { position: absolute; inset-inline: var(--gutter); inset-block-end: 15mm; }
|
||||
.cover-main { display: flex; align-items: flex-end; gap: 8mm; }
|
||||
.cover-head { flex: 1; min-width: 0; }
|
||||
.cover-dates {
|
||||
display: inline-block; font-family: var(--num); font-size: 9px; font-weight: 600; letter-spacing: 0.16em;
|
||||
text-transform: uppercase; color: var(--paper); padding: 5px 11px; border-radius: 99px;
|
||||
background: var(--glass-tile); border: 1px solid var(--glass-edge);
|
||||
}
|
||||
.cover-title { font-size: 54px; font-weight: 700; line-height: 1; letter-spacing: -0.025em; margin: 5mm 0 3.5mm; }
|
||||
.cover-desc { max-width: 120mm; font-size: 12px; line-height: 1.6; color: var(--on-night); }
|
||||
.cover-route {
|
||||
flex: 0 0 66mm; padding: 9px 10px 6px; border-radius: 18px;
|
||||
background: var(--glass-deep); border: 1px solid var(--glass-edge);
|
||||
}
|
||||
.cover-route-lbl {
|
||||
font-family: var(--num); font-size: 7px; font-weight: 600; letter-spacing: 0.16em;
|
||||
text-transform: uppercase; color: var(--on-night-2);
|
||||
}
|
||||
.cover-route-svg { display: block; width: 100%; height: auto; }
|
||||
.cover-route-glow { color: var(--paper); }
|
||||
.cover-route-start { fill: var(--paper); }
|
||||
.cover-route-end { stroke: var(--paper); }
|
||||
.cover-ribbon { display: flex; gap: 2px; height: 5px; margin-block-start: 8mm; }
|
||||
.cover-ribbon span { flex: 1; border-radius: 3px; }
|
||||
.cover-ribbon-ends {
|
||||
display: flex; justify-content: space-between; margin-block-start: 5px;
|
||||
font-family: var(--num); font-size: 7.5px; font-weight: 600; letter-spacing: 0.12em;
|
||||
text-transform: uppercase; color: var(--on-night-2);
|
||||
}
|
||||
.cover-stats { display: flex; flex-wrap: wrap; gap: 8px; margin-block-start: 6mm; }
|
||||
.cover-stat {
|
||||
flex: 1 1 0; min-width: max-content;
|
||||
background: var(--glass-tile); border: 1px solid var(--glass-edge); border-radius: 16px;
|
||||
padding: 12px 14px 11px;
|
||||
}
|
||||
.cover-stat-num {
|
||||
font-family: var(--num); font-size: 19px; font-weight: 600; line-height: 1.1;
|
||||
white-space: nowrap; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.cover-stat-lbl {
|
||||
font-family: var(--num); font-size: 7.5px; font-weight: 500; letter-spacing: 0.14em;
|
||||
text-transform: uppercase; color: var(--on-night-2); margin-block-start: 5px;
|
||||
}
|
||||
|
||||
/* The glass is a tinted fill, not a backdrop blur: print engines leave a blur out, and
|
||||
in the preview a blur over the full-page photo had to be redrawn on every scroll. */
|
||||
|
||||
/* ── Overview: route map, the days at a glance, bookings and stays ─────── */
|
||||
.overview { padding: 2mm var(--gutter) 0; }
|
||||
.pdf-no-overview .overview { display: none; }
|
||||
.sec-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-block-end: 4mm; }
|
||||
.sec-title { font-size: calc(17px * var(--t)); font-weight: 600; letter-spacing: -0.01em; }
|
||||
.sec-block { break-inside: avoid; margin-block-end: 9mm; }
|
||||
.trip-map { margin-block-end: 9mm; }
|
||||
.trip-map-head { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; margin-block-end: 4mm; }
|
||||
.trip-map-title { font-size: calc(17px * var(--t)); font-weight: 600; letter-spacing: -0.01em; }
|
||||
.trip-map-total {
|
||||
font-family: var(--num); font-size: calc(9px * var(--t)); font-weight: 600; color: var(--ink-2);
|
||||
background: var(--wash); border-radius: 99px; padding: 4px 10px;
|
||||
}
|
||||
.trip-map-note { font-size: 9px; font-weight: 600; color: var(--gold); margin: -2mm 0 3mm; }
|
||||
.trip-map-svg { width: 100%; height: auto; border-radius: 16px; border: 1px solid var(--hair); display: block; overflow: hidden; }
|
||||
.trip-map-legend { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 5px 14px; margin-block-start: 4mm; }
|
||||
.trip-map-leg { display: flex; align-items: center; gap: 6px; min-width: 0; font-size: calc(8.5px * var(--t)); color: var(--ink-2); }
|
||||
.trip-map-leg-name { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.trip-map-dot { width: 8px; height: 8px; border-radius: 50%; }
|
||||
.trip-map-leg-dist { font-family: var(--num); color: var(--ink-4); white-space: nowrap; }
|
||||
.trip-map-credit { font-size: 7px; color: var(--ink-4); margin-block-start: 3mm; }
|
||||
|
||||
.glance { width: 100%; border-collapse: collapse; font-size: calc(8.5px * var(--t)); }
|
||||
.glance th {
|
||||
font-family: var(--num); font-size: calc(7px * var(--t)); font-weight: 600; letter-spacing: 0.12em;
|
||||
text-transform: uppercase; color: var(--ink-4); text-align: start; padding: 0 6px 6px;
|
||||
border-block-end: 1px solid var(--hair);
|
||||
}
|
||||
.glance td { padding: 6px; border-block-end: 1px solid var(--wash-2); vertical-align: top; color: var(--ink-2); }
|
||||
.glance tr { break-inside: avoid; }
|
||||
.glance-day { display: inline-flex; align-items: center; justify-content: center; min-width: 22px; height: 18px; padding: 0 5px; border-radius: 6px; background: var(--day); color: var(--paper); font-family: var(--num); font-weight: 600; font-size: calc(8px * var(--t)); }
|
||||
.glance-title { color: var(--ink); font-weight: 500; }
|
||||
.glance .num, .glance-end { text-align: end; white-space: nowrap; }
|
||||
.glance .glance-stops { text-align: center; }
|
||||
.glance .glance-date { text-align: start; }
|
||||
.glance th.glance-stops svg { display: inline-block; vertical-align: -1px; }
|
||||
|
||||
.ledger { display: grid; gap: 5px; }
|
||||
.ledger-row {
|
||||
display: grid; grid-template-columns: 26px 1fr auto; gap: 10px; align-items: center;
|
||||
padding: 7px 10px; border: 1px solid var(--hair); border-radius: 12px; break-inside: avoid;
|
||||
}
|
||||
.ledger-icon {
|
||||
width: 26px; height: 26px; border-radius: 8px; display: flex; align-items: center; justify-content: center;
|
||||
background: color-mix(in srgb, var(--kind) 14%, var(--paper)); color: var(--kind);
|
||||
}
|
||||
.ledger-title { font-weight: 600; font-size: calc(9.5px * var(--t)); }
|
||||
.ledger-sub { font-size: calc(8px * var(--t)); color: var(--ink-3); }
|
||||
.ledger-when { font-family: var(--num); font-size: calc(8px * var(--t)); color: var(--ink-3); text-align: end; white-space: nowrap; }
|
||||
|
||||
/* ── Day ─────────────────────────────────────────────────── */
|
||||
/* A real <table>, so the browser repeats the <thead> day header on every page an
|
||||
overflowing day spills onto (#1471); CSS table-header-group on a <div> is not
|
||||
repeated by Chromium's print engine. */
|
||||
.day-section { width: 100%; border-collapse: collapse; table-layout: fixed; }
|
||||
.day-break { break-before: page; }
|
||||
/* The first day always opens a page of its own, after the cover or the overview. */
|
||||
.day-first { break-before: page; }
|
||||
.pdf-flow .day-break { break-before: auto; }
|
||||
.pdf-flow .day-section + .day-section { margin-block-start: 8mm; }
|
||||
/* Hold a flowing day together where it fits, so a header is never stranded at the
|
||||
foot of a sheet with its content on the next one (#1471). */
|
||||
.pdf-flow .day-section { break-inside: avoid; page-break-inside: avoid; }
|
||||
/* The gap under the header sits inside the repeated cell: a block-start padding on the
|
||||
body is only painted on its first fragment (#1531). */
|
||||
.day-header > tr > td { padding: 0 var(--gutter) 5mm; }
|
||||
.day-head {
|
||||
display: flex; align-items: center; gap: 12px; padding-block: 3mm 3.5mm;
|
||||
border-block-end: 1px solid var(--hair); position: relative;
|
||||
}
|
||||
.day-head::after {
|
||||
content: ''; position: absolute; inset-inline-start: 0; inset-block-end: -1px;
|
||||
width: 26mm; height: 2px; border-radius: 2px; background: var(--day);
|
||||
}
|
||||
.day-tag {
|
||||
width: 42px; height: 42px; border-radius: 13px; background: var(--day); color: var(--paper);
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; flex-shrink: 0;
|
||||
}
|
||||
.day-tag-lbl { font-family: var(--num); font-size: 6.5px; font-weight: 600; letter-spacing: 0.14em; opacity: 0.85; }
|
||||
.day-tag-num { font-family: var(--num); font-size: 17px; font-weight: 600; line-height: 1; }
|
||||
.day-head-main { flex: 1; min-width: 0; }
|
||||
.day-date { font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-3); }
|
||||
.day-title { font-size: calc(17px * var(--t)); font-weight: 600; line-height: 1.25; letter-spacing: -0.01em; }
|
||||
.day-meta { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 5px; max-width: 70mm; }
|
||||
.meta-pill, .day-cost {
|
||||
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
|
||||
font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; color: var(--ink-2);
|
||||
background: var(--wash); border-radius: 99px; padding: 4px 9px;
|
||||
}
|
||||
.meta-pill svg, .day-cost svg { color: var(--ink-4); }
|
||||
.day-body { padding: 0 var(--gutter) 4mm; }
|
||||
.day-intro {
|
||||
margin-block-end: 4mm; padding: 9px 12px; border-radius: 12px; background: var(--wash);
|
||||
font-size: calc(9px * var(--t)); color: var(--ink-2); white-space: pre-line;
|
||||
}
|
||||
|
||||
/* ── Photo strip ─────────────────────────────────────────── */
|
||||
.day-strip { display: grid; gap: 4px; height: 48mm; margin-block-end: 5mm; border-radius: 16px; overflow: hidden; }
|
||||
.day-strip-1 { grid-template-columns: 1fr; }
|
||||
.day-strip-2 { grid-template-columns: 3fr 2fr; }
|
||||
.day-strip-3 { grid-template-columns: 2fr 1fr 1fr; }
|
||||
.day-strip-photo { position: relative; min-width: 0; overflow: hidden; background: var(--wash-2); }
|
||||
.day-strip-photo img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.glass-label {
|
||||
position: absolute; inset-inline-start: 8px; inset-block-end: 8px; max-width: calc(100% - 16px);
|
||||
padding: 4px 10px; border-radius: 99px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
font-size: calc(8px * var(--t)); font-weight: 500; color: var(--paper);
|
||||
background: var(--glass-dark); border: 1px solid var(--glass-edge);
|
||||
}
|
||||
.pdf-no-photos .day-strip { display: none; }
|
||||
|
||||
/* ── Stays ───────────────────────────────────────────────── */
|
||||
.day-accommodations { display: grid; grid-template-columns: repeat(auto-fit, minmax(80mm, 1fr)); gap: 6px; margin-block-end: 5mm; }
|
||||
.day-accommodation {
|
||||
display: flex; gap: 10px; align-items: center; padding: 8px 10px;
|
||||
border: 1px solid var(--hair); border-radius: 14px; break-inside: avoid;
|
||||
}
|
||||
.day-accommodation.stay-quiet { padding: 6px 10px; background: var(--wash); border-color: transparent; }
|
||||
.stay-media {
|
||||
width: 40px; height: 40px; border-radius: 11px; overflow: hidden; flex-shrink: 0;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
background: color-mix(in srgb, var(--day) 12%, var(--paper)); color: var(--day);
|
||||
}
|
||||
.stay-quiet .stay-media { width: 26px; height: 26px; border-radius: 8px; }
|
||||
.stay-media img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.pdf-no-photos .stay-media img { display: none; }
|
||||
.stay-main { flex: 1; min-width: 0; }
|
||||
.stay-kicker { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase; color: var(--day); }
|
||||
.stay-name { font-size: calc(10.5px * var(--t)); font-weight: 600; line-height: 1.35; }
|
||||
.stay-quiet .stay-name { font-size: calc(9px * var(--t)); font-weight: 500; }
|
||||
.stay-line { font-size: calc(8.5px * var(--t)); color: var(--ink-3); }
|
||||
.stay-extra { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 4px; }
|
||||
|
||||
/* ── Timeline ────────────────────────────────────────────── */
|
||||
.timeline { list-style: none; }
|
||||
.tl-item { display: grid; grid-template-columns: 13mm 22px minmax(0, 1fr); column-gap: 8px; break-inside: avoid; }
|
||||
.tl-time { text-align: end; padding-block-start: 11px; font-family: var(--num); font-variant-numeric: tabular-nums; }
|
||||
.tl-start { display: block; font-size: calc(9.5px * var(--t)); font-weight: 600; color: var(--ink); }
|
||||
.tl-end { display: block; font-size: calc(8px * var(--t)); color: var(--ink-4); }
|
||||
.tl-rail { position: relative; display: flex; justify-content: center; }
|
||||
.tl-rail::before {
|
||||
content: ''; position: absolute; inset-block: 0; inset-inline-start: calc(50% - 0.75px); width: 1.5px;
|
||||
background: color-mix(in srgb, var(--day) 26%, var(--paper));
|
||||
}
|
||||
.tl-item:first-child .tl-rail::before { inset-block-start: 14px; }
|
||||
.tl-item:last-child .tl-rail::before { inset-block-end: auto; height: 14px; }
|
||||
.tl-item:only-child .tl-rail::before { display: none; }
|
||||
.tl-marker {
|
||||
position: relative; margin-block-start: 8px; width: 22px; height: 22px; border-radius: 50%;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
background: var(--paper); border: 1.5px solid var(--day); color: var(--day);
|
||||
font-family: var(--num); font-size: calc(8.5px * var(--t)); font-weight: 600;
|
||||
}
|
||||
.tl-place .tl-marker { background: var(--day); color: var(--paper); }
|
||||
.tl-booking .tl-marker { border-color: var(--kind); color: var(--kind); }
|
||||
.tl-note .tl-marker { width: 10px; height: 10px; margin-block-start: 13px; background: var(--wash-2); border-color: var(--wash-2); }
|
||||
.tl-body { padding-block: 3px 7px; min-width: 0; }
|
||||
.empty-day { padding: 10mm 0; text-align: center; color: var(--ink-4); font-size: calc(9px * var(--t)); }
|
||||
|
||||
/* ── Place ───────────────────────────────────────────────── */
|
||||
.place-card {
|
||||
display: flex; gap: 11px; padding: 10px; border: 1px solid var(--hair); border-radius: 14px;
|
||||
background: var(--paper); break-inside: avoid;
|
||||
}
|
||||
.place-thumb, .place-thumb-fallback { width: 74px; height: 74px; border-radius: 11px; flex-shrink: 0; }
|
||||
.place-thumb { object-fit: cover; }
|
||||
.place-thumb-fallback {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
background: color-mix(in srgb, var(--cat) 14%, var(--paper)); color: var(--cat);
|
||||
}
|
||||
.pdf-no-photos .place-thumb, .pdf-no-photos .place-thumb-fallback { display: none; }
|
||||
.place-info { flex: 1; min-width: 0; }
|
||||
.place-name-row { display: flex; align-items: flex-start; gap: 8px; }
|
||||
.place-name { flex: 1; font-size: calc(12px * var(--t)); font-weight: 600; line-height: 1.3; letter-spacing: -0.005em; }
|
||||
.cat-badge {
|
||||
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; flex-shrink: 0;
|
||||
font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600;
|
||||
border-radius: 99px; padding: 3px 8px;
|
||||
background: color-mix(in srgb, var(--cat) 13%, var(--paper));
|
||||
color: color-mix(in srgb, var(--cat) 78%, var(--ink));
|
||||
}
|
||||
.facts { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 5px; }
|
||||
.chip {
|
||||
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
|
||||
font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 500; color: var(--ink-2);
|
||||
background: var(--wash); border-radius: 99px; padding: 2px 8px;
|
||||
}
|
||||
.chip svg { color: var(--ink-4); }
|
||||
.chip-rating { color: var(--gold); }
|
||||
.chip-rating svg { color: var(--gold); fill: var(--gold); }
|
||||
.chip-tag { background: color-mix(in srgb, var(--tag) 12%, var(--paper)); color: color-mix(in srgb, var(--tag) 75%, var(--ink)); }
|
||||
.chip-tag::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--tag); }
|
||||
.code-chip {
|
||||
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
|
||||
font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.04em;
|
||||
color: var(--ink); background: var(--wash-2); border-radius: 6px; padding: 2px 7px;
|
||||
}
|
||||
.code-chip svg { color: var(--ink-3); }
|
||||
.info-row { display: flex; align-items: flex-start; gap: 5px; margin-block-start: 4px; }
|
||||
.info-row svg { color: var(--ink-4); margin-block-start: 1px; }
|
||||
.info-text { font-size: calc(8.5px * var(--t)); color: var(--ink-2); line-height: 1.5; min-width: 0; }
|
||||
.info-text.muted { color: var(--ink-3); }
|
||||
.info-spacer { display: none; }
|
||||
.coords { font-family: var(--num); color: var(--ink-4); font-size: calc(8px * var(--t)); }
|
||||
.pdf-no-coords .coords { display: none; }
|
||||
.place-text { margin-block-start: 5px; font-size: calc(9px * var(--t)); color: var(--ink-2); line-height: 1.55; }
|
||||
.place-text .info-row { margin: 0; }
|
||||
.place-text .info-text { font-size: inherit; color: inherit; }
|
||||
.place-note {
|
||||
margin-block-start: 6px; padding: 6px 9px; border-radius: 9px; background: var(--wash);
|
||||
font-size: calc(8.5px * var(--t)); color: var(--ink-2);
|
||||
}
|
||||
.place-note .info-row { margin: 0; }
|
||||
.place-note .info-text { color: inherit; }
|
||||
.details { display: flex; flex-wrap: wrap; gap: 3px 12px; margin-block-start: 6px; }
|
||||
.detail { display: inline-flex; align-items: center; gap: 4px; font-size: calc(8px * var(--t)); color: var(--ink-3); }
|
||||
.detail svg { color: var(--ink-4); }
|
||||
.pdf-no-details .details { display: none; }
|
||||
${PDF_MARKDOWN_CSS}
|
||||
|
||||
/* ── Bookings and notes ──────────────────────────────────── */
|
||||
.note-card {
|
||||
display: flex; gap: 10px; align-items: flex-start; padding: 9px 11px; border-radius: 14px;
|
||||
break-inside: avoid; background: var(--wash);
|
||||
}
|
||||
.booking-card {
|
||||
background: color-mix(in srgb, var(--kind) 6%, var(--paper));
|
||||
border: 1px solid color-mix(in srgb, var(--kind) 20%, var(--paper));
|
||||
}
|
||||
.note-icon {
|
||||
width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0;
|
||||
display: flex; align-items: center; justify-content: center; color: var(--ink-3); background: var(--paper);
|
||||
}
|
||||
.booking-card .note-icon { background: var(--kind); color: var(--paper); }
|
||||
.note-tinted { border-inline-start: 3px solid var(--note); }
|
||||
.note-tinted .note-icon { color: var(--note); }
|
||||
.note-body { flex: 1; min-width: 0; }
|
||||
.note-kicker { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase; color: var(--kind, var(--ink-3)); }
|
||||
.note-text { font-size: calc(9.5px * var(--t)); color: var(--ink); line-height: 1.5; }
|
||||
.booking-card .note-text { font-size: calc(11px * var(--t)); font-weight: 600; line-height: 1.35; }
|
||||
.note-time { font-size: calc(8.5px * var(--t)); color: var(--ink-3); margin-block-start: 2px; white-space: pre-line; }
|
||||
.note-line { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-block-start: 4px; }
|
||||
.note-line .route { font-family: var(--num); font-size: calc(9px * var(--t)); font-weight: 600; color: var(--ink); margin-inline-end: 2px; }
|
||||
.booking-card .chip { background: var(--paper); }
|
||||
.note-extra { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 5px; }
|
||||
.transport-note { font-style: italic; white-space: pre-line; }
|
||||
.pdf-no-transport-notes .transport-note { display: none; }
|
||||
|
||||
/* ── Plugin sections ─────────────────────────────────────── */
|
||||
.plugin-sections { padding: 2mm var(--gutter) 4mm; }
|
||||
.plugin-section { margin-block-end: 6mm; break-inside: avoid; }
|
||||
.plugin-section-title { font-size: calc(13px * var(--t)); font-weight: 600; margin-block-end: 2mm; padding-block-end: 2mm; border-block-end: 1px solid var(--hair); }
|
||||
.plugin-section-text { font-size: calc(9.5px * var(--t)); color: var(--ink-2); line-height: 1.55; margin-block-end: 5px; }
|
||||
.plugin-section-table { width: 100%; border-collapse: collapse; margin-block-start: 6px; }
|
||||
.plugin-section-table th { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; color: var(--ink-4); text-transform: uppercase; letter-spacing: 0.1em; text-align: start; padding: 4px 8px; border-block-end: 1px solid var(--hair); }
|
||||
.plugin-section-table td { font-size: calc(9px * var(--t)); color: var(--ink-2); padding: 4px 8px; border-block-end: 1px solid var(--wash-2); }
|
||||
|
||||
.doc-end { display: flex; align-items: center; justify-content: center; gap: 6px; padding: 8mm 0 4mm; color: var(--ink-4); font-size: 7.5px; letter-spacing: 0.06em; }
|
||||
.doc-end img { height: 10px; opacity: 0.55; }
|
||||
`;
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNod
|
||||
import type { PlaceClientOrigin, RoadtripStopType, TourListItem } from '@trek/shared'
|
||||
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'
|
||||
@@ -120,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,
|
||||
|
||||
@@ -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(), {
|
||||
|
||||
@@ -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={[
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// FE-PLANNER-TRANSITDISPLAY-001 to FE-PLANNER-TRANSITDISPLAY-003
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import type { TransitLegDisplay } from './transitDisplay';
|
||||
import { TransitItineraryInline, TransitWalkDivider } from './transitDisplay';
|
||||
|
||||
const t = (key: string, params?: Record<string, string | number>) =>
|
||||
params ? `${key}:${Object.values(params).join(',')}` : key;
|
||||
|
||||
const ride: TransitLegDisplay = {
|
||||
mode: 'RAIL',
|
||||
line: 'XC',
|
||||
duration: 1260,
|
||||
from: { name: 'Basingstoke', time: '12:48' },
|
||||
to: { name: 'Reading', time: '13:09' },
|
||||
};
|
||||
const walk: TransitLegDisplay = { mode: 'WALK', duration: 240, to: { name: 'Reading station, Station Approach' } };
|
||||
|
||||
/** Whether a rendered element clips its text to one line. */
|
||||
function clipsToOneLine(el: HTMLElement): boolean {
|
||||
return el.style.whiteSpace === 'nowrap' || el.style.textOverflow === 'ellipsis';
|
||||
}
|
||||
|
||||
describe('TransitItineraryInline (#3139)', () => {
|
||||
it('FE-PLANNER-TRANSITDISPLAY-001: a ride shows both stop names in full', () => {
|
||||
render(<TransitItineraryInline legs={[ride]} t={t} />);
|
||||
for (const name of ['Basingstoke', 'Reading']) {
|
||||
const el = screen.getByText(name);
|
||||
expect(clipsToOneLine(el)).toBe(false);
|
||||
expect(el.style.overflowWrap).toBe('anywhere');
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSITDISPLAY-002: a ride shows its arrival time under its departure', () => {
|
||||
render(<TransitItineraryInline legs={[ride, { ...ride, to: { name: 'Oxford' } }]} t={t} />);
|
||||
expect(screen.getByText('13:09')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('12:48')).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransitWalkDivider (#3139)', () => {
|
||||
it('FE-PLANNER-TRANSITDISPLAY-003: the walk target wraps instead of being cut off', () => {
|
||||
render(<TransitWalkDivider leg={walk} t={t} size="sm" />);
|
||||
const text = screen.getByText(/transit\.walkTo:Reading station, Station Approach/);
|
||||
expect(clipsToOneLine(text)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -41,14 +41,14 @@ export function TransitWalkDivider({ leg, t, size = 'md' }: {
|
||||
background: `linear-gradient(to ${dir}, var(--text-faint), transparent)`,
|
||||
opacity: 0.55,
|
||||
})
|
||||
// On phones the minutes lead so a long stop name only ever clips the name.
|
||||
// On phones the minutes lead, so they stay on the first line when a long stop name wraps.
|
||||
const text = isMobile
|
||||
? `${mins ? `${t('transit.min', { count: mins })} · ` : ''}${t('transit.walkTo', { name: leg.to?.name || '' })}`
|
||||
: `${t('transit.walkTo', { name: leg.to?.name || '' })}${mins ? ` · ${t('transit.min', { count: mins })}` : ''}`
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: size === 'sm' ? '1px 0' : '2px 0' }}>
|
||||
<span style={rule('left')} />
|
||||
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: isMobile ? '85%' : '75%' }}>
|
||||
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, textAlign: 'center', overflowWrap: 'anywhere', maxWidth: isMobile ? '85%' : '75%' }}>
|
||||
<Footprints size={size === 'sm' ? 11 : 12} style={{ flexShrink: 0 }} />
|
||||
{text}
|
||||
</span>
|
||||
@@ -72,8 +72,10 @@ export function TransitItineraryInline({ legs, t }: {
|
||||
const mins = leg.duration ? Math.round(leg.duration / 60) : null
|
||||
return (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
|
||||
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
|
||||
{leg.from?.time || ''}
|
||||
{/* Departure beside the stops, arrival under it (#3139). */}
|
||||
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, alignSelf: 'stretch', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
|
||||
<span>{leg.from?.time || ''}</span>
|
||||
{leg.to?.time && <span className="text-content-faint">{leg.to.time}</span>}
|
||||
</span>
|
||||
<span style={{
|
||||
display: 'inline-flex', alignItems: 'center', borderRadius: 4, padding: '0 5px',
|
||||
@@ -84,10 +86,11 @@ export function TransitItineraryInline({ legs, t }: {
|
||||
{leg.line || leg.mode}
|
||||
</span>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 }}>
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.from?.name}</span>
|
||||
{/* The folded-out itinerary is where a journey is read in full: stop names wrap (#3139). */}
|
||||
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', flexWrap: 'wrap', alignItems: 'center', columnGap: 4, minWidth: 0 }}>
|
||||
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.from?.name}</span>
|
||||
<MoveRight size={10} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.to?.name}</span>
|
||||
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.to?.name}</span>
|
||||
</div>
|
||||
<div className="text-content-faint" style={{ fontSize: 'calc(9.5px * var(--fs-scale-caption, 1))', marginTop: 1 }}>
|
||||
{[
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { buildDay } from '../../../tests/helpers/factories';
|
||||
import type { Accommodation } from '../../types';
|
||||
import { orderTransitStaysByDate } from './transitStayOrder';
|
||||
|
||||
const day = buildDay({ id: 500, date: '2027-03-21', day_number: 21 });
|
||||
const stay = (id: number, start: number, end = start) =>
|
||||
({ id, start_day_id: start, end_day_id: end }) as Accommodation;
|
||||
const refs = [
|
||||
buildDay({ id: 900, date: '2027-03-01', day_number: 1 }),
|
||||
buildDay({ id: 700, date: '2027-03-19', day_number: 19 }),
|
||||
buildDay({ id: 600, date: '2027-03-20', day_number: 20 }),
|
||||
day,
|
||||
buildDay({ id: 400, date: '2027-03-22', day_number: 22 }),
|
||||
buildDay({ id: 300, date: '2027-03-23', day_number: 23 }),
|
||||
];
|
||||
const ids = (stays: Accommodation[]) => stays.map((a) => a.id);
|
||||
|
||||
describe('orderTransitStaysByDate', () => {
|
||||
it('uses the whole interval: an early check-in with a nearby checkout is close', () => {
|
||||
const spanning = stay(1, 900, 600);
|
||||
const future = stay(2, 400, 300);
|
||||
const farther = stay(3, 700);
|
||||
expect(ids(orderTransitStaysByDate(day, refs, [farther, future, spanning]))).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('puts the earlier interval first at equal distance, then earlier checkout and stable stay id', () => {
|
||||
const list = [stay(90, 400, 300), stay(2, 600), stay(80, 400, 300), stay(100, 400)];
|
||||
expect(ids(orderTransitStaysByDate(day, refs, list))).toEqual([2, 100, 80, 90]);
|
||||
expect(ids(orderTransitStaysByDate(day, refs, list.slice().reverse()))).toEqual([2, 100, 80, 90]);
|
||||
});
|
||||
|
||||
it('places missing, incomplete and invalid calendar dates after dated stays', () => {
|
||||
const dates = [
|
||||
...refs,
|
||||
buildDay({ id: 10, date: null }),
|
||||
buildDay({ id: 11, date: '2027-02-30' }),
|
||||
buildDay({ id: 12, date: 'not-a-date' }),
|
||||
];
|
||||
const list = [stay(4, 10), stay(3, 11), stay(2, 12), stay(5, 600, 10), stay(6, 99999), stay(9, 900)];
|
||||
expect(ids(orderTransitStaysByDate(day, dates, list))).toEqual([9, 2, 3, 4, 5, 6]);
|
||||
});
|
||||
|
||||
it('handles leap days without accepting a normalized invalid date', () => {
|
||||
const selected = buildDay({ id: 1, date: '2028-03-01' });
|
||||
const dates = [selected, buildDay({ id: 2, date: '2028-02-29' }), buildDay({ id: 3, date: '2027-02-29' })];
|
||||
expect(ids(orderTransitStaysByDate(selected, dates, [stay(1, 3), stay(2, 2)]))).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('uses updated calendar dates after days are reordered, regardless of array order or numeric ids', () => {
|
||||
const before = stay(1, 600);
|
||||
const after = stay(2, 400);
|
||||
const reordered = refs
|
||||
.map((d) =>
|
||||
d.id === 600
|
||||
? { ...d, date: '2027-03-22', day_number: 22 }
|
||||
: d.id === 400
|
||||
? { ...d, date: '2027-03-20', day_number: 20 }
|
||||
: d
|
||||
)
|
||||
.reverse();
|
||||
expect(ids(orderTransitStaysByDate(day, refs, [after, before]))).toEqual([1, 2]);
|
||||
expect(ids(orderTransitStaysByDate(day, reordered, [before, after]))).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('counts calendar nights equally across the spring DST boundary', () => {
|
||||
const selected = buildDay({ id: 1, date: '2027-03-29' });
|
||||
const dates = [selected, buildDay({ id: 2, date: '2027-03-28' }), buildDay({ id: 3, date: '2027-03-30' })];
|
||||
expect(ids(orderTransitStaysByDate(selected, dates, [stay(1, 3), stay(2, 2)]))).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('normalizes reversed interval endpoints consistently with day-range membership', () => {
|
||||
expect(ids(orderTransitStaysByDate(day, refs, [stay(1, 700), stay(2, 300, 600)]))).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('keeps dated stays ahead of undated ones when the selected day has no usable date', () => {
|
||||
const selected = { ...day, date: null };
|
||||
expect(ids(orderTransitStaysByDate(selected, refs, [stay(1, 99999), stay(3, 300), stay(2, 900)]))).toEqual([
|
||||
2, 3, 1,
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not mutate the caller list', () => {
|
||||
const list = Object.freeze([stay(1, 300), stay(2, 600)]);
|
||||
expect(ids(orderTransitStaysByDate(day, refs, list))).toEqual([2, 1]);
|
||||
expect(ids([...list])).toEqual([1, 2]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Accommodation, Day } from '../../types';
|
||||
|
||||
/** A strict calendar date as a UTC day number, so DST never changes the number of nights. */
|
||||
function nightNumber(value: string | null | undefined): number | null {
|
||||
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
|
||||
const time = Date.parse(`${value}T00:00:00Z`);
|
||||
if (!Number.isFinite(time) || new Date(time).toISOString().slice(0, 10) !== value) return null;
|
||||
return time / 86_400_000;
|
||||
}
|
||||
|
||||
/** Rank other-day stays by the closest boundary of their complete booking interval. */
|
||||
export function orderTransitStaysByDate(
|
||||
day: Pick<Day, 'date'>,
|
||||
days: readonly Pick<Day, 'id' | 'date'>[],
|
||||
stays: readonly Accommodation[]
|
||||
): Accommodation[] {
|
||||
const selected = nightNumber(day.date);
|
||||
const dates = new Map(days.map((d) => [d.id, nightNumber(d.date)]));
|
||||
return stays
|
||||
.map((stay) => {
|
||||
const start = dates.get(stay.start_day_id);
|
||||
const end = dates.get(stay.end_day_id);
|
||||
// A partial or invalid interval has no usable proximity and follows every dated stay.
|
||||
const lo = start != null && end != null ? Math.min(start, end) : Infinity;
|
||||
const hi = start != null && end != null ? Math.max(start, end) : Infinity;
|
||||
const distance = selected != null && lo !== Infinity ? Math.max(lo - selected, selected - hi, 0) : Infinity;
|
||||
// Earlier check-in, then earlier check-out, then stable booking identity break ties.
|
||||
return { stay, rank: [distance, lo, hi, stay.id] };
|
||||
})
|
||||
.sort((a, b) => {
|
||||
for (let i = 0; i < a.rank.length; i++) {
|
||||
if (a.rank[i] !== b.rank[i]) return a.rank[i] < b.rank[i] ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
})
|
||||
.map((row) => row.stay);
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
// FE-PLANNER-TRIPEXPORT-001 to -014: the trip exports behind the desktop export
|
||||
// FE-PLANNER-TRIPEXPORT-001 to -015: the trip exports behind the desktop export
|
||||
// dialog and the phone's export sheet.
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
|
||||
|
||||
import { buildAssignment, buildReservation, buildTrip, buildUser } from '../../../tests/helpers/factories';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripAddonsStore } from '../../store/tripAddonsStore';
|
||||
import type { DayNote } from '../../types';
|
||||
import { downloadTripPDF } from '../PDF/TripPDF';
|
||||
import { flatDayNotes, saveBlob, useTripExport, type TripExportOptions } from './useTripExport';
|
||||
@@ -133,6 +134,17 @@ describe('useTripExport', () => {
|
||||
expect(vi.mocked(downloadTripPDF).mock.calls[1][0]).toMatchObject({ onlyUserId: 9 });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRIPEXPORT-015: the PDF prints costs and tours as the trip has them, not the instance', async () => {
|
||||
seedInstanceAddons(['budget']);
|
||||
useTripAddonsStore.getState().publish(3, [
|
||||
{ id: 'budget', name: 'Costs', icon: null, enabled: false, instanceEnabled: true, overridden: true },
|
||||
{ id: 'tours', name: 'Tours', icon: null, enabled: true, instanceEnabled: false, overridden: true },
|
||||
]);
|
||||
const { result } = renderHook(() => useTripExport(options()));
|
||||
await act(() => result.current.exportPdf());
|
||||
expect(vi.mocked(downloadTripPDF).mock.calls[0][0]).toMatchObject({ costsEnabled: false, toursEnabled: true });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRIPEXPORT-005: the phone stays open after the PDF and prints nothing without a trip', async () => {
|
||||
const opts = options(PHONE);
|
||||
const { result } = renderHook(() => useTripExport(opts));
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripAddonEnabled } from '../../store/tripAddonsStore';
|
||||
import type { AssignmentsMap, Category, Day, DayNote, Place, Reservation, Trip } from '../../types';
|
||||
import { importChunk } from '../../utils/chunkReload';
|
||||
import type { ViasByDay } from '../../utils/dayRouteVias';
|
||||
@@ -144,6 +145,9 @@ export function useTripExport({
|
||||
// them, so it needs the same switch the plan reads.
|
||||
const showServiceStops = useRoadtripSettings((s) => s.roadtrip_service_stops_in_days !== false, tripId);
|
||||
const myId = useAuthStore((s) => s.user?.id);
|
||||
// The sections the trip has on, as the plan shows them: costs in the figures, tours on the route.
|
||||
const costsEnabled = useTripAddonEnabled(tripId, 'budget');
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours');
|
||||
const offerMine = myId != null && hasPersonalPlan(data.assignments, data.reservations);
|
||||
const fileBase = data.trip?.title || 'trip';
|
||||
|
||||
@@ -185,6 +189,8 @@ export function useTripExport({
|
||||
timeFormat,
|
||||
distanceUnit,
|
||||
showServiceStops,
|
||||
costsEnabled,
|
||||
toursEnabled,
|
||||
onlyUserId: mine ? myId : undefined,
|
||||
route: { viasByDay: data.viasByDay, tourStageStops: data.tourStageStops, ...routing },
|
||||
signal: givenUp,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { dayColor } from './dayColors'
|
||||
import { stageMapData, stagePlaceIds, stagePoints } from './stageMap'
|
||||
import { stageConnectionIds, stageMapData, stagePlaceIds, stagePoints } from './stageMap'
|
||||
import type { AccessSpur, RoadtripDay, RoadtripRoutes, RoadtripStop } from '@trek/shared/roadtrip'
|
||||
|
||||
// FE-RTSTAGE-001 to FE-RTSTAGE-021
|
||||
// FE-RTSTAGE-001 to FE-RTSTAGE-023
|
||||
|
||||
function stop(name: string, over: Partial<RoadtripStop> = {}): RoadtripStop {
|
||||
return {
|
||||
@@ -125,14 +125,15 @@ describe('stageMapData with a stage', () => {
|
||||
expect(stageMapData(routes(), stage, true).lines).toEqual([LINES[1], LINES[2]])
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-016: the drive into the next day is left off the stage', () => {
|
||||
// With "connect the days" on, that leg is drawn in the colour of the day it leaves, so
|
||||
it('FE-RTSTAGE-016: the drive in from the day before is left off the stage', () => {
|
||||
// With "connect the days" on, that leg is drawn as the day it arrives on (#3123), so
|
||||
// filtering by day number alone handed the stage a line running off it to a place the
|
||||
// day never visits. On a phone, where the stage IS the map, it was the longest thing
|
||||
// on screen and read as the day's own route.
|
||||
const withJoin = routes({ lineJoins: [false, false, true, false] })
|
||||
// on screen and read as the day's own route. The assembler emits it first among the
|
||||
// lines of the day it reaches, ahead of that day's own legs.
|
||||
const withJoin = routes({ lineJoins: [false, true, false, false] })
|
||||
|
||||
expect(stageMapData(withJoin, stage, true).lines).toEqual([LINES[1]])
|
||||
expect(stageMapData(withJoin, stage, true).lines).toEqual([LINES[2]])
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-020: a day that is nothing but driving keeps its connection rather than going blank', () => {
|
||||
@@ -144,7 +145,7 @@ describe('stageMapData with a stage', () => {
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-017: the colours still line up once a join has been dropped', () => {
|
||||
const data = stageMapData(routes({ lineJoins: [false, false, true, false] }), stage, true)
|
||||
const data = stageMapData(routes({ lineJoins: [false, true, false, false] }), stage, true)
|
||||
|
||||
expect(data.lineColors).toHaveLength(data.lines.length)
|
||||
expect(data.lineColors).toEqual([dayColor(2)])
|
||||
@@ -153,7 +154,7 @@ describe('stageMapData with a stage', () => {
|
||||
it('FE-RTSTAGE-018: the all-days view keeps the joins, which is the view they are for', () => {
|
||||
// The setting draws the whole drive as one connected line; that is what it is for, and
|
||||
// on this map the connection has the other days beside it.
|
||||
expect(stageMapData(routes({ lineJoins: [false, false, true, false] }), null, true).lines).toEqual(LINES)
|
||||
expect(stageMapData(routes({ lineJoins: [false, true, false, false] }), null, true).lines).toEqual(LINES)
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-019: routes from before the flag existed are drawn as they were', () => {
|
||||
@@ -267,3 +268,23 @@ describe('a stage that starts or ends at a booked night', () => {
|
||||
expect(data.accessLines).toEqual([walk])
|
||||
})
|
||||
})
|
||||
|
||||
describe('stageConnectionIds', () => {
|
||||
const flight = (reservationId: number, role: 'arrival' | 'departure') =>
|
||||
stop('Airport', { carrier: { reservationId, type: 'flight', role, title: 'Flight', code: null, at: null } })
|
||||
|
||||
it("FE-RTSTAGE-022: a stage draws its own rides, not the drive's ride home from a later day", () => {
|
||||
// The flight in (31) seams this stage; the flight home (32) belongs to a stage days later
|
||||
// and is not on this one at all.
|
||||
const stage = day([flight(31, 'arrival'), stop('Ubud')])
|
||||
expect(stageConnectionIds(stage, [], () => true)).toEqual([31])
|
||||
})
|
||||
|
||||
it('FE-RTSTAGE-023: of the bookings switched on by hand only those running on the stage day stay', () => {
|
||||
const stage = day([stop('Ubud')])
|
||||
const onThisDay = new Set([40])
|
||||
expect(stageConnectionIds(stage, [40, 41], id => onThisDay.has(id))).toEqual([40])
|
||||
// A ride that seams the stage stays even when it was booked on another day.
|
||||
expect(stageConnectionIds(day([flight(31, 'arrival')]), [31], () => false)).toEqual([31])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { dayColor } from './dayColors'
|
||||
import { carrierReservationIds } from '@trek/shared/roadtrip'
|
||||
import type { AccessSpur, RoadtripDay, RoadtripRoutes } from '@trek/shared/roadtrip'
|
||||
|
||||
/**
|
||||
@@ -50,15 +51,15 @@ export function stageMapData(
|
||||
}
|
||||
if (!routes.lines.length) return { ...EMPTY, placeIds: stagePlaceIds(stage), focusPoints: stagePoints(stage) }
|
||||
|
||||
// A stage is ONE day, so the drive into the next day is left off it.
|
||||
// A stage is ONE day, so the drive in from the day before is left off it.
|
||||
//
|
||||
// With "connect the days" on, that leg is drawn in the colour of the day it leaves, so
|
||||
// on the whole-drive map it reads as that day carrying on. Filtering by day number
|
||||
// alone therefore handed a stage a line that runs off it to a place the day never
|
||||
// visits: on a phone, where the stage IS the map, that read as the day's own route and
|
||||
// was the longest thing on screen. The desktop has the same connection, but it has it
|
||||
// beside every other day, which is the view the setting exists for; here that view is
|
||||
// the "all days" one, a tap away on the same map.
|
||||
// With "connect the days" on, that leg is drawn as the day it arrives on, the day whose
|
||||
// distance counts it. Filtering by day number alone therefore handed a stage a line
|
||||
// that runs off it to a place the day never visits: on a phone, where the stage IS the
|
||||
// map, that read as the day's own route and was the longest thing on screen. The
|
||||
// desktop has the same connection, but it has it beside every other day, which is the
|
||||
// view the setting exists for; here that view is the "all days" one, a tap away on the
|
||||
// same map.
|
||||
const ofDay: number[] = []
|
||||
routes.lineDays.forEach((n, i) => { if (n === stage.dayNumber) ofDay.push(i) })
|
||||
const own = ofDay.filter(i => !routes.lineJoins?.[i])
|
||||
@@ -88,6 +89,20 @@ export function stagePlaceIds(stage: RoadtripDay): Set<number> {
|
||||
return new Set(stage.stops.filter(s => !s.automaticNight).map(s => s.placeId))
|
||||
}
|
||||
|
||||
/**
|
||||
* The bookings the map draws as arcs on ONE stage: the rides that seam this stage's
|
||||
* drive, whatever day they were booked on, and of the ones switched on by hand only
|
||||
* those that run on the stage's day. Taking the rides of the whole drive put a flight
|
||||
* home across every stage before it, as if it were part of that day.
|
||||
*/
|
||||
export function stageConnectionIds(
|
||||
stage: RoadtripDay,
|
||||
switchedOn: readonly number[],
|
||||
runsOnStageDay: (reservationId: number) => boolean,
|
||||
): number[] {
|
||||
return [...new Set([...switchedOn.filter(runsOnStageDay), ...carrierReservationIds([stage])])]
|
||||
}
|
||||
|
||||
/** The stage's stops as coordinates, for the fit. */
|
||||
export function stagePoints(stage: RoadtripDay): [number, number][] {
|
||||
return stage.stops
|
||||
|
||||
@@ -631,7 +631,7 @@ describe('useRoadtripRoutes', () => {
|
||||
expect(result.current.totalDistance).toBe(300000)
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-ROUTES-022: the joining stroke wears the day it leaves, its kilometres the day it reaches', async () => {
|
||||
it('FE-ROADTRIP-ROUTES-022: the joining stroke wears the day it reaches, like its kilometres (#3123)', async () => {
|
||||
setting({ roadtrip_connect_days: true })
|
||||
const { days: daysList, assignments } = twoDays()
|
||||
const { result } = renderHook(() => useRoadtripRoutes(7, daysList, assignments))
|
||||
@@ -639,10 +639,9 @@ describe('useRoadtripRoutes', () => {
|
||||
|
||||
// Same length and same order as `lines`, or a colour lands on the wrong day.
|
||||
expect(result.current.lineDays).toHaveLength(result.current.lines.length)
|
||||
// The stroke starts at a stop on day 1, so drawing it as day 2 would make day 2
|
||||
// look like it begins somewhere it has no stop.
|
||||
expect(result.current.lineDays).toEqual([1, 1, 2])
|
||||
// The kilometres go the other way: they are driven on the day they arrive.
|
||||
// Day 1 ends at its last stop, so the drive on to day 2 is driven on day 2: its
|
||||
// kilometres are counted there, and drawn in day 1's colour the map said otherwise.
|
||||
expect(result.current.lineDays).toEqual([1, 2, 2])
|
||||
expect(result.current.days.map(d => d.distance)).toEqual([100000, 200000])
|
||||
})
|
||||
|
||||
@@ -666,7 +665,8 @@ describe('useRoadtripRoutes', () => {
|
||||
|
||||
setting({ roadtrip_connect_days: true })
|
||||
expect(result.current.lines).toHaveLength(3)
|
||||
expect(result.current.lineDays).toEqual([1, 2, 2])
|
||||
// The drive past midnight lands on day 2 and is drawn there, like day 2's own legs.
|
||||
expect(result.current.lineDays).toEqual([2, 2, 2])
|
||||
expect(result.current.days[0].distance).toBe(300000)
|
||||
})
|
||||
|
||||
|
||||
@@ -447,7 +447,28 @@ describe('CollectionToursSection', () => {
|
||||
expect(await screen.findByTestId('kept-tour-preview')).toBeInTheDocument();
|
||||
unmount();
|
||||
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
|
||||
const off = { response: { status: 404, data: { error: 'Tours addon is not enabled' } } };
|
||||
list.mockRejectedValue(off);
|
||||
render(<CollectionToursSection collectionId={3} canRemove />);
|
||||
await waitFor(() => expect(list).toHaveBeenLastCalledWith(3));
|
||||
expect(screen.queryByTestId('collection-tours')).toBeNull();
|
||||
expect(screen.queryByText('The tours of this list could not be loaded.')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COLLECTION-TOURS-021: with Tours off for the instance, the tours show once the server hands them over', async () => {
|
||||
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
|
||||
// A trip of the user switched Tours on for itself, so the server answers.
|
||||
vi.spyOn(collectionToursRepo, 'list').mockResolvedValue({ tours: [kept()] });
|
||||
render(<CollectionToursSection collectionId={3} canRemove />);
|
||||
expect(await screen.findByTestId('kept-tour-4')).toHaveTextContent('Ridge');
|
||||
});
|
||||
|
||||
it('FE-COLLECTION-TOURS-022: with Tours off for the instance, a failed read shows nothing, as it always did', async () => {
|
||||
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
|
||||
const list = vi.spyOn(collectionToursRepo, 'list').mockRejectedValue(new Error('500'));
|
||||
render(<CollectionToursSection collectionId={3} canRemove />);
|
||||
await waitFor(() => expect(list).toHaveBeenCalled());
|
||||
expect(screen.queryByText('The tours of this list could not be loaded.')).toBeNull();
|
||||
expect(screen.queryByTestId('collection-tours')).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -13,23 +13,26 @@ import { useToast } from '../../shared/Toast';
|
||||
/**
|
||||
* LIB-03: the tours a collection keeps, for the collection's page. Read when
|
||||
* the collection opens and kept current while its members keep or remove one;
|
||||
* nothing at all while the Tours addon is off. Removing asks first and says
|
||||
* nothing at all while the Tours addon is off. Tours counts as on while the
|
||||
* instance has it on or any of the user's trips switched it on for itself;
|
||||
* only the server knows the second, so with the instance off the tours are
|
||||
* read all the same and its refusal hides them. Removing asks first and says
|
||||
* how it went.
|
||||
*/
|
||||
export function useCollectionTours(collectionId: number) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const enabled = useAddonStore((state) => state.isEnabled('tours'));
|
||||
const instanceOn = useAddonStore((state) => state.isEnabled('tours'));
|
||||
const { tours, status, shownFor } = useCollectionTourStore(
|
||||
useShallow((state) => ({ tours: state.tours, status: state.status, shownFor: state.collectionId }))
|
||||
);
|
||||
const [removing, setRemoving] = useState<CollectionTourItem | null>(null);
|
||||
|
||||
// Read again when the instance switch flips, since the answer may change with it.
|
||||
useEffect(() => {
|
||||
if (!enabled) return undefined;
|
||||
void useCollectionTourStore.getState().load(collectionId);
|
||||
return watchCollectionTours();
|
||||
}, [collectionId, enabled]);
|
||||
}, [collectionId, instanceOn]);
|
||||
|
||||
const confirmRemove = async () => {
|
||||
const tour = removing;
|
||||
@@ -44,6 +47,9 @@ export function useCollectionTours(collectionId: number) {
|
||||
};
|
||||
|
||||
const current = shownFor === collectionId;
|
||||
// With the instance on nothing changes; with it off only tours the server handed over show,
|
||||
// so an install without a trip of its own choice shows nothing, as it always did.
|
||||
const enabled = instanceOn ? !(current && status === 'off') : current && status === 'ready';
|
||||
return {
|
||||
enabled,
|
||||
tours: enabled && current ? tours : [],
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { translateApiError, useTranslation } from '../../../i18n';
|
||||
import { tourPackingLinkRepo } from '../../../repo/tourPackingLinkRepo';
|
||||
import { useAddonStore } from '../../../store/addonStore';
|
||||
import { useTripAddonEnabled } from '../../../store/tripAddonsStore';
|
||||
import { useTripStore } from '../../../store/tripStore';
|
||||
import type { PackingItem } from '../../../types';
|
||||
import { packingCategoryOrder, packingViewItems } from '../../Packing/packingListModel';
|
||||
@@ -42,7 +42,7 @@ interface TourPackingCategory extends PackingCategoryChoice {
|
||||
export function useTourPackingLink({ tripId, tour }: { tripId: number; tour: TourListItem }) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const packingEnabled = useAddonStore((state) => state.isEnabled('packing'));
|
||||
const packingEnabled = useTripAddonEnabled(tripId, 'packing');
|
||||
const items = useTripStore((state) => state.packingItems);
|
||||
const placeId = tour.place_id;
|
||||
const key = `${tripId}:${placeId}`;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user