mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-21 22:46:32 +00:00
Compare commits
232 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d80577480c | |||
| 1c05ee4b3a | |||
| 1ff22490f2 | |||
| aa1f76ad11 | |||
| c6a089107f | |||
| cd06f0f7f4 | |||
| e6f66014a5 | |||
| 06bee95ae3 | |||
| 5f77c2cee9 | |||
| cf5920ebe0 | |||
| a0952bd871 | |||
| 3c7f6e69dd | |||
| 30a3f664b1 | |||
| 0a3a993dfc | |||
| bea3af4b45 | |||
| 26ab4a58b1 | |||
| 0887f251ce | |||
| 151e32107f | |||
| 8779529efb | |||
| e1315806c2 | |||
| e64ade010f | |||
| 3062df153f | |||
| 233076030b | |||
| c5ac479915 | |||
| 954758082b | |||
| 83be759c49 | |||
| f3ca0b1a4c | |||
| 302101b186 | |||
| 1639fc6a3e | |||
| 1b63285ad0 | |||
| b56f335978 | |||
| 2f6f921aef | |||
| 436f0740fb | |||
| 1423ba8933 | |||
| 2350c3ae14 | |||
| 362b1ee8d1 | |||
| b5457d9e6a | |||
| a1d6348c5f | |||
| f16698bdb1 | |||
| a910c2a837 | |||
| 0df82185bd | |||
| e8ec3427e5 | |||
| 8d78c988c3 | |||
| ae80ad266d | |||
| 41b14ebc2a | |||
| 05f533dd0d | |||
| e6e520b78f | |||
| 05651eed1a | |||
| 7e7d13c021 | |||
| 514e2e62ee | |||
| 7fa0434570 | |||
| 3a67a8e279 | |||
| cc5957dc6a | |||
| 83d088e842 | |||
| e921799580 | |||
| 34c1dc79b5 | |||
| 451e6d240b | |||
| ab3a81a9eb | |||
| e6daed9403 | |||
| 53a422d22d | |||
| 6124e0b056 | |||
| d52154c765 | |||
| aceb75949b | |||
| 4f5a6bb7d8 | |||
| d609e1e202 | |||
| 6f3977e4c1 | |||
| 615e74aff6 | |||
| bb515ac3cc | |||
| 93dddaa4af | |||
| 1a8d5a3dd9 | |||
| ed8acf4c4b | |||
| a280517ff3 | |||
| 2dd77aaac1 | |||
| 85b5756e89 | |||
| cb85ba915c | |||
| 81292d4d2b | |||
| 757967bf18 | |||
| b0c19bfac1 | |||
| da32eb8a3c | |||
| a44df6cf11 | |||
| e510ff25ab | |||
| 34f3aeee5f | |||
| bdd326163f | |||
| b1baf3baa9 | |||
| fdab3bb347 | |||
| d288459449 | |||
| e35d95da71 | |||
| 6b1d65b06c | |||
| b6fcaced2e | |||
| e12ae950df | |||
| 11b1399b5c | |||
| 0644106f7a | |||
| 903378f8ad | |||
| 84d3dd0c4a | |||
| bdb031a1e9 | |||
| 0b4230ff4c | |||
| fa35966ab8 | |||
| 4be2314856 | |||
| f43b89be13 | |||
| ac23773352 | |||
| 8138c83558 | |||
| 141afe708d | |||
| 43a3a5217e | |||
| d14d83ebaa | |||
| cce64c4030 | |||
| bf0507ddb5 | |||
| 9bd9ff4a80 | |||
| 8845f73eb9 | |||
| 6b09a8bc11 | |||
| 67dff455da | |||
| 97a2ea1748 | |||
| 8d70d875b3 | |||
| 3dfdc92b2a | |||
| 84b73d1a83 | |||
| eeda3188c2 | |||
| be9a38e3b0 | |||
| 417d0445b9 | |||
| a86e4b560a | |||
| cd769d9993 | |||
| 979a9283cd | |||
| 32f2488774 | |||
| b98787f836 | |||
| dbb98a9bcd | |||
| 8215fed2a7 | |||
| 9731407694 | |||
| 8f6ed02cff | |||
| 31239f3687 | |||
| ed18c37903 | |||
| 1e35a99c11 | |||
| a782e0e471 | |||
| 7ccc8dc03d | |||
| 2a7ad1e241 | |||
| 4b3fb7dec9 | |||
| 5d04f9c400 | |||
| 62cccf32f3 | |||
| c8d4ed896e | |||
| 44c92052a3 | |||
| 033735777a | |||
| d803efd39d | |||
| 7cfec6452d | |||
| 00de3c3a1d | |||
| 3ad40e056d | |||
| 83c9cebddc | |||
| 58f6a49f32 | |||
| 03d3f2f91e | |||
| 80bb06c84f | |||
| bb6003684c | |||
| 154c88b48a | |||
| cc1c16ec34 | |||
| 40f8912937 | |||
| 66061a05df | |||
| bcdb931a34 | |||
| ec2711cec0 | |||
| 233f46575c | |||
| 9de8490176 | |||
| 843582863c | |||
| 25d4e34959 | |||
| 71400b7e85 | |||
| 98e2938033 | |||
| b88b92add7 | |||
| 01a7224f29 | |||
| dd3d97589b | |||
| dc1ac0ae85 | |||
| ac47066a93 | |||
| 9f531d1cd9 | |||
| e6a5ca1521 | |||
| 7237a1881d | |||
| 4fa06c3483 | |||
| 1430056d24 | |||
| 2d7cb124b3 | |||
| 902dbbf84c | |||
| d4c6ac9fe8 | |||
| 5ef8bf31f4 | |||
| e9742e9322 | |||
| 371b7da9de | |||
| 7f87dd512d | |||
| 0e2d255d81 | |||
| 543a052da7 | |||
| 7806560c8f | |||
| c8f9edad87 | |||
| 92ccd24eed | |||
| 08df1812be | |||
| ce5cc49b58 | |||
| 8860e16149 | |||
| 185f6c5335 | |||
| 1e338e2c71 | |||
| 2879433bd3 | |||
| 1908d6f5f9 | |||
| 425e1ef183 | |||
| 9f57bbf4fb | |||
| 3dd3e1e8d2 | |||
| bbcf17d816 | |||
| d18077d171 | |||
| 84923b97a7 | |||
| c0ff4dabb3 | |||
| d07aa80093 | |||
| 911f3e2583 | |||
| 0b1ca1c98a | |||
| a250fa6339 | |||
| 50f0641ad9 | |||
| 782bb365b5 | |||
| 222313d198 | |||
| 6a6c7f1882 | |||
| 9b415c8ab9 | |||
| bf0ec85372 | |||
| 9de18634fe | |||
| 5b60dda150 | |||
| bf03d91345 | |||
| 79450a5380 | |||
| bd347f553b | |||
| aaff8f9db4 | |||
| 5f57c63426 | |||
| bd44197974 | |||
| 37163e9a41 | |||
| 61a8a2765b | |||
| c0195557d4 | |||
| 06610bd97e | |||
| 05ee3d50e4 | |||
| e2bdd2dd08 | |||
| 99783cc8da | |||
| e5d85eda8d | |||
| a9cd47caeb | |||
| 8a72d98bc6 | |||
| 09e46bf723 | |||
| f0a4e4c74d | |||
| acd6f1acdf | |||
| 4eaf90fd1b | |||
| ef259e7d7d | |||
| 12eabbb685 | |||
| b7ed11ef4a | |||
| b90d258b6c | |||
| c0e3fde6f7 |
@@ -26,3 +26,5 @@
|
||||
*.eot binary
|
||||
*.pdf binary
|
||||
*.zip binary
|
||||
# A GPX fixture whose byte-order mark and CRLF line endings are what it tests
|
||||
server/tests/fixtures/gpx/bom-crlf.gpx -text
|
||||
|
||||
@@ -51,6 +51,12 @@ on:
|
||||
- 'package-lock.json'
|
||||
- 'sonar-project.properties'
|
||||
- '.github/workflows/test.yml'
|
||||
# The image's start-up shape is pinned by a unit test
|
||||
# (server/tests/unit/docker-entrypoint.test.ts), so a change to the
|
||||
# Dockerfile or to the entrypoint script has to run the suite — that is
|
||||
# exactly the change the test exists to catch.
|
||||
- 'Dockerfile'
|
||||
- 'server/scripts/**'
|
||||
# Docs inside the workspaces (CLAUDE.md, READMEs, PATTERN.md) affect
|
||||
# neither the tests nor the scan — no test reads checked-in markdown
|
||||
# and SonarCloud has no markdown analyzer. Negations must stay last.
|
||||
@@ -69,6 +75,12 @@ on:
|
||||
- 'package-lock.json'
|
||||
- 'sonar-project.properties'
|
||||
- '.github/workflows/test.yml'
|
||||
# The image's start-up shape is pinned by a unit test
|
||||
# (server/tests/unit/docker-entrypoint.test.ts), so a change to the
|
||||
# Dockerfile or to the entrypoint script has to run the suite — that is
|
||||
# exactly the change the test exists to catch.
|
||||
- 'Dockerfile'
|
||||
- 'server/scripts/**'
|
||||
# Docs inside the workspaces (CLAUDE.md, READMEs, PATTERN.md) affect
|
||||
# neither the tests nor the scan — no test reads checked-in markdown
|
||||
# and SonarCloud has no markdown analyzer. Negations must stay last.
|
||||
|
||||
+27
-11
@@ -27,7 +27,8 @@ COPY client/ ./client/
|
||||
RUN npm run build --workspace=client
|
||||
|
||||
# ── Stage 3: server ──────────────────────────────────────────────────────────
|
||||
# --ignore-scripts skips native builds (better-sqlite3); they happen in the production stage.
|
||||
# --ignore-scripts: nothing here needs a postinstall, tsc only reads types. The one
|
||||
# native module, better-sqlite3, ships its binaries inside the npm tarball since 13.x.
|
||||
FROM node:24-alpine AS server-builder
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
@@ -52,17 +53,27 @@ COPY server/package.json ./server/
|
||||
# changeset, so it costs nothing. Everything copied after this point carries
|
||||
# --chown=node:node for the same reason — a recursive chown in a later layer
|
||||
# would copy up every inode it touches and duplicate the whole tree in the image.
|
||||
#
|
||||
# No compiler in this stage. better-sqlite3 13.x carries prebuilt binaries for
|
||||
# amd64 and arm64 inside its tarball, so there is nothing left to build: the old
|
||||
# python3 + build-essential fallback compiled it against whatever Node headers
|
||||
# the base image had that day, and 24.19+ headers give an addon that aborts with
|
||||
# "Assertion failed: (env) != nullptr" the first time a statement is collected
|
||||
# (#2421). --ignore-scripts because a lockfile-driven npm ci still synthesises
|
||||
# `node-gyp rebuild` for the binding.gyp it finds, blind to the package's
|
||||
# gypfile:false (npm/cli#9837). The only other install scripts among the runtime
|
||||
# deps are esbuild's binary check, redundant next to its optional platform
|
||||
# package, and a telemetry ping.
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates python3 build-essential \
|
||||
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
|
||||
libkitinerary-bin libsqlite3-0 && \
|
||||
npm ci --workspace=server --omit=dev && \
|
||||
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; \
|
||||
apt-get purge -y python3 build-essential && \
|
||||
apt-get autoremove -y && \
|
||||
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) — used by CMD to drop to node.
|
||||
# gosu rebuilt with a current Go toolchain (stage 0) — the entrypoint script uses
|
||||
# it to drop to node.
|
||||
COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
|
||||
|
||||
ENV XDG_CACHE_HOME=/tmp/kf6-cache
|
||||
@@ -117,9 +128,14 @@ EXPOSE 3000
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD wget -qO- http://localhost:3000/api/health || exit 1
|
||||
|
||||
# Start-up lives in a script, not an inline `sh -c` string: container management
|
||||
# UIs re-tokenise Config.Cmd when you edit a container in place, and a command
|
||||
# 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.
|
||||
RUN chmod 0755 /usr/local/bin/trek-entrypoint
|
||||
|
||||
ENTRYPOINT ["dumb-init", "--"]
|
||||
# Preflight: if the app code is missing, a volume was almost certainly mounted
|
||||
# over /app (it hides the image's node_modules + dist). Fail with actionable
|
||||
# guidance instead of a cryptic "Cannot find module 'tsconfig-paths/register'".
|
||||
# cd into server/ so tsconfig-paths/register finds tsconfig.json and ../node_modules resolves correctly.
|
||||
CMD ["sh", "-c", "if [ ! -f /app/server/dist/index.js ] || [ ! -d /app/node_modules/tsconfig-paths ]; then echo 'FATAL: TREK application files are missing from the image.'; echo 'A volume is likely mounted over /app, which hides the app code.'; echo 'Mount ONLY your data and uploads dirs: -v ./data:/app/data -v ./uploads:/app/uploads'; echo 'Do NOT mount a volume at /app. See the Troubleshooting section of the README.'; exit 1; fi; chown -R node:node /app/data /app/uploads 2>/dev/null || true; cd /app/server && exec gosu node node --require tsconfig-paths/register dist/index.js"]
|
||||
CMD ["/usr/local/bin/trek-entrypoint"]
|
||||
|
||||
@@ -49,6 +49,7 @@ See `values.yaml` for more options.
|
||||
- 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.
|
||||
- If using ingress, you must manually keep `env.ALLOWED_ORIGINS` and `ingress.hosts` in sync to ensure CORS works correctly. The chart does not sync these automatically.
|
||||
- Set `env.ALLOW_INTERNAL_NETWORK: "true"` if Immich or other integrated services are hosted on a private/RFC-1918 address (e.g. a pod on the same cluster or a NAS on your LAN). Loopback (`127.x`) and link-local/metadata addresses (`169.254.x`) remain blocked regardless.
|
||||
- Set `env.ALLOW_LINK_LOCAL_IPS` to a single link-local address (e.g. `"169.254.1.2"`) only when a service TREK needs sits behind one, such as a host gateway. Cloud metadata addresses (`169.254.169.x`, `169.254.170.x`) cannot be listed.
|
||||
- `FORCE_HTTPS` is optional. Set `env.FORCE_HTTPS: "true"` only when ingress (or another proxy) terminates TLS. It enables HTTPS redirects, HSTS, CSP `upgrade-insecure-requests`, and forces the session cookie `secure` flag. Requires `TRUST_PROXY` to be set.
|
||||
- Set `env.TRUST_PROXY: "1"` (or the number of proxy hops) when running behind ingress or a load balancer. Required for `FORCE_HTTPS` to detect the forwarded protocol correctly. In production it defaults to `1` automatically.
|
||||
- `COOKIE_SECURE` is auto-derived (on when `NODE_ENV=production` or `FORCE_HTTPS=true`). Set `env.COOKIE_SECURE: "false"` only during local testing without TLS. **Not recommended for production.**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
apiVersion: v2
|
||||
name: trek
|
||||
version: 4.2.0
|
||||
version: 4.3.4
|
||||
description: Minimal Helm chart for TREK app
|
||||
appVersion: "4.2.0"
|
||||
appVersion: "4.3.4"
|
||||
|
||||
@@ -43,6 +43,9 @@ data:
|
||||
{{- if .Values.env.ALLOW_INTERNAL_NETWORK }}
|
||||
ALLOW_INTERNAL_NETWORK: {{ .Values.env.ALLOW_INTERNAL_NETWORK | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.ALLOW_LINK_LOCAL_IPS }}
|
||||
ALLOW_LINK_LOCAL_IPS: {{ .Values.env.ALLOW_LINK_LOCAL_IPS | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.OIDC_ISSUER }}
|
||||
OIDC_ISSUER: {{ .Values.env.OIDC_ISSUER | quote }}
|
||||
{{- end }}
|
||||
@@ -73,9 +76,24 @@ data:
|
||||
{{- if .Values.env.MCP_RATE_LIMIT }}
|
||||
MCP_RATE_LIMIT: {{ .Values.env.MCP_RATE_LIMIT | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.NOMINATIM_URL }}
|
||||
NOMINATIM_URL: {{ .Values.env.NOMINATIM_URL | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.OVERPASS_URL }}
|
||||
OVERPASS_URL: {{ .Values.env.OVERPASS_URL | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.OVERPASS_TIMEOUT_MS }}
|
||||
OVERPASS_TIMEOUT_MS: {{ .Values.env.OVERPASS_TIMEOUT_MS | quote }}
|
||||
{{- end }}
|
||||
{{- /* Tested for presence rather than truth: the one value this switch gets set to is
|
||||
false, and an unquoted false (or --set env.TREK_PLACES_ENABLED=false) would
|
||||
otherwise drop the key and leave the index on. */}}
|
||||
{{- if not (kindIs "invalid" .Values.env.TREK_PLACES_ENABLED) }}
|
||||
TREK_PLACES_ENABLED: {{ .Values.env.TREK_PLACES_ENABLED | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.TREK_PLACES_URL }}
|
||||
TREK_PLACES_URL: {{ .Values.env.TREK_PLACES_URL | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.env.AMAP_API_BASE }}
|
||||
AMAP_API_BASE: {{ .Values.env.AMAP_API_BASE | quote }}
|
||||
{{- end }}
|
||||
|
||||
@@ -75,6 +75,18 @@ spec:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: UNSPLASH_ACCESS_KEY
|
||||
optional: true
|
||||
- name: AMAP_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: AMAP_API_KEY
|
||||
optional: true
|
||||
- name: AMAP_API_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: AMAP_API_SECRET
|
||||
optional: true
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /app/data
|
||||
|
||||
@@ -20,6 +20,12 @@ data:
|
||||
{{- if .Values.secretEnv.UNSPLASH_ACCESS_KEY }}
|
||||
UNSPLASH_ACCESS_KEY: {{ .Values.secretEnv.UNSPLASH_ACCESS_KEY | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.AMAP_API_KEY }}
|
||||
AMAP_API_KEY: {{ .Values.secretEnv.AMAP_API_KEY | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.AMAP_API_SECRET }}
|
||||
AMAP_API_SECRET: {{ .Values.secretEnv.AMAP_API_SECRET | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{- if and (not .Values.existingSecret) (.Values.generateEncryptionKey) }}
|
||||
@@ -50,4 +56,10 @@ stringData:
|
||||
{{- if .Values.secretEnv.UNSPLASH_ACCESS_KEY }}
|
||||
UNSPLASH_ACCESS_KEY: {{ .Values.secretEnv.UNSPLASH_ACCESS_KEY }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.AMAP_API_KEY }}
|
||||
AMAP_API_KEY: {{ .Values.secretEnv.AMAP_API_KEY }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.AMAP_API_SECRET }}
|
||||
AMAP_API_SECRET: {{ .Values.secretEnv.AMAP_API_SECRET }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
+35
-2
@@ -54,6 +54,9 @@ env:
|
||||
# ALLOW_INTERNAL_NETWORK: "false"
|
||||
# Set to "true" if Immich or other integrated services are hosted on a private/RFC-1918 network address.
|
||||
# Loopback (127.x) and link-local/metadata addresses (169.254.x) are always blocked.
|
||||
# ALLOW_LINK_LOCAL_IPS: ""
|
||||
# Comma-separated single link-local addresses TREK may reach after all, e.g. "169.254.1.2" for a host gateway.
|
||||
# 169.254.169.x and 169.254.170.x (cloud metadata) cannot be listed; an invalid entry aborts startup.
|
||||
# OIDC_ISSUER: ""
|
||||
# OpenID Connect provider URL.
|
||||
# OIDC_CLIENT_ID: ""
|
||||
@@ -78,12 +81,33 @@ env:
|
||||
# Max MCP API requests per user per minute. Defaults to 300.
|
||||
# MCP_MAX_SESSION_PER_USER: "20"
|
||||
# Max concurrent MCP sessions per user. Defaults to 20.
|
||||
# NOMINATIM_URL: ""
|
||||
# Custom Nominatim base URL for every geocoding call the server makes (place search, reverse lookup, Atlas region
|
||||
# fill). When set it REPLACES the public OpenStreetMap service, with no fallback, so the instance behind it needs
|
||||
# the coverage you expect and has to speak the Nominatim API. TREK keeps its ~1 request per second spacing either
|
||||
# way. Defaults to https://nominatim.openstreetmap.org.
|
||||
# OVERPASS_URL: ""
|
||||
# Custom Overpass endpoint(s) for the map POI "explore" search, comma-separated. When set, REPLACES the bundled
|
||||
# public mirrors — point it at an internal/self-hosted Overpass instance when the public mirrors are unreachable
|
||||
# from the cluster (e.g. locked-down egress). Non-http(s) entries are ignored.
|
||||
# OVERPASS_TIMEOUT_MS: "12000"
|
||||
# Per-endpoint timeout (ms) for Overpass POI requests. Raise it for a slow self-hosted Overpass instance. Defaults to 12000.
|
||||
# OVERPASS_TIMEOUT_MS: "25000"
|
||||
# Per-endpoint timeout (ms) for Overpass POI requests. The query itself gives Overpass 20 seconds of work, so a
|
||||
# lower value hangs up on answers that were still coming. Raise it for a slow self-hosted Overpass instance.
|
||||
# Defaults to 25000.
|
||||
# TREK_PLACES_ENABLED: "false"
|
||||
# Place search (suggestions, full search, category buttons, Road trip search, import geocoding, offline downloads)
|
||||
# asks the TREK Places API at https://places.liketrek.com by default, so the pod makes outbound requests to that
|
||||
# host. Set "false" to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send
|
||||
# nothing there. There is no switch in the admin panel on purpose: whether searches leave the instance is decided
|
||||
# here. Defaults to on.
|
||||
# TREK_PLACES_URL: ""
|
||||
# Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from
|
||||
# configuration rather than typed by a user, so an in-cluster address works without ALLOW_INTERNAL_NETWORK.
|
||||
# Defaults to https://places.liketrek.com.
|
||||
# AMAP_API_BASE: ""
|
||||
# Send the Amap (高德地图) calls through an egress proxy, a cache or a gateway that speaks the same API instead of
|
||||
# restapi.amap.com directly. The key itself is a credential and goes under secretEnv.AMAP_API_KEY, or into
|
||||
# Admin > Settings > API Keys. Defaults to https://restapi.amap.com.
|
||||
|
||||
|
||||
# Secret environment variables stored in a Kubernetes Secret.
|
||||
@@ -109,6 +133,15 @@ secretEnv:
|
||||
# Get a free key at https://unsplash.com/developers. Can also be set per-admin
|
||||
# in Admin > Settings; this value overrides that. Leave empty to disable.
|
||||
UNSPLASH_ACCESS_KEY: ""
|
||||
# Optional Amap (高德地图) Web 服务 key for place search and geocoding inside mainland
|
||||
# China. Overrides the key set in Admin > Settings > API Keys. A Web 端 (JS API) key is
|
||||
# a different credential and is rejected with INVALID_USER_KEY. Leave empty to use the
|
||||
# key from the admin panel, or none.
|
||||
AMAP_API_KEY: ""
|
||||
# The private secret (数字签名) of that key. Required exactly when the key was created
|
||||
# with signing enabled, because such a key rejects every unsigned request. Leave empty
|
||||
# otherwise. The endpoint itself is not a secret and is set under env.AMAP_API_BASE.
|
||||
AMAP_API_SECRET: ""
|
||||
|
||||
# If true, a random ENCRYPTION_KEY is generated at install and preserved across upgrades
|
||||
generateEncryptionKey: false
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
<!-- Pre-paint appearance (FOUC fix). External classic script so it runs
|
||||
before first paint AND complies with the prod CSP (script-src 'self'). -->
|
||||
<script src="/theme-boot.js"></script>
|
||||
<!-- Recovers a shell whose entry module cannot load (#2524). Classic for the
|
||||
same reasons, and ahead of the entry, which it has to watch. -->
|
||||
<script src="/shell-guard.js"></script>
|
||||
|
||||
<!-- PWA / iOS -->
|
||||
<meta name="theme-color" content="#09090b" />
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@trek/client",
|
||||
"version": "4.2.0",
|
||||
"version": "4.3.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* Boot guard for the app shell (#2524).
|
||||
*
|
||||
* Loaded as an external classic script in <head> (NOT a module), like
|
||||
* theme-boot.js, so it runs before the entry module and complies with the
|
||||
* production CSP (script-src 'self').
|
||||
*
|
||||
* The entry module and every chunk it imports statically have to load before
|
||||
* any of the app's own code runs. When one of them does not (a service worker
|
||||
* precache that keeps index.html under a chunk's name, a proxy that hands out a
|
||||
* stale file), the module script fails as a whole: nothing renders, and no error
|
||||
* screen or reload button of the app is there to help. A reload changes nothing
|
||||
* either, since the same precache answers it. This notices exactly that failure
|
||||
* and, while the server answers, loads the page again from the server under a
|
||||
* URL no cache has seen. When a service worker served the page, the app shell
|
||||
* it keeps (the Workbox precache and the worker itself) is thrown away first,
|
||||
* since that is what answered with the broken file. Once per session, so a build
|
||||
* that is broken on the server cannot put the page in a reload loop. Offline
|
||||
* nothing happens: the precache is then the only way the app can start at all.
|
||||
*
|
||||
* It also strips the query parameter such a reload carries, before the app
|
||||
* reads the URL. Keep the parameter and the cache filter in sync with
|
||||
* src/utils/chunkReload.ts and src/utils/serviceWorkerShell.ts.
|
||||
*
|
||||
* It must never throw.
|
||||
*/
|
||||
(function () {
|
||||
var PARAM = 'trek-reload';
|
||||
var MARKER = 'trek:shell-reload';
|
||||
var HEALTH_TIMEOUT_MS = 3000;
|
||||
|
||||
try {
|
||||
var here = new URL(window.location.href);
|
||||
if (here.searchParams.has(PARAM)) {
|
||||
here.searchParams.delete(PARAM);
|
||||
window.history.replaceState(window.history.state, '', here.pathname + here.search + here.hash);
|
||||
}
|
||||
} catch (e) {
|
||||
/* the parameter stays in the address bar, which is harmless */
|
||||
}
|
||||
|
||||
// The built entry lives under /assets/. The dev server's /src/main.tsx does
|
||||
// not, so a syntax error while developing is left to Vite's own overlay.
|
||||
function isEntry(el) {
|
||||
return !!el && el.tagName === 'SCRIPT' && el.type === 'module' && /\/assets\//.test(el.src || '');
|
||||
}
|
||||
|
||||
function alreadyTried() {
|
||||
try {
|
||||
return !!sessionStorage.getItem(MARKER);
|
||||
} catch (e) {
|
||||
// Without the marker there is no loop protection, so do nothing.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function markTried() {
|
||||
try {
|
||||
sessionStorage.setItem(MARKER, String(Date.now()));
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Same test as probeNow() in src/sync/connectivity.ts: TREK's own health JSON,
|
||||
// not an edge proxy's login page and not a request that never came back.
|
||||
function serverAnswers() {
|
||||
var ctrl = typeof AbortController === 'function' ? new AbortController() : null;
|
||||
var timer = ctrl ? setTimeout(function () { ctrl.abort(); }, HEALTH_TIMEOUT_MS) : null;
|
||||
return fetch('/api/health', {
|
||||
credentials: 'include',
|
||||
cache: 'no-store',
|
||||
redirect: 'manual',
|
||||
signal: ctrl ? ctrl.signal : undefined,
|
||||
}).then(function (res) {
|
||||
var type = res.headers.get('content-type') || '';
|
||||
return res.ok && type.indexOf('application/json') !== -1;
|
||||
}, function () {
|
||||
return false;
|
||||
}).then(function (ok) {
|
||||
if (timer) clearTimeout(timer);
|
||||
return ok;
|
||||
});
|
||||
}
|
||||
|
||||
function servedByWorker() {
|
||||
try {
|
||||
return !!(navigator.serviceWorker && navigator.serviceWorker.controller);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function dropAppShell() {
|
||||
var jobs = [];
|
||||
if (typeof caches !== 'undefined') {
|
||||
jobs.push(caches.keys().then(function (names) {
|
||||
return Promise.all(names.filter(function (name) {
|
||||
return name.indexOf('-precache-') !== -1;
|
||||
}).map(function (name) {
|
||||
return caches.delete(name);
|
||||
}));
|
||||
}));
|
||||
}
|
||||
if (navigator.serviceWorker) {
|
||||
jobs.push(navigator.serviceWorker.getRegistration().then(function (reg) {
|
||||
return reg ? reg.unregister() : false;
|
||||
}));
|
||||
}
|
||||
return Promise.all(jobs);
|
||||
}
|
||||
|
||||
function reloadFresh() {
|
||||
var url = new URL(window.location.href);
|
||||
url.searchParams.set(PARAM, Date.now().toString(36));
|
||||
window.location.replace(url.href);
|
||||
}
|
||||
|
||||
function recover() {
|
||||
if (alreadyTried()) return;
|
||||
// Read now: a page the worker did not serve failed on the network, and its
|
||||
// precache has nothing to do with it.
|
||||
var fromWorker = servedByWorker();
|
||||
serverAnswers().then(function (ok) {
|
||||
if (!ok || alreadyTried() || !markTried()) return;
|
||||
var dropped = fromWorker ? dropAppShell() : Promise.resolve();
|
||||
return dropped.then(null, function () {
|
||||
/* reload regardless, the server has the current build */
|
||||
}).then(reloadFresh);
|
||||
}).then(null, function () {
|
||||
/* never block boot */
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
// Error and load events of a script do not bubble, so both are caught on
|
||||
// their way down. On the document, since a load event never reaches window.
|
||||
document.addEventListener('error', function (event) {
|
||||
if (isEntry(event.target)) recover();
|
||||
}, true);
|
||||
// The shell started, so a later update in this session may recover too.
|
||||
document.addEventListener('load', function (event) {
|
||||
if (!isEntry(event.target)) return;
|
||||
try {
|
||||
sessionStorage.removeItem(MARKER);
|
||||
} catch (e) {
|
||||
/* nothing to clear */
|
||||
}
|
||||
}, true);
|
||||
} catch (e) {
|
||||
/* never block boot */
|
||||
}
|
||||
})();
|
||||
@@ -23,3 +23,17 @@ export const rtlTextAlias = {
|
||||
'../dist/mapbox-gl-rtl-text.js',
|
||||
),
|
||||
};
|
||||
|
||||
/**
|
||||
* Same shape for Plyr's icon sprite. The package publishes its JS and CSS entries
|
||||
* and nothing else, so `plyr/dist/plyr.svg` is refused by the resolver although
|
||||
* the file is right there. The player has to point at a copy on this origin
|
||||
* (#2341): its default is the sprite on cdn.plyr.io, which the CSP refuses.
|
||||
*/
|
||||
export const plyrSpriteAlias = {
|
||||
find: /^plyr\/dist\/plyr\.svg/,
|
||||
replacement: path.join(
|
||||
path.dirname(createRequire(import.meta.url).resolve('plyr')),
|
||||
'plyr.svg',
|
||||
),
|
||||
};
|
||||
|
||||
+27
-7
@@ -580,24 +580,44 @@ describe('Version cache-busting', () => {
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-027: the version marker is written even if the update path throws (#2228)', async () => {
|
||||
// The marker used to be written after the purge and outside its try, so a
|
||||
// throwing step left it unwritten and the whole destructive path repeated on
|
||||
// every launch, for good.
|
||||
it('FE-COMP-APP-027: an update path that throws is retried on the next launch, harmlessly (#2228)', async () => {
|
||||
// A handover that never happened must not be recorded as done, or the
|
||||
// device stays on the old build for good. The retry this buys has to be
|
||||
// harmless: the purge that once repeated on every launch is gone, and a
|
||||
// failure neither deletes anything nor reloads into the old worker's shell.
|
||||
localStorage.setItem('trek_app_version', '2.9.9')
|
||||
const reload = vi.fn()
|
||||
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
|
||||
const cachesDelete = vi.fn().mockResolvedValue(true)
|
||||
const unregister = vi.fn().mockResolvedValue(true)
|
||||
vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete })
|
||||
const getRegistration = vi.fn().mockRejectedValue(new Error('no worker'))
|
||||
Object.defineProperty(navigator, 'serviceWorker', {
|
||||
configurable: true,
|
||||
value: { getRegistration: vi.fn().mockRejectedValue(new Error('no worker')), addEventListener: vi.fn() },
|
||||
value: { getRegistration, getRegistrations: vi.fn().mockResolvedValue([{ unregister }]), addEventListener: vi.fn() },
|
||||
})
|
||||
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () =>
|
||||
HttpResponse.json({ version: '2.9.10' })
|
||||
HttpResponse.json({ version: '2.9.10', places_provider: 'google' })
|
||||
)
|
||||
)
|
||||
seedAuth()
|
||||
const first = renderApp('/')
|
||||
await waitFor(() => expect(getRegistration).toHaveBeenCalledTimes(1))
|
||||
await act(async () => { await Promise.resolve() })
|
||||
first.unmount()
|
||||
expect(localStorage.getItem('trek_app_version')).toBe('2.9.9')
|
||||
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(localStorage.getItem('trek_app_version')).toBe('2.9.10'))
|
||||
await waitFor(() => expect(getRegistration).toHaveBeenCalledTimes(2))
|
||||
await act(async () => { await Promise.resolve() })
|
||||
expect(localStorage.getItem('trek_app_version')).toBe('2.9.9')
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
expect(cachesDelete).not.toHaveBeenCalled()
|
||||
expect(unregister).not.toHaveBeenCalled()
|
||||
// Without a reload the session carries on, so the rest of the config applies.
|
||||
expect(useAuthStore.getState().placesProvider).toBe('google')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
+6
-44
@@ -17,6 +17,7 @@ import MobileShell from './mobile/MobileShell'
|
||||
import MRouteFallback from './mobile/components/MRouteFallback'
|
||||
import ErrorBoundary from './components/shared/ErrorBoundary'
|
||||
import { lazyWithRetry } from './utils/lazyWithRetry'
|
||||
import { reconcileAppVersion } from './utils/versionHandover'
|
||||
import { useIsPhone } from './mobile/useIsPhone'
|
||||
import { TranslationProvider, useTranslation } from './i18n'
|
||||
import { authApi, isAuthPublicPath } from './api/client'
|
||||
@@ -284,7 +285,7 @@ function RouteFallback() {
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const { loadUser, isAuthenticated, demoMode, setManaged, setDemoMode, setDevMode, setIsPrerelease, setAppVersion, setHasMapsKey, setHasAmapKey, setServerTimezone, setAppRequireMfa, setTripRemindersEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, setPlacesEnrichEnabled, setPlaceShadowEnabled } = useAuthStore()
|
||||
const { loadUser, isAuthenticated, demoMode, setManaged, setDemoMode, setDevMode, setIsPrerelease, setAppVersion, setHasMapsKey, setHasAmapKey, setPlacesProvider, setServerTimezone, setAppRequireMfa, setTripRemindersEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, setPlacesEnrichEnabled, setPlaceShadowEnabled } = useAuthStore()
|
||||
const { loadSettings } = useSettingsStore()
|
||||
const { loadAddons } = useAddonStore()
|
||||
const { loadPlugins } = usePluginStore()
|
||||
@@ -301,7 +302,7 @@ export default function App() {
|
||||
loadUser()
|
||||
}
|
||||
}
|
||||
authApi.getAppConfig().then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; permissions?: Record<string, PermissionLevel> }) => {
|
||||
authApi.getAppConfig().then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; permissions?: Record<string, PermissionLevel> }) => {
|
||||
setManaged(!!config?.managed)
|
||||
setDemoMode(!!config?.demo_mode)
|
||||
if (config?.dev_mode) setDevMode(true)
|
||||
@@ -309,6 +310,7 @@ export default function App() {
|
||||
if (config?.version) setAppVersion(config.version)
|
||||
if (config?.has_maps_key !== undefined) setHasMapsKey(config.has_maps_key)
|
||||
if (config?.has_amap_key !== undefined) setHasAmapKey(config.has_amap_key)
|
||||
if (config?.places_provider) setPlacesProvider(config.places_provider)
|
||||
if (config?.timezone) setServerTimezone(config.timezone)
|
||||
if (config?.require_mfa !== undefined) setAppRequireMfa(!!config.require_mfa)
|
||||
if (config?.trip_reminders_enabled !== undefined) setTripRemindersEnabled(config.trip_reminders_enabled)
|
||||
@@ -318,48 +320,8 @@ export default function App() {
|
||||
if (config?.places_enrich_enabled !== undefined) setPlacesEnrichEnabled(config.places_enrich_enabled)
|
||||
if (config?.place_shadow_enabled !== undefined) setPlaceShadowEnabled(config.place_shadow_enabled)
|
||||
if (config?.permissions) usePermissionsStore.getState().setPermissions(config.permissions)
|
||||
|
||||
// A version is a short release tag and nothing else. It arrives over the
|
||||
// wire and is written to this device's storage, so it is rebuilt from the
|
||||
// characters a tag may contain and kept only when nothing had to be
|
||||
// stripped. Anything else is ignored, which also keeps a malformed value
|
||||
// from being compared against the stored marker and starting an update on
|
||||
// every launch.
|
||||
const reportedVersion = typeof config?.version === 'string' ? config.version : ''
|
||||
const version = reportedVersion.replace(/[^\w.+-]/g, '').slice(0, 64)
|
||||
if (version && version === reportedVersion) {
|
||||
const storedVersion = localStorage.getItem('trek_app_version')
|
||||
// Record the version BEFORE acting on it. The old code wrote the marker
|
||||
// after the purge and outside its try, so a throwing setItem (private
|
||||
// mode, blocked site data, quota) left the caches deleted, the marker
|
||||
// unwritten and the reload unreached, and the purge then repeated on
|
||||
// every single launch, permanently (#2228).
|
||||
try { localStorage.setItem('trek_app_version', version) } catch { /* site data blocked */ }
|
||||
if (storedVersion && storedVersion !== version) {
|
||||
// A newer build is deployed. Ask the service worker to fetch it and
|
||||
// hand over; Workbox ('autoUpdate' + skipWaiting + clientsClaim)
|
||||
// installs the new precache and only then drops the outdated one, so
|
||||
// there is never a moment without an app shell.
|
||||
//
|
||||
// This used to delete EVERY Cache Storage bucket and unregister EVERY
|
||||
// worker instead. That left the device with no shell and no worker
|
||||
// until a fresh ~22 MB precache finished (minutes on mobile data),
|
||||
// and anyone who closed the app or lost signal in that window was
|
||||
// left with a PWA that could no longer start offline at all. It also
|
||||
// threw away the map tiles and file blobs the user had deliberately
|
||||
// downloaded for offline use (#2228).
|
||||
try {
|
||||
const reg = 'serviceWorker' in navigator ? await navigator.serviceWorker.getRegistration() : undefined
|
||||
if (reg) {
|
||||
navigator.serviceWorker.addEventListener('controllerchange', () => window.location.reload(), { once: true })
|
||||
await reg.update()
|
||||
return
|
||||
}
|
||||
} catch { /* fall through to a plain reload */ }
|
||||
window.location.reload()
|
||||
return
|
||||
}
|
||||
}
|
||||
// Last, since a new release reloads the page from here.
|
||||
await reconcileAppVersion(config?.version)
|
||||
}).catch(() => {})
|
||||
}, [])
|
||||
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
import React from 'react'
|
||||
import { render, waitFor, act } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { server } from '../tests/helpers/msw/server'
|
||||
import { useAuthStore } from './store/authStore'
|
||||
import { resetAllStores } from '../tests/helpers/store'
|
||||
import App from './App'
|
||||
|
||||
/*
|
||||
* #2458: an installed PWA kept serving the previous UI after a server upgrade.
|
||||
*
|
||||
* The launch probe compares the server's version with a marker in localStorage
|
||||
* and, on a mismatch, asks the service worker to fetch the new build and reloads
|
||||
* once it has taken over. These tests drive that probe across consecutive
|
||||
* launches against a fake service-worker container, so a handover that never
|
||||
* completed can be told apart from one that did.
|
||||
*
|
||||
* The fake is installed before App is imported (vi.hoisted), so code that
|
||||
* notes the controlling worker when its module loads sees the worker that
|
||||
* served this page, exactly as in the browser.
|
||||
*/
|
||||
const sw = vi.hoisted(() => {
|
||||
class FakeWorker extends EventTarget {
|
||||
state: string
|
||||
readonly scriptURL = '/sw.js'
|
||||
constructor(state: string) {
|
||||
super()
|
||||
this.state = state
|
||||
}
|
||||
become(state: string) {
|
||||
this.state = state
|
||||
this.dispatchEvent(new Event('statechange'))
|
||||
}
|
||||
}
|
||||
class FakeRegistration extends EventTarget {
|
||||
active: FakeWorker | null = null
|
||||
installing: FakeWorker | null = null
|
||||
waiting: FakeWorker | null = null
|
||||
readonly scope = '/'
|
||||
update = vi.fn()
|
||||
}
|
||||
class FakeContainer extends EventTarget {
|
||||
controller: FakeWorker | null = null
|
||||
getRegistration = vi.fn()
|
||||
// Listeners a page adds die with that page. Those added while modules load
|
||||
// (before `trackPage` is switched on) stand for module-level code and stay.
|
||||
trackPage = false
|
||||
private pageListeners: Array<[string, EventListenerOrEventListenerObject, boolean | AddEventListenerOptions | undefined]> = []
|
||||
addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions) {
|
||||
super.addEventListener(type, listener, options)
|
||||
if (this.trackPage && listener) this.pageListeners.push([type, listener, options])
|
||||
}
|
||||
dropPageListeners() {
|
||||
for (const [type, listener, options] of this.pageListeners) super.removeEventListener(type, listener, options)
|
||||
this.pageListeners = []
|
||||
}
|
||||
}
|
||||
const oldWorker = new FakeWorker('activated')
|
||||
const registration = new FakeRegistration()
|
||||
const container = new FakeContainer()
|
||||
registration.active = oldWorker
|
||||
container.controller = oldWorker
|
||||
container.getRegistration.mockImplementation(async () => registration)
|
||||
Object.defineProperty(navigator, 'serviceWorker', { configurable: true, value: container })
|
||||
return { FakeWorker, registration, container, oldWorker }
|
||||
})
|
||||
|
||||
vi.mock('./pages/LoginPage', () => ({ default: () => <div>Login</div> }))
|
||||
vi.mock('./pages/DashboardPage', () => ({ default: () => <div>Dashboard</div> }))
|
||||
vi.mock('./hooks/useInAppNotificationListener.ts', () => ({ useInAppNotificationListener: vi.fn() }))
|
||||
|
||||
// Every import above has been evaluated by now; from here on a listener belongs to a page.
|
||||
sw.container.trackPage = true
|
||||
|
||||
const reload = vi.fn()
|
||||
let configHits = 0
|
||||
|
||||
function serveVersion(version: string, gate?: Promise<void>) {
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', async () => {
|
||||
configHits++
|
||||
if (gate) await gate
|
||||
return HttpResponse.json({ version })
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/** The browser's handover: the new worker installs, activates and claims the page. */
|
||||
function handOver() {
|
||||
const next = new sw.FakeWorker('activated')
|
||||
sw.registration.installing = null
|
||||
sw.registration.active = next
|
||||
sw.container.controller = next
|
||||
sw.container.dispatchEvent(new Event('controllerchange'))
|
||||
}
|
||||
|
||||
/** update() finds a new sw.js and starts installing it; `then` decides how the install ends. */
|
||||
function updateStartsInstall(then: 'activates' | 'fails') {
|
||||
sw.registration.update.mockImplementation(async () => {
|
||||
const next = new sw.FakeWorker('installing')
|
||||
sw.registration.installing = next
|
||||
setTimeout(() => {
|
||||
if (then === 'activates') {
|
||||
next.become('activated')
|
||||
handOver()
|
||||
} else {
|
||||
// Workbox precaching is all-or-nothing: one failed fetch out of ~463
|
||||
// rejects the install event and the new worker is thrown away.
|
||||
sw.registration.installing = null
|
||||
next.become('redundant')
|
||||
}
|
||||
}, 0)
|
||||
return sw.registration
|
||||
})
|
||||
}
|
||||
|
||||
/** One cold start of the installed app: fresh page, fresh session, same localStorage. */
|
||||
async function launch() {
|
||||
sessionStorage.clear()
|
||||
const hitsBefore = configHits
|
||||
const view = render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<App />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
await waitFor(() => expect(configHits).toBe(hitsBefore + 1))
|
||||
// Let the probe, update() and the fake install run to completion.
|
||||
await act(async () => { await new Promise(r => setTimeout(r, 50)) })
|
||||
view.unmount()
|
||||
sw.container.dropPageListeners()
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
vi.clearAllMocks()
|
||||
configHits = 0
|
||||
sw.registration.active = sw.oldWorker
|
||||
sw.registration.installing = null
|
||||
sw.registration.waiting = null
|
||||
sw.registration.update.mockReset()
|
||||
sw.registration.update.mockResolvedValue(sw.registration)
|
||||
sw.container.controller = sw.oldWorker
|
||||
sw.container.dropPageListeners()
|
||||
sw.container.getRegistration.mockReset()
|
||||
sw.container.getRegistration.mockImplementation(async () => sw.registration)
|
||||
reload.mockReset()
|
||||
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
|
||||
server.use(
|
||||
http.get('/api/health/features', () => HttpResponse.json({ bookingImport: false, aiParsing: false })),
|
||||
http.get('/api/system-notices/active', () => HttpResponse.json([])),
|
||||
)
|
||||
useAuthStore.setState({
|
||||
isLoading: false,
|
||||
isAuthenticated: false,
|
||||
user: null,
|
||||
appRequireMfa: false,
|
||||
loadUser: vi.fn().mockResolvedValue(undefined),
|
||||
})
|
||||
})
|
||||
|
||||
describe('#2458 version handover: behaviour that must survive the fix', () => {
|
||||
it('FE-COMP-APP-2458-P1: a confirmed handover reloads once and is not repeated on the next launch', async () => {
|
||||
localStorage.setItem('trek_app_version', '4.3.0')
|
||||
serveVersion('4.3.1')
|
||||
updateStartsInstall('activates')
|
||||
|
||||
await launch()
|
||||
expect(sw.registration.update).toHaveBeenCalledTimes(1)
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
expect(localStorage.getItem('trek_app_version')).toBe('4.3.1')
|
||||
|
||||
await launch()
|
||||
expect(sw.registration.update).toHaveBeenCalledTimes(1)
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-2458-P2: nothing to hand over (sw.js unchanged, same worker in control) neither reloads nor retries', async () => {
|
||||
// A release that changed nothing the precache holds leaves sw.js byte-identical,
|
||||
// so update() installs nothing. The bundle this page runs is already current.
|
||||
localStorage.setItem('trek_app_version', '4.3.0')
|
||||
serveVersion('4.3.1')
|
||||
|
||||
await launch()
|
||||
expect(sw.registration.update).toHaveBeenCalledTimes(1)
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
|
||||
await launch()
|
||||
expect(sw.registration.update).toHaveBeenCalledTimes(1)
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a self-built image without the build arg', 'dev'],
|
||||
['a test instance pinned to an older tag', '4.0.0'],
|
||||
['a prerelease image, whose bundle keeps the last stable version', '4.4.0-pre.3'],
|
||||
])('FE-COMP-APP-2458-P3: %s (server says %s, bundle is built as another version) never loops', async (_label, serverVersion) => {
|
||||
// The server reports APP_VERSION, the bundle carries client/package.json. On
|
||||
// these setups the two never agree, so a check against the bundle's own
|
||||
// version would see an update on every launch.
|
||||
serveVersion(serverVersion)
|
||||
|
||||
await launch()
|
||||
await launch()
|
||||
await launch()
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
expect(sw.registration.update).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('#2458 version handover: the reported defect', () => {
|
||||
it('FE-COMP-APP-2458-01: an update() that rejects is retried on the next launch', async () => {
|
||||
localStorage.setItem('trek_app_version', '4.3.0')
|
||||
serveVersion('4.3.1')
|
||||
sw.registration.update.mockRejectedValue(new TypeError('Failed to update a ServiceWorker: network error'))
|
||||
|
||||
await launch()
|
||||
expect(sw.registration.update).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Next cold start, network fine this time.
|
||||
updateStartsInstall('activates')
|
||||
await launch()
|
||||
expect(sw.registration.update).toHaveBeenCalledTimes(2)
|
||||
expect(reload).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-2458-02: a failed update() does not reload into the shell the same worker serves again', async () => {
|
||||
// The old worker still controls the page, so a plain reload is answered from
|
||||
// its precache: the same old UI, now with the marker saying it is current.
|
||||
localStorage.setItem('trek_app_version', '4.3.0')
|
||||
serveVersion('4.3.1')
|
||||
sw.registration.update.mockRejectedValue(new TypeError('Failed to update a ServiceWorker: network error'))
|
||||
|
||||
await launch()
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-APP-2458-03: an install that goes redundant is retried on the next launch', async () => {
|
||||
localStorage.setItem('trek_app_version', '4.3.0')
|
||||
serveVersion('4.3.1')
|
||||
updateStartsInstall('fails')
|
||||
|
||||
await launch()
|
||||
expect(sw.registration.update).toHaveBeenCalledTimes(1)
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
|
||||
updateStartsInstall('activates')
|
||||
await launch()
|
||||
expect(sw.registration.update).toHaveBeenCalledTimes(2)
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
// Kept last: it swaps the controlling worker mid-launch, which code that
|
||||
// remembers "the controller changed since this page loaded" keeps seeing.
|
||||
it('FE-COMP-APP-2458-04: a worker that took over before the probe answered still reloads the page', async () => {
|
||||
// The browser checks sw.js on every navigation by itself. When that check
|
||||
// installs and activates the new worker before /api/auth/app-config has
|
||||
// answered, the takeover happens while nobody listens, and update() then
|
||||
// finds nothing newer. The page keeps running the bundle the old worker served.
|
||||
localStorage.setItem('trek_app_version', '4.3.0')
|
||||
let open!: () => void
|
||||
const gate = new Promise<void>(r => { open = r })
|
||||
serveVersion('4.3.1', gate)
|
||||
|
||||
sessionStorage.clear()
|
||||
const view = render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<App />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
await waitFor(() => expect(configHits).toBe(1))
|
||||
act(() => handOver())
|
||||
open()
|
||||
await act(async () => { await new Promise(r => setTimeout(r, 50)) })
|
||||
view.unmount()
|
||||
sw.container.dropPageListeners()
|
||||
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-APISURF-001 to FE-APISURF-054
|
||||
// FE-APISURF-001 to FE-APISURF-059
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import type { AxiosResponse } from 'axios'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
mapsApi, airportsApi, budgetApi, filesApi, reservationsApi, healthApi, weatherApi,
|
||||
configApi, helpApi, settingsApi, accommodationsApi, dayNotesApi, collabApi, backupApi,
|
||||
shareApi, transitApi, tripInviteApi, notificationsApi, inAppNotificationsApi, memoriesApi,
|
||||
docsyncApi, DOCSYNC_RUN_TIMEOUT_MS, DOCSYNC_UPSTREAM_TIMEOUT_MS,
|
||||
} from './client'
|
||||
|
||||
interface Recorded { method: string; url: string; body: unknown }
|
||||
@@ -454,6 +455,7 @@ describe('client > endpoint wiring', () => {
|
||||
{ n: 'createSettlement', r: () => budgetApi.createSettlement(1, { from_user_id: 4, to_user_id: 5, amount: 10 }), e: 'POST /api/trips/1/budget/settlements' },
|
||||
{ n: 'updateSettlement', r: () => budgetApi.updateSettlement(1, 6, { from_user_id: 4, to_user_id: 5, amount: 12 }), e: 'PUT /api/trips/1/budget/settlements/6' },
|
||||
{ n: 'deleteSettlement', r: () => budgetApi.deleteSettlement(1, 6), e: 'DELETE /api/trips/1/budget/settlements/6' },
|
||||
{ n: 'freezeRates', r: () => budgetApi.freezeRates(1, {}), e: 'POST /api/trips/1/budget/freeze-rates' },
|
||||
{ n: 'reorderItems', r: () => budgetApi.reorderItems(1, [2, 3]), e: 'PUT /api/trips/1/budget/reorder/items' },
|
||||
{ n: 'reorderCategories', r: () => budgetApi.reorderCategories(1, ['Food']), e: 'PUT /api/trips/1/budget/reorder/categories' },
|
||||
])
|
||||
@@ -571,6 +573,19 @@ describe('client > request payloads', () => {
|
||||
expect((await traceOne(() => journeyApi.reorderEntries(2, [8, 7]))).body).toEqual({ orderedIds: [8, 7] })
|
||||
})
|
||||
|
||||
it('FE-APISURF-059: the settlement carries the display rate only when the caller has one', async () => {
|
||||
expect((await traceOne(() => budgetApi.settlement(1, 'EUR', 0.61))).url).toBe('/api/trips/1/budget/settlement?base=EUR&base_rate=0.61')
|
||||
expect((await traceOne(() => budgetApi.settlement(1, 'EUR', null))).url).toBe('/api/trips/1/budget/settlement?base=EUR')
|
||||
expect((await traceOne(() => budgetApi.settlement(1))).url).toBe('/api/trips/1/budget/settlement')
|
||||
const lent = { fallback_fx: { base: 'AUD', rates: { VND: 18241.3 } } }
|
||||
expect((await traceOne(() => budgetApi.freezeRates(1, lent))).body).toEqual(lent)
|
||||
})
|
||||
|
||||
it('FE-APISURF-058: a dated day is asked for with the dated flag alone', async () => {
|
||||
const rec = await traceOne(() => daysApi.create(1, { dated: true }))
|
||||
expect(rec).toMatchObject({ method: 'POST', url: '/api/trips/1/days', body: { dated: true } })
|
||||
})
|
||||
|
||||
it('FE-APISURF-023: user-id collections are sent as user_ids', async () => {
|
||||
expect((await traceOne(() => assignmentsApi.setParticipants(1, 7, [4, 5]))).body).toEqual({ user_ids: [4, 5] })
|
||||
expect((await traceOne(() => budgetApi.setMembers(1, 2, [4]))).body).toEqual({ user_ids: [4] })
|
||||
@@ -665,6 +680,12 @@ describe('client > request payloads', () => {
|
||||
expect(rec.method).toBe('DELETE')
|
||||
expect(rec.body).toEqual({ password: 'hunter2' })
|
||||
})
|
||||
|
||||
it('FE-APISURF-056: docsyncApi.createScope names the connection in the path only', async () => {
|
||||
const rec = await traceOne(() => docsyncApi.createScope(1, 5, 'Norway'))
|
||||
expect(`${rec.method} ${rec.url}`).toBe('POST /api/trips/1/docsync/connections/5/scopes')
|
||||
expect(rec.body).toEqual({ name: 'Norway' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('client > query parameters', () => {
|
||||
@@ -895,4 +916,47 @@ describe('client > multipart uploads', () => {
|
||||
expect(call[2]).toMatchObject({ timeout: 40000 })
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-APISURF-057: every document-sync call that reaches the store outlives the 8s global timeout', async () => {
|
||||
const post = spyPost()
|
||||
const get = vi.spyOn(apiClient, 'get').mockResolvedValue({ data: { ok: true } } as unknown as AxiosResponse)
|
||||
const del = vi.spyOn(apiClient, 'delete').mockResolvedValue({ data: { ok: true } } as unknown as AxiosResponse)
|
||||
|
||||
// The server allows each request to a store 15 s, and a run waits for the
|
||||
// whole listing and every transfer; cut off at 8 s the browser reported a
|
||||
// failure while the server carried on and finished.
|
||||
await docsyncApi.testConnection(1, { providerId: 'paperless' })
|
||||
await docsyncApi.createScope(1, 5, 'Norway')
|
||||
await docsyncApi.createLink(1, { connectionId: 5 })
|
||||
await docsyncApi.listScopes(1, 5)
|
||||
await docsyncApi.deleteLink(1, 9)
|
||||
|
||||
expect(post.mock.calls.map(c => c[0])).toEqual([
|
||||
'/trips/1/docsync/connections/test',
|
||||
'/trips/1/docsync/connections/5/scopes',
|
||||
'/trips/1/docsync/links',
|
||||
])
|
||||
for (const call of post.mock.calls) {
|
||||
expect(call[2]).toMatchObject({ timeout: DOCSYNC_UPSTREAM_TIMEOUT_MS })
|
||||
}
|
||||
expect(get.mock.calls[0][0]).toBe('/trips/1/docsync/connections/5/scopes')
|
||||
expect(get.mock.calls[0][1]).toMatchObject({ timeout: DOCSYNC_UPSTREAM_TIMEOUT_MS })
|
||||
expect(del.mock.calls[0][0]).toBe('/trips/1/docsync/links/9')
|
||||
expect(del.mock.calls[0][1]).toMatchObject({ timeout: DOCSYNC_UPSTREAM_TIMEOUT_MS })
|
||||
expect(DOCSYNC_UPSTREAM_TIMEOUT_MS).toBeGreaterThan(8000)
|
||||
|
||||
// A run, and a conflict choice that runs the binding afterwards.
|
||||
post.mockClear()
|
||||
await docsyncApi.syncNow(1, 9)
|
||||
await docsyncApi.resolve(1, 4, 'trek')
|
||||
|
||||
expect(post.mock.calls.map(c => c[0])).toEqual([
|
||||
'/trips/1/docsync/links/9/sync',
|
||||
'/trips/1/docsync/items/4/resolve',
|
||||
])
|
||||
for (const call of post.mock.calls) {
|
||||
expect(call[2]).toMatchObject({ timeout: DOCSYNC_RUN_TIMEOUT_MS })
|
||||
}
|
||||
expect(DOCSYNC_RUN_TIMEOUT_MS).toBeGreaterThan(DOCSYNC_UPSTREAM_TIMEOUT_MS)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { isEffectivelyOffline } from '../sync/networkMode'
|
||||
import axios, { AxiosInstance } from 'axios'
|
||||
import type { z } from 'zod'
|
||||
import type { Place } from '../types'
|
||||
import type { Day, Place, Trip } from '../types'
|
||||
import type { TransitProvider } from '@trek/shared'
|
||||
import { randomId } from '../utils/randomId'
|
||||
import {
|
||||
@@ -40,6 +40,8 @@ import {
|
||||
type PackingImportRequest, type PackingBagMembersRequest, type PackingUpdateBagRequest,
|
||||
type PackingCategoryAssigneesRequest, type PackingApplyTemplateRequest,
|
||||
type BudgetUpdateMembersRequest, type BudgetToggleMemberPaidRequest, type BudgetReorderCategoriesRequest,
|
||||
type BudgetCreateSettlementRequest, type BudgetUpdateSettlementRequest, type BudgetSettlementQuery,
|
||||
type BudgetFreezeRatesRequest, type BudgetFreezeRatesResponse,
|
||||
type TodoCategoryAssigneesRequest,
|
||||
type CollabNoteCreateRequest, type CollabNoteUpdateRequest, type CollabPollCreateRequest,
|
||||
type CollabPollVoteRequest, type CollabMessageCreateRequest, type CollabReactionRequest,
|
||||
@@ -434,11 +436,17 @@ export const tripsApi = {
|
||||
|
||||
export const daysApi = {
|
||||
list: (tripId: number | string) => apiClient.get(`/trips/${tripId}/days`).then(r => r.data),
|
||||
create: (tripId: number | string, data: DayCreateRequest) => apiClient.post(`/trips/${tripId}/days`, data).then(r => r.data),
|
||||
// `trip` comes along when the new day changed the trip itself: a dated day
|
||||
// (`dated: true`) moved its end date, an insert at a position grew it by a day.
|
||||
create: (tripId: number | string, data: DayCreateRequest): Promise<{ day: Day; trip?: Trip }> =>
|
||||
apiClient.post(`/trips/${tripId}/days`, data).then(r => r.data),
|
||||
update: (tripId: number | string, dayId: number | string, data: DayUpdateRequest) => apiClient.put(`/trips/${tripId}/days/${dayId}`, data).then(r => r.data),
|
||||
// Whole-day default route mode (#1281); per-segment leg modes override it.
|
||||
updateTransport: (tripId: number | string, dayId: number | string, mode: string | null) => apiClient.put(`/trips/${tripId}/days/${dayId}/transport`, { transport_mode: mode }).then(r => r.data),
|
||||
delete: (tripId: number | string, dayId: number | string) => apiClient.delete(`/trips/${tripId}/days/${dayId}`).then(r => r.data),
|
||||
// Answers with the trip in list shape: its day count changed, and its end
|
||||
// date when the day took the last date along.
|
||||
delete: (tripId: number | string, dayId: number | string): Promise<{ success: boolean; trip?: Trip }> =>
|
||||
apiClient.delete(`/trips/${tripId}/days/${dayId}`).then(r => r.data),
|
||||
reorder: (tripId: number | string, orderedIds: number[]) => apiClient.put(`/trips/${tripId}/days/reorder`, { orderedIds } satisfies DayReorderRequest).then(r => r.data),
|
||||
}
|
||||
|
||||
@@ -671,6 +679,8 @@ export const adminApi = {
|
||||
updatePlacesAutocomplete: (enabled: boolean) => apiClient.put('/admin/places-autocomplete', { enabled }).then(r => r.data),
|
||||
getPlacesDetails: () => apiClient.get('/admin/places-details').then(r => r.data),
|
||||
updatePlacesDetails: (enabled: boolean) => apiClient.put('/admin/places-details', { enabled }).then(r => r.data),
|
||||
getPlacesGoogleOnly: () => apiClient.get('/admin/places-google-only').then(r => r.data),
|
||||
updatePlacesGoogleOnly: (enabled: boolean) => apiClient.put('/admin/places-google-only', { enabled }).then(r => r.data),
|
||||
getPlacesEnrich: () => apiClient.get('/admin/places-enrich').then(r => r.data),
|
||||
updatePlacesEnrich: (enabled: boolean) => apiClient.put('/admin/places-enrich', { enabled }).then(r => r.data),
|
||||
getTransitProvider: () => apiClient.get('/admin/transit-provider').then(r => r.data),
|
||||
@@ -1050,7 +1060,10 @@ const MEMORIES_TIMEOUT = 0
|
||||
export const memoriesApi = {
|
||||
status: (provider: string): Promise<{ connected: boolean }> =>
|
||||
apiClient.get(`/integrations/memories/${provider}/status`, { timeout: MEMORIES_TIMEOUT }).then(r => r.data),
|
||||
search: (provider: string, body: { from: string; to: string; page: number; size: number }, signal?: AbortSignal) =>
|
||||
// utc_offset_minutes says which 24 hours from/to name. It is NOT the Synology
|
||||
// `offset`, which is rows to skip: one body goes to whichever provider, so the
|
||||
// two names have to stay apart (#2336).
|
||||
search: (provider: string, body: { from: string; to: string; page: number; size: number; utc_offset_minutes?: number }, signal?: AbortSignal) =>
|
||||
apiClient.post(`/integrations/memories/${provider}/search`, body, { timeout: MEMORIES_TIMEOUT, signal }).then(r => r.data),
|
||||
albums: (provider: string) =>
|
||||
apiClient.get(`/integrations/memories/${provider}/albums`, { timeout: MEMORIES_TIMEOUT }).then(r => r.data),
|
||||
@@ -1211,14 +1224,19 @@ export const mapsApi = {
|
||||
* caller of this one function gets them without knowing they exist. Appended rather
|
||||
* than interleaved: the core list is ordered by relevance and has earned that order,
|
||||
* and a plugin's row carries its own `source` for a caller that wants to mark it.
|
||||
*
|
||||
* `provider: 'google'` sends this one search to Google alone, the "search Google
|
||||
* instead" link under a list the index answered with the wrong place. The server
|
||||
* ignores it unless Google holds the keyed slot: without a Google key, or with
|
||||
* Amap or OpenStreetMap picked as the provider, the index answers as usual.
|
||||
*/
|
||||
search: (query: string, lang?: string, locationBias?: { lat: number; lng: number; radius?: number }) =>
|
||||
search: (query: string, lang?: string, locationBias?: { lat: number; lng: number; radius?: number }, provider?: 'google') =>
|
||||
withCachedPlaces(query, (places) => ({ places, source: 'offline-cache' }), async () => {
|
||||
// Side by side, so the wait is the slower of the two rather than their sum. Only
|
||||
// the core call may reject: that rejection is what hands withCachedPlaces the
|
||||
// offline path, and a plugin failure must never trigger it.
|
||||
const [core, extra] = await Promise.all([
|
||||
apiClient.post(`/maps/search?lang=${lang || 'en'}`, { query, locationBias }).then(r => checkInDev(mapsSearchResultSchema, r.data, 'maps.search')),
|
||||
apiClient.post(`/maps/search?lang=${lang || 'en'}`, { query, locationBias, ...(provider ? { provider } : {}) }).then(r => checkInDev(mapsSearchResultSchema, r.data, 'maps.search')),
|
||||
pluginSearchPlaces(query, lang, locationBias),
|
||||
])
|
||||
if (extra.length === 0) return core
|
||||
@@ -1336,9 +1354,13 @@ export const budgetApi = {
|
||||
togglePaid: (tripId: number | string, id: number, userId: number, paid: boolean) => apiClient.put(`/trips/${tripId}/budget/${id}/members/${userId}/paid`, { paid } satisfies BudgetToggleMemberPaidRequest).then(r => r.data),
|
||||
setPayers: (tripId: number | string, id: number, payers: { user_id: number; amount: number }[]) => apiClient.put(`/trips/${tripId}/budget/${id}/payers`, { payers }).then(r => r.data),
|
||||
perPersonSummary: (tripId: number | string) => apiClient.get(`/trips/${tripId}/budget/summary/per-person`).then(r => r.data),
|
||||
settlement: (tripId: number | string, base?: string) => apiClient.get(`/trips/${tripId}/budget/settlement`, base ? { params: { base } } : undefined).then(r => r.data),
|
||||
createSettlement: (tripId: number | string, data: { from_user_id: number; to_user_id: number; amount: number; currency?: string; settled_at?: string | null }) => apiClient.post(`/trips/${tripId}/budget/settlements`, data).then(r => r.data),
|
||||
updateSettlement: (tripId: number | string, settlementId: number, data: { from_user_id: number; to_user_id: number; amount: number; currency?: string; settled_at?: string | null }) => apiClient.put(`/trips/${tripId}/budget/settlements/${settlementId}`, data).then(r => r.data),
|
||||
// `baseRate` is units of `base` per 1 trip currency from the client's own rates. The server
|
||||
// uses it only in place of a display quote it cannot fetch itself, which also reads legacy
|
||||
// transfers without a currency (in the display currency, as with a live quote).
|
||||
settlement: (tripId: number | string, base?: string, baseRate?: number | null) => apiClient.get(`/trips/${tripId}/budget/settlement`, base ? { params: { base, ...(baseRate != null ? { base_rate: baseRate } : {}) } satisfies BudgetSettlementQuery } : undefined).then(r => r.data),
|
||||
createSettlement: (tripId: number | string, data: BudgetCreateSettlementRequest) => apiClient.post(`/trips/${tripId}/budget/settlements`, data).then(r => r.data),
|
||||
updateSettlement: (tripId: number | string, settlementId: number, data: BudgetUpdateSettlementRequest) => apiClient.put(`/trips/${tripId}/budget/settlements/${settlementId}`, data).then(r => r.data),
|
||||
freezeRates: (tripId: number | string, data: BudgetFreezeRatesRequest): Promise<BudgetFreezeRatesResponse> => apiClient.post(`/trips/${tripId}/budget/freeze-rates`, data).then(r => r.data),
|
||||
deleteSettlement: (tripId: number | string, settlementId: number) => apiClient.delete(`/trips/${tripId}/budget/settlements/${settlementId}`).then(r => r.data),
|
||||
reorderItems: (tripId: number | string, orderedIds: number[]) => apiClient.put(`/trips/${tripId}/budget/reorder/items`, { orderedIds }).then(r => r.data),
|
||||
reorderCategories: (tripId: number | string, orderedCategories: string[]) => apiClient.put(`/trips/${tripId}/budget/reorder/categories`, { orderedCategories } satisfies BudgetReorderCategoriesRequest).then(r => r.data),
|
||||
@@ -1358,6 +1380,64 @@ export const filesApi = {
|
||||
getLinks: (tripId: number | string, fileId: number) => apiClient.get(`/trips/${tripId}/files/${fileId}/links`).then(r => r.data),
|
||||
}
|
||||
|
||||
/**
|
||||
* How long the browser waits for a document-sync call that makes the server go
|
||||
* and ask the store.
|
||||
*
|
||||
* The shared 8 s on `apiClient` is right for TREK's own routes and wrong for
|
||||
* these, for the reason `dawarich.ts` gives: the server allows each request to
|
||||
* a store 15 s by itself (20 s for Papra), a connection test may probe more
|
||||
* than once, and binding or unbinding first registers or removes a webhook at
|
||||
* the store. Cut off at 8 s, the browser reported a failure while the server
|
||||
* carried on and finished, so a listing that took twelve seconds read as a
|
||||
* broken store.
|
||||
*/
|
||||
export const DOCSYNC_UPSTREAM_TIMEOUT_MS = 60_000
|
||||
|
||||
/**
|
||||
* A run is longer again. The server answers only once the whole of it is
|
||||
* through: a listing of up to 40 pages, then up to 25 transfers at up to 120 s
|
||||
* each, and Paperless-ngx holds every push until its consume task has run.
|
||||
* Resolving a conflict runs the binding afterwards, so it waits just as long.
|
||||
* Ten minutes covers a full transfer budget of ordinary documents; a run that
|
||||
* outlasts it still finishes on the server, and the `docsync:changed` ping
|
||||
* refreshes the dialog when it does.
|
||||
*/
|
||||
export const DOCSYNC_RUN_TIMEOUT_MS = 600_000
|
||||
|
||||
const docsyncUpstream = { timeout: DOCSYNC_UPSTREAM_TIMEOUT_MS }
|
||||
const docsyncRun = { timeout: DOCSYNC_RUN_TIMEOUT_MS }
|
||||
|
||||
/**
|
||||
* Document sync: one provider connection per trip, shared by every member.
|
||||
*
|
||||
* Trip-scoped rather than user-scoped on purpose: a per-user connection would
|
||||
* make a document's visibility depend on whose credentials fetched it, which is
|
||||
* the opposite of what a shared trip needs.
|
||||
*/
|
||||
export const docsyncApi = {
|
||||
providers: (tripId: number | string) => apiClient.get(`/trips/${tripId}/docsync/providers`).then(r => r.data),
|
||||
status: (tripId: number | string) => apiClient.get(`/trips/${tripId}/docsync/status`).then(r => r.data),
|
||||
listConnections: (tripId: number | string) => apiClient.get(`/trips/${tripId}/docsync/connections`).then(r => r.data),
|
||||
saveConnection: (tripId: number | string, data: unknown) => apiClient.put(`/trips/${tripId}/docsync/connections`, data).then(r => r.data),
|
||||
testConnection: (tripId: number | string, data: unknown) => apiClient.post(`/trips/${tripId}/docsync/connections/test`, data, docsyncUpstream).then(r => r.data),
|
||||
deleteConnection: (tripId: number | string, connectionId: number) => apiClient.delete(`/trips/${tripId}/docsync/connections/${connectionId}`).then(r => r.data),
|
||||
listScopes: (tripId: number | string, connectionId: number, q?: string) =>
|
||||
apiClient.get(`/trips/${tripId}/docsync/connections/${connectionId}/scopes`, { params: q ? { q } : {}, ...docsyncUpstream }).then(r => r.data),
|
||||
createScope: (tripId: number | string, connectionId: number, name: string) =>
|
||||
apiClient.post(`/trips/${tripId}/docsync/connections/${connectionId}/scopes`, { name }, docsyncUpstream).then(r => r.data),
|
||||
listLinks: (tripId: number | string) => apiClient.get(`/trips/${tripId}/docsync/links`).then(r => r.data),
|
||||
createLink: (tripId: number | string, data: unknown) => apiClient.post(`/trips/${tripId}/docsync/links`, data, docsyncUpstream).then(r => r.data),
|
||||
updateLink: (tripId: number | string, linkId: number, data: unknown) => apiClient.patch(`/trips/${tripId}/docsync/links/${linkId}`, data).then(r => r.data),
|
||||
deleteLink: (tripId: number | string, linkId: number) => apiClient.delete(`/trips/${tripId}/docsync/links/${linkId}`, docsyncUpstream).then(r => r.data),
|
||||
syncNow: (tripId: number | string, linkId: number, full = false) =>
|
||||
apiClient.post(`/trips/${tripId}/docsync/links/${linkId}/sync`, { full }, docsyncRun).then(r => r.data),
|
||||
items: (tripId: number | string, state?: string) =>
|
||||
apiClient.get(`/trips/${tripId}/docsync/items`, { params: state ? { state } : {} }).then(r => r.data),
|
||||
resolve: (tripId: number | string, itemId: number, keep: 'trek' | 'provider' | 'both') =>
|
||||
apiClient.post(`/trips/${tripId}/docsync/items/${itemId}/resolve`, { keep }, docsyncRun).then(r => r.data),
|
||||
}
|
||||
|
||||
export const reservationsApi = {
|
||||
list: (tripId: number | string) => apiClient.get(`/trips/${tripId}/reservations`).then(r => r.data),
|
||||
upcoming: () => apiClient.get('/reservations/upcoming').then(r => r.data),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-032
|
||||
// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-034
|
||||
//
|
||||
// The Collections addon wrapper is thin, but every method encodes a URL, a verb and a
|
||||
// request-body shape that the server contract depends on. These tests drive each method
|
||||
@@ -342,4 +342,23 @@ describe('collectionsApi', () => {
|
||||
expect(requestBody).toEqual({ label_ids: [3], place_ids: [10] })
|
||||
expect(res.changed).toBe(1)
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-033: exportGpx() reads the GPX of a list by id', async () => {
|
||||
server.use(http.get(`${BASE}/:id/export/gpx`, record({ name: 'Tokyo', gpx: '<gpx/>', waypoints: 0, omitted: 2 })))
|
||||
|
||||
const res = await collectionsApi.exportGpx(1)
|
||||
|
||||
expect(requestUrl).toContain(`${BASE}/1/export/gpx`)
|
||||
expect(res).toEqual({ name: 'Tokyo', gpx: '<gpx/>', waypoints: 0, omitted: 2 })
|
||||
})
|
||||
|
||||
it('FE-API-COLLECTIONS-034: readGpx() posts the document and its file name', async () => {
|
||||
const file = { format: 'trek.collection', version: 1, name: 'Tokyo', places: [] }
|
||||
server.use(http.post(`${BASE}/gpx/read`, record({ file, skipped: 0, track_points: 12 })))
|
||||
|
||||
const res = await collectionsApi.readGpx({ gpx: '<gpx/>', file_name: 'tokyo.gpx' })
|
||||
|
||||
expect(requestBody).toEqual({ gpx: '<gpx/>', file_name: 'tokyo.gpx' })
|
||||
expect(res).toEqual({ file, skipped: 0, track_points: 12 })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -12,7 +12,11 @@ import type {
|
||||
CollectionImportablesResponse,
|
||||
CollectionFile,
|
||||
CollectionImportRequest,
|
||||
CollectionImportIntoRequest,
|
||||
CollectionImportResult,
|
||||
CollectionGpxExport,
|
||||
CollectionGpxReadRequest,
|
||||
CollectionGpxReadResult,
|
||||
CollectionPlaceUpdateRequest,
|
||||
CollectionCopyToTripRequest,
|
||||
CollectionInviteRequest,
|
||||
@@ -62,6 +66,15 @@ export const collectionsApi = {
|
||||
ax.get(`${base}/${id}/export`).then((r: AxiosResponse) => r.data),
|
||||
importFile: (body: CollectionImportRequest): Promise<CollectionImportResult> =>
|
||||
ax.post(`${base}/import`, body satisfies CollectionImportRequest).then((r: AxiosResponse) => r.data),
|
||||
/** The same file into a list that already exists: it only ever adds to it. */
|
||||
importFileInto: (id: number, body: CollectionImportIntoRequest): Promise<CollectionImportResult> =>
|
||||
ax.post(`${base}/${id}/import`, body satisfies CollectionImportIntoRequest).then((r: AxiosResponse) => r.data),
|
||||
// The same list as GPX (#2301). A GPX is read by the server into a list file,
|
||||
// which then goes through importFile above like any other.
|
||||
exportGpx: (id: number): Promise<CollectionGpxExport> =>
|
||||
ax.get(`${base}/${id}/export/gpx`).then((r: AxiosResponse) => r.data),
|
||||
readGpx: (body: CollectionGpxReadRequest): Promise<CollectionGpxReadResult> =>
|
||||
ax.post(`${base}/gpx/read`, body satisfies CollectionGpxReadRequest).then((r: AxiosResponse) => r.data),
|
||||
// Both answer with the bare collection, not a { collection } envelope — the
|
||||
// controller returns the service's `Collection` straight through, and the e2e
|
||||
// suite pins that shape. Declaring the envelope made createCollection() resolve
|
||||
|
||||
@@ -81,6 +81,12 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
|
||||
// who has the book open, and where their pointers are)
|
||||
'journey:book:peers',
|
||||
'journey:book:cursor',
|
||||
// Document sync: components/Files/docsync/useDocSync re-reads the bindings
|
||||
// and their counts, and components/Files/docsync/useDocSyncOffered asks
|
||||
// again whether the Files screen offers the sync button. Content-free like
|
||||
// the bag ping: what a run changed is per-binding server state, and the
|
||||
// files it moved arrive as file:* events.
|
||||
'docsync:changed',
|
||||
// Booking import — BackgroundTasks/BackgroundTasksWidget ('import:' prefix listener)
|
||||
'import:progress',
|
||||
'import:done',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-ADMIN-ADDON-001 to FE-ADMIN-ADDON-025
|
||||
// FE-ADMIN-ADDON-001 to FE-ADMIN-ADDON-037
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { delay, http, HttpResponse } from 'msw';
|
||||
@@ -418,7 +418,102 @@ describe('AddonManager', () => {
|
||||
expect(isOn(addonToggle('Todo List'))).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-018: the collab sub-features render their state and report the toggled key', async () => {
|
||||
it('FE-ADMIN-ADDON-033: document providers hang off Documents with their glyphs and stay out of the count', async () => {
|
||||
server.use(addonsRoute([
|
||||
buildAddon({ id: 'documents', name: 'Documents', icon: 'FileText', enabled: true }),
|
||||
buildAddon({ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: false }),
|
||||
buildAddon({ id: 'paperless', name: 'Paperless-ngx', description: 'Document archive', type: 'document_provider', enabled: true }),
|
||||
buildAddon({ id: 'nextcloud', name: 'Nextcloud', description: 'WebDAV files', type: 'document_provider', enabled: false }),
|
||||
]));
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText('Paperless-ngx');
|
||||
const paperlessRow = screen.getByText('Paperless-ngx').closest('li') as HTMLElement;
|
||||
expect(paperlessRow.querySelector('svg')).toBeInTheDocument();
|
||||
expect(isOn(subToggle('Paperless-ngx'))).toBe(true);
|
||||
expect(isOn(subToggle('Nextcloud'))).toBe(false);
|
||||
// Documents and Journey are the addons; an enabled provider is a shelf row
|
||||
// and must not turn 1/2 into 2/2.
|
||||
expect(screen.getByText('1/2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-034: document providers stay hidden while Documents itself is off', async () => {
|
||||
server.use(addonsRoute([
|
||||
buildAddon({ id: 'documents', name: 'Documents', icon: 'FileText', enabled: false }),
|
||||
buildAddon({ id: 'paperless', name: 'Paperless-ngx', type: 'document_provider', enabled: true }),
|
||||
]));
|
||||
render(<AddonManager />);
|
||||
|
||||
await screen.findByText('Documents');
|
||||
expect(screen.queryByText('Paperless-ngx')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-035: switching Documents off and on again shows the cascaded providers as off', async () => {
|
||||
const user = userEvent.setup();
|
||||
let loads = 0;
|
||||
let documentsOn = true;
|
||||
let paperlessOn = true;
|
||||
server.use(
|
||||
http.get('/api/admin/addons', () => {
|
||||
loads += 1;
|
||||
return HttpResponse.json({
|
||||
addons: [
|
||||
buildAddon({ id: 'documents', name: 'Documents', icon: 'FileText', enabled: documentsOn }),
|
||||
buildAddon({ id: 'paperless', name: 'Paperless-ngx', type: 'document_provider', enabled: paperlessOn }),
|
||||
],
|
||||
});
|
||||
}),
|
||||
http.put('/api/admin/addons/documents', async ({ request }) => {
|
||||
documentsOn = (await request.json() as { enabled: boolean }).enabled;
|
||||
if (!documentsOn) paperlessOn = false;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><AddonManager /></>);
|
||||
await screen.findByText('Paperless-ngx');
|
||||
|
||||
await user.click(addonToggle('Documents'));
|
||||
await screen.findByText('Addon updated');
|
||||
expect(loads).toBe(2);
|
||||
expect(screen.queryByText('Paperless-ngx')).not.toBeInTheDocument();
|
||||
|
||||
await user.click(addonToggle('Documents'));
|
||||
|
||||
await screen.findByText('Paperless-ngx');
|
||||
expect(isOn(subToggle('Paperless-ngx'))).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-036: toggling a document provider persists it without re-reading the list', async () => {
|
||||
const user = userEvent.setup();
|
||||
let loads = 0;
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
http.get('/api/admin/addons', () => {
|
||||
loads += 1;
|
||||
return HttpResponse.json({
|
||||
addons: [
|
||||
buildAddon({ id: 'documents', name: 'Documents', icon: 'FileText', enabled: true }),
|
||||
buildAddon({ id: 'papra', name: 'Papra', type: 'document_provider', enabled: false }),
|
||||
],
|
||||
});
|
||||
}),
|
||||
http.put('/api/admin/addons/papra', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
render(<><ToastContainer /><AddonManager /></>);
|
||||
await screen.findByText('Papra');
|
||||
|
||||
await user.click(subToggle('Papra'));
|
||||
|
||||
await screen.findByText('Addon updated');
|
||||
expect(body).toEqual({ enabled: true });
|
||||
expect(loads).toBe(1);
|
||||
expect(isOn(subToggle('Papra'))).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-018:the collab sub-features render their state and report the toggled key', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onToggleCollabFeature = vi.fn();
|
||||
server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));
|
||||
@@ -448,6 +543,22 @@ describe('AddonManager', () => {
|
||||
expect(screen.queryByText('Polls')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-037: the links row describes the feature, not an empty list', async () => {
|
||||
// The row's tooltip is its description. The links tab's empty state read as a
|
||||
// status here, and a status that never changes reads as a broken feature.
|
||||
server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));
|
||||
render(
|
||||
<AddonManager
|
||||
collabFeatures={{ chat: true, notes: true, links: true, polls: true, whatsnext: true }}
|
||||
onToggleCollabFeature={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const links = await screen.findByText('Links');
|
||||
expect(links).toHaveAttribute('title');
|
||||
expect(links.getAttribute('title')).not.toBe('No shared links yet');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-ADDON-020: a disabled AI-parsing addon renders the row without its config block', async () => {
|
||||
server.use(addonsRoute([{ ...llmAddon({ provider: 'local' }), enabled: false }]));
|
||||
render(<AddonManager />);
|
||||
|
||||
@@ -9,6 +9,7 @@ import CustomSelect from '../shared/CustomSelect'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import AirTrailIcon from '../shared/AirTrailIcon'
|
||||
import { DOCUMENT_PROVIDER_ICONS } from '../shared/DocumentProviderIcons'
|
||||
import AddonTile from './AddonTile'
|
||||
import AddonSubRow from './AddonSubRow'
|
||||
|
||||
@@ -41,6 +42,9 @@ function SynologyIcon({ size = 14 }: { size?: number }) {
|
||||
const PROVIDER_ICONS: Record<string, ComponentType<{ size?: number }>> = {
|
||||
immich: ImmichIcon,
|
||||
synologyphotos: SynologyIcon,
|
||||
// The document providers' own marks, single-colour so they read as glyphs in
|
||||
// a row of lucide icons and invert with the theme.
|
||||
...DOCUMENT_PROVIDER_ICONS,
|
||||
}
|
||||
|
||||
interface Addon {
|
||||
@@ -95,7 +99,7 @@ interface CollabFeatures { chat: boolean; notes: boolean; links?: boolean; polls
|
||||
const COLLAB_SUB_FEATURES = [
|
||||
{ key: 'chat', icon: MessageCircle, titleKey: 'admin.collab.chat.title', subtitleKey: 'admin.collab.chat.subtitle' },
|
||||
{ key: 'notes', icon: StickyNote, titleKey: 'admin.collab.notes.title', subtitleKey: 'admin.collab.notes.subtitle' },
|
||||
{ key: 'links', icon: Link2, titleKey: 'collab.tabs.links', subtitleKey: 'collab.links.empty' },
|
||||
{ key: 'links', icon: Link2, titleKey: 'collab.tabs.links', subtitleKey: 'admin.collab.links.subtitle' },
|
||||
{ key: 'polls', icon: BarChart3, titleKey: 'admin.collab.polls.title', subtitleKey: 'admin.collab.polls.subtitle' },
|
||||
{ key: 'whatsnext', icon: Sparkles, titleKey: 'admin.collab.whatsnext.title', subtitleKey: 'admin.collab.whatsnext.subtitle' },
|
||||
] as const
|
||||
@@ -137,7 +141,9 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
// Journey off disables every photo provider with it, and the response carries
|
||||
// only Journey. Without re-reading, switching Journey back on brings the shelf
|
||||
// up with providers the database has long since turned off.
|
||||
if (addon.id === 'journey') await loadAddons()
|
||||
// Same for Documents: switching it off disables every document provider in
|
||||
// the database, and the response carries only the addon itself.
|
||||
if (addon.id === 'journey' || addon.id === 'documents') await loadAddons()
|
||||
toast.success(t('admin.addons.toast.updated'))
|
||||
}
|
||||
|
||||
@@ -145,12 +151,17 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
return addon.type === 'photo_provider'
|
||||
}
|
||||
|
||||
const isDocumentProviderAddon = (addon: Addon) => {
|
||||
return addon.type === 'document_provider'
|
||||
}
|
||||
|
||||
const isPhotosAddon = (addon: Addon) => {
|
||||
const haystack = `${addon.id} ${addon.name} ${addon.description}`.toLowerCase()
|
||||
return addon.type === 'trip' && (addon.icon === 'Image' || haystack.includes('photo') || haystack.includes('memories'))
|
||||
}
|
||||
|
||||
const photoProviderAddons = addons.filter(isPhotoProviderAddon)
|
||||
const documentProviderAddons = addons.filter(isDocumentProviderAddon)
|
||||
const tripAddons = addons.filter(a => a.type === 'trip' && !isPhotosAddon(a))
|
||||
const globalAddons = addons.filter(a => a.type === 'global')
|
||||
const integrationAddons = addons.filter(a => a.type === 'integration')
|
||||
@@ -161,6 +172,13 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
enabled: provider.enabled,
|
||||
toggle: () => handleToggle(provider),
|
||||
}))
|
||||
const documentProviderOptions: ProviderOption[] = documentProviderAddons.map((provider) => ({
|
||||
key: provider.id,
|
||||
label: provider.name,
|
||||
description: provider.description,
|
||||
enabled: provider.enabled,
|
||||
toggle: () => handleToggle(provider),
|
||||
}))
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -200,6 +218,25 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
)
|
||||
})
|
||||
}
|
||||
// Document providers are the Documents tile's shelf, the way photo providers
|
||||
// are Journey's. Unlike those they carry no credential form here: a document
|
||||
// connection belongs to a trip, not to a user, so it is entered in the trip's
|
||||
// file manager. The admin decides only whether a provider may be offered.
|
||||
if (addon.id === 'documents' && addon.enabled && documentProviderOptions.length > 0) {
|
||||
return documentProviderOptions.map(provider => {
|
||||
const ProviderIcon = PROVIDER_ICONS[provider.key]
|
||||
return (
|
||||
<AddonSubRow
|
||||
key={provider.key}
|
||||
icon={ProviderIcon ? <ProviderIcon size={14} /> : undefined}
|
||||
title={provider.label}
|
||||
description={provider.description}
|
||||
enabled={provider.enabled}
|
||||
onToggle={provider.toggle}
|
||||
/>
|
||||
)
|
||||
})
|
||||
}
|
||||
if (addon.id === 'journey' && addon.enabled && providerOptions.length > 0) {
|
||||
return providerOptions.map(provider => {
|
||||
const ProviderIcon = PROVIDER_ICONS[provider.key]
|
||||
@@ -248,7 +285,7 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
{ key: 'global', addons: globalAddons },
|
||||
{ key: 'integration', addons: integrationAddons },
|
||||
].filter(g => g.addons.length > 0)
|
||||
const enabledCount = addons.filter(a => a.type !== 'photo_provider' && a.enabled).length
|
||||
const enabledCount = addons.filter(a => a.type !== 'photo_provider' && a.type !== 'document_provider' && a.enabled).length
|
||||
const totalCount = tripAddons.length + globalAddons.length + integrationAddons.length
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-W4BGT-001 to FE-W4BGT-022
|
||||
// FE-W4BGT-001 to FE-W4BGT-024
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { screen, act, waitFor } from '@testing-library/react'
|
||||
import { render, fireEvent } from '../../../tests/helpers/render'
|
||||
@@ -276,3 +276,31 @@ describe('BackgroundTasksWidget — AI retry', () => {
|
||||
expect(await screen.findByText('No model configured')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The reporter's phone showed a green tick beside "No reservations could be
|
||||
* extracted" and two warnings (#2477). A parse that found nothing is not a
|
||||
* success, so it wears the warning mark; the tick stays for a parse that did.
|
||||
*/
|
||||
describe('BackgroundTasksWidget: the mark on a finished job (#2477)', () => {
|
||||
it('FE-W4BGT-023: a job that found nothing shows the warning mark, not the success tick', () => {
|
||||
useBackgroundTasksStore.setState({
|
||||
tasks: [task({ items: [], warnings: ['Incomplete LodgingReservation in booking.pdf[0] (no reservationFor)'] })],
|
||||
})
|
||||
const { baseElement } = render(<BackgroundTasksWidget />)
|
||||
|
||||
expect(screen.getByText('No reservations could be extracted from the uploaded files.')).toBeInTheDocument()
|
||||
expect(baseElement.querySelector('svg.lucide-alert-triangle')).toHaveAttribute('stroke', 'var(--warning)')
|
||||
expect(baseElement.querySelector('svg.lucide-check-circle2')).toBeNull()
|
||||
expect(baseElement.querySelector('.animate-spin')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W4BGT-024: a job with items keeps the success tick, even with warnings', () => {
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ items: [{ id: 1 }] as never, warnings: ['could not locate "X"'] })] })
|
||||
const { baseElement } = render(<BackgroundTasksWidget />)
|
||||
|
||||
// The theme's own success colour, so it follows light and dark.
|
||||
expect(baseElement.querySelector('svg.lucide-check-circle2')).toHaveAttribute('stroke', 'var(--success)')
|
||||
expect(baseElement.querySelector('svg.lucide-alert-triangle')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { Loader2, CheckCircle2, AlertCircle, X } from 'lucide-react'
|
||||
import { Loader2, CheckCircle2, AlertCircle, AlertTriangle, X } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { addListener, removeListener } from '../../api/websocket'
|
||||
import { reservationsApi, healthApi } from '../../api/client'
|
||||
@@ -141,8 +141,12 @@ export default function BackgroundTasksWidget() {
|
||||
>
|
||||
<div style={{ flexShrink: 0, marginTop: 1 }}>
|
||||
{(task.status === 'running' || (task.status === 'done' && task.items === undefined)) && <Loader2 size={16} className="animate-spin" color="var(--accent)" />}
|
||||
{task.status === 'done' && task.items !== undefined && <CheckCircle2 size={16} color="#10b981" />}
|
||||
{task.status === 'error' && <AlertCircle size={16} color="#ef4444" />}
|
||||
{task.status === 'done' && task.items !== undefined && task.items.length > 0 && <CheckCircle2 size={16} color="var(--success)" />}
|
||||
{/* A parse that found nothing is not a success, whatever the job
|
||||
status says: the same card used to show a green tick next to
|
||||
"no reservations could be extracted" (#2477). */}
|
||||
{task.status === 'done' && task.items?.length === 0 && <AlertTriangle size={16} color="var(--warning)" />}
|
||||
{task.status === 'error' && <AlertCircle size={16} color="var(--danger)" />}
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
|
||||
@@ -15,6 +15,7 @@ import type { BudgetParticipantFinal } from '@trek/shared'
|
||||
import type { BudgetItem } from '../../types'
|
||||
import CostsPanel, { ExpenseModal } from './CostsPanel'
|
||||
import { splitEqualShares, calculateTicketShares, type TicketItem } from './CostsPanel.helpers'
|
||||
import { resetFreezeAttempts } from './useFreezeMissingRates'
|
||||
|
||||
const tripMembers = [
|
||||
{ id: 1, username: 'alice', avatar_url: null },
|
||||
@@ -744,7 +745,7 @@ describe('CostsPanel — settlements in the ledger', () => {
|
||||
|
||||
type Flow = { from: { user_id: number; username: string }; to: { user_id: number; username: string }; amount: number }
|
||||
type Balance = { user_id: number; username: string; avatar_url: string | null; balance: number }
|
||||
type Payment = { id: number; from_user_id: number; to_user_id: number; amount: number; currency?: string | null; created_at?: string; settled_at?: string | null }
|
||||
type Payment = { id: number; from_user_id: number; to_user_id: number; amount: number; currency?: string | null; exchange_rate?: number; created_at?: string; settled_at?: string | null }
|
||||
|
||||
// `members` here is the wire shape the panel reads; `paid` is only set by the server.
|
||||
type MemberFixture = { user_id: number; username?: string; amount?: number; paid?: number }
|
||||
@@ -875,10 +876,11 @@ describe('CostsPanel — overview', () => {
|
||||
const alice = within(card).getByRole('button', { name: /You/ })
|
||||
await user.click(alice)
|
||||
expect(alice).toHaveAttribute('aria-expanded', 'true')
|
||||
// The dinner is the server's 92 €, once as the line and once as its only row;
|
||||
// the raw 100 USD never shows up in the card.
|
||||
// The dinner is the server's 92 €, once as the line and once as its only row; the
|
||||
// 100 USD is never converted again here. What was entered labels the row (#2525).
|
||||
expect(within(card).getAllByText('+92,00 €')).toHaveLength(2)
|
||||
expect(within(card).queryByText(/100,00/)).toBeNull()
|
||||
expect(within(card).getByText('· $100.00')).toBeInTheDocument()
|
||||
// Received and still pending both lower her cost, each line with its one row.
|
||||
expect(within(card).getAllByText('−15,00 €')).toHaveLength(2)
|
||||
expect(within(card).getAllByText('−16,00 €')).toHaveLength(2)
|
||||
@@ -1185,6 +1187,26 @@ describe('CostsPanel — expense rows', () => {
|
||||
expect(screen.getByText(/\$20\.00 → 10,00 €/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-078: a booked rate outlives the live one, for the expense and for the transfer', async () => {
|
||||
// What a tester hit after settling up: the euro moved, and so did a bill that had
|
||||
// already been paid. A cost is money that changed hands at a rate that was true that
|
||||
// day, so the frozen rate wins over whatever the market says this morning.
|
||||
localStorage.setItem('trek_fx_EUR', JSON.stringify({ rates: { EUR: 1, USD: 2 }, ts: Date.now() }))
|
||||
mount([expense({
|
||||
id: 131, name: 'Diner', category: 'food', total_price: 120, currency: 'USD', exchange_rate: 1.2,
|
||||
expense_date: '2025-06-15',
|
||||
payers: [{ user_id: 1, amount: 120 }],
|
||||
members: [{ user_id: 1, username: 'alice' }, { user_id: 2, username: 'bob' }],
|
||||
})], { settlements: [{ id: 9, from_user_id: 2, to_user_id: 1, amount: 24, currency: 'USD', exchange_rate: 1.2, created_at: '2025-06-15 09:00:00' }] })
|
||||
|
||||
await screen.findByText('Diner')
|
||||
// 120 USD at the booked 1.2 per euro is 100 euro. At today's 2 it would read 60,00 euro.
|
||||
expect(screen.getByText(/\$120\.00 → 100,00 €/)).toBeInTheDocument()
|
||||
expect(screen.queryByText(/60,00 €/)).toBeNull()
|
||||
// The settled transfer is read back the same way: 24 USD booked at 1.2 is 20 euro.
|
||||
expect(screen.getByText(/\$24\.00 → 20,00 €/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-022: deleting an expense removes it, and a failure is reported', async () => {
|
||||
const addToast = vi.fn()
|
||||
window.__addToast = addToast as unknown as typeof window.__addToast
|
||||
@@ -2273,3 +2295,390 @@ describe('CostsPanel — expense modal in another language', () => {
|
||||
expect(screen.queryByText('Excluded')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
// ── #2525: a bill entered in the display currency on a trip kept in another ───
|
||||
describe('CostsPanel: a bill entered in the display currency (#2525)', () => {
|
||||
// The reporter's setup: a euro trip, read in dollars, with the bill entered in
|
||||
// dollars. It was booked at 1.17 dollars to the euro, 685.26 EUR, and that is what
|
||||
// the balances and settle-up net. Today the euro buys 1.1551 dollars, so those
|
||||
// euros are $791.55. The dollar's own quote is rounded separately (0.865706 per
|
||||
// dollar is 1.155126 per euro), which is why the panel converts with the euro's.
|
||||
beforeEach(() => {
|
||||
seedAlice()
|
||||
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'USD' } })
|
||||
clearExchangeRateCache()
|
||||
localStorage.setItem('trek_fx_USD', JSON.stringify({ rates: { USD: 1, EUR: 0.865706 }, ts: Date.now() }))
|
||||
localStorage.setItem('trek_fx_EUR', JSON.stringify({ rates: { EUR: 1, USD: 1.1551, SEK: 10 }, ts: Date.now() }))
|
||||
})
|
||||
afterEach(clearExchangeRateCache)
|
||||
|
||||
const hotel = (over: Partial<BudgetItem> = {}) => expense({
|
||||
id: 401, name: 'Aparthotel Silver', category: 'accommodation', total_price: 801.76, currency: 'USD', exchange_rate: 1.17,
|
||||
expense_date: '2026-08-06',
|
||||
payers: [{ user_id: 1, amount: 801.76 }],
|
||||
members: [{ user_id: 1, username: 'alice' }, { user_id: 2, username: 'bob' }],
|
||||
...over,
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-079: a bill whose rate moved shows what was entered and what it was booked at', async () => {
|
||||
mount([hotel()])
|
||||
|
||||
await screen.findByText('Aparthotel Silver')
|
||||
// The entered amount was nowhere on the row, so $791.57 read as a wrong copy of
|
||||
// the 801.76 in the dialog. The pill beside the line is the last step.
|
||||
expect(screen.getByText(/^\$801\.76 → 685,26\s€$/)).toBeInTheDocument()
|
||||
// Row total and payer chip stay the booked euros at today's rate, and so does what
|
||||
// I lent: half of 685.26 EUR, the figure settle-up offers. Printing $400.88 here
|
||||
// had Bob pay back more than he owed and reopened the trip.
|
||||
expect(screen.getAllByText('$791.55')).toHaveLength(2)
|
||||
expect(screen.getByText('you lent $395.77')).toBeInTheDocument()
|
||||
expect(screen.queryByText('you lent $400.88')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-087: a bill booked at today\'s rate reads exactly as typed everywhere on the page', async () => {
|
||||
mount([
|
||||
hotel({ id: 407, name: 'Villa', total_price: 12345.67, exchange_rate: 1.1551, payers: [{ user_id: 1, amount: 12345.67 }] }),
|
||||
hotel({ id: 408, name: 'Unpaid deposit', total_price: 250, exchange_rate: 1.1551, payers: [], members: [] }),
|
||||
])
|
||||
|
||||
await screen.findByText('Villa')
|
||||
// Pill and payer chip; converting back with the dollar's own quote gave $12,346.05.
|
||||
expect(screen.getAllByText('$12,345.67')).toHaveLength(2)
|
||||
expect(screen.queryByText(/12,346\.0[56]/)).toBeNull()
|
||||
expect(screen.getByText('$12,595.67 spent')).toBeInTheDocument()
|
||||
const total = screen.getByText('Total trip spend').parentElement!.parentElement!.parentElement!
|
||||
expect(total.textContent).toContain('$12,595.67')
|
||||
const outstanding = screen.getByText('Outstanding amount').parentElement!.parentElement!.parentElement!
|
||||
expect(outstanding.textContent).toContain('$250.00')
|
||||
// Nothing to explain under either row.
|
||||
expect(screen.queryByText(/^\$12,345\.67 →/)).toBeNull()
|
||||
expect(screen.queryByText(/^\$250\.00 →/)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-088: the CSV export adds the trip-currency amount every sum is built from', async () => {
|
||||
let exported: Blob | null = null
|
||||
const createObjURL = vi.spyOn(URL, 'createObjectURL').mockImplementation(b => { exported = b as Blob; return 'blob:mock' })
|
||||
const revokeObjURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
|
||||
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||||
try {
|
||||
mount([hotel()])
|
||||
await screen.findByText('Aparthotel Silver')
|
||||
fireEvent.click(screen.getByTitle('Export CSV'))
|
||||
await waitFor(() => expect(exported).toBeTruthy())
|
||||
const lines = (await exported!.text()).replace(/^\uFEFF/, '').split('\r\n')
|
||||
expect(lines[0]).toBe('Date;Name;Category;Amount;Currency;Amount (EUR);Amount (USD);Note')
|
||||
expect(lines[1]).toMatch(/;801\.76;USD;685\.26;791\.55;$/)
|
||||
} finally {
|
||||
createObjURL.mockRestore(); revokeObjURL.mockRestore(); clickSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-080: the totals add up the figures the rows show', async () => {
|
||||
mount([
|
||||
hotel(),
|
||||
hotel({ id: 402, name: 'Dinner', category: 'food', total_price: 120, payers: [{ user_id: 2, amount: 120 }] }),
|
||||
])
|
||||
|
||||
await screen.findByText('Aparthotel Silver')
|
||||
// 120 USD at 1.17 is 102.56 EUR, $118.47 today; with the hotel's $791.55 that is
|
||||
// $910.02, on the day header and on the total spend card.
|
||||
expect(screen.getByText(/^\$120\.00 → 102,56\s€$/)).toBeInTheDocument()
|
||||
expect(screen.getByText('$910.02 spent')).toBeInTheDocument()
|
||||
// Label, its text block, the header row, then the card itself.
|
||||
const card = screen.getByText('Total trip spend').parentElement!.parentElement!.parentElement!
|
||||
expect(card.textContent).toContain('$910.02')
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-084: the totals follow the rates when they arrive after the expenses', async () => {
|
||||
// Nothing cached: the rates land after the expenses and the settlement, and the
|
||||
// totals used to keep the figure they were first added up with.
|
||||
clearExchangeRateCache()
|
||||
server.use(http.get('https://api.frankfurter.dev/v2/rates', async () => {
|
||||
await new Promise(r => setTimeout(r, 150))
|
||||
return HttpResponse.json([{ quote: 'EUR', rate: 0.8 }])
|
||||
}))
|
||||
mount([hotel({ id: 406, name: 'Museum', category: 'activities', total_price: 100, currency: 'EUR', exchange_rate: 1, payers: [{ user_id: 1, amount: 100 }] })])
|
||||
|
||||
// 100 euro at 0.8 euro to the dollar.
|
||||
expect(await screen.findByText(/100,00\s€ → \$125\.00/)).toBeInTheDocument()
|
||||
const card = screen.getByText('Total trip spend').parentElement!.parentElement!.parentElement!
|
||||
await waitFor(() => expect(card.textContent).toContain('$125.00'))
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-081: a euro row converts live, a third currency shows the euros it was booked at', async () => {
|
||||
mount([
|
||||
hotel({ id: 403, name: 'Museum', category: 'activities', total_price: 100, currency: 'EUR', exchange_rate: 1, payers: [{ user_id: 1, amount: 100 }] }),
|
||||
hotel({ id: 404, name: 'Ferry', category: 'transport', total_price: 1000, currency: 'SEK', exchange_rate: 10, payers: [{ user_id: 1, amount: 1000 }] }),
|
||||
// Written before the freeze existed: nothing was booked, so dollars stay dollars.
|
||||
hotel({ id: 405, name: 'Old taxi', category: 'transport', total_price: 50, currency: 'USD', exchange_rate: 1, payers: [{ user_id: 1, amount: 50 }] }),
|
||||
])
|
||||
|
||||
await screen.findByText('Museum')
|
||||
// The trip currency has no frozen rate of its own and goes to dollars live.
|
||||
expect(screen.getByText(/^100,00\s€ → \$115\.51$/)).toBeInTheDocument()
|
||||
// 1000 SEK at 10 per euro is 100 euro, then live to dollars in the pill.
|
||||
expect(screen.getByText(/^1\s000,00\skr → 100,00\s€$/)).toBeInTheDocument()
|
||||
expect(screen.getAllByText('$50.00').length).toBeGreaterThanOrEqual(2)
|
||||
expect(screen.queryByText(/^\$50\.00 →/)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-082: a payment recorded in dollars is booked like an expense, a legacy one stays as entered', async () => {
|
||||
mount([hotel()], {
|
||||
settlements: [
|
||||
{ id: 21, from_user_id: 2, to_user_id: 1, amount: 400.88, currency: 'USD', exchange_rate: 1.17, created_at: '2026-08-07 09:00:00' },
|
||||
// Rows from before transfers had a currency were entered in the display
|
||||
// currency, which is how the server settles them.
|
||||
{ id: 22, from_user_id: 2, to_user_id: 1, amount: 30, currency: null, created_at: '2026-08-08 09:00:00' },
|
||||
],
|
||||
})
|
||||
|
||||
await screen.findByText('Aparthotel Silver')
|
||||
expect(screen.getByText(/\$400\.88 → 342,63\s€$/)).toBeInTheDocument()
|
||||
expect(screen.getByText('$395.77')).toBeInTheDocument()
|
||||
expect(screen.getByText('$30.00')).toBeInTheDocument()
|
||||
expect(screen.queryByText('$34.65')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-085: the edit dialog previews the rate the save keeps, the one the row was booked at', async () => {
|
||||
const user = userEvent.setup()
|
||||
mount([hotel()])
|
||||
|
||||
await screen.findByText('Aparthotel Silver')
|
||||
await user.click(screen.getByTitle('Edit'))
|
||||
expect(await screen.findByDisplayValue('801.76')).toBeInTheDocument()
|
||||
// Same currency as the list, so the dialog said nothing, and 801.76 there beside
|
||||
// $791.57 in the list looked like two different expenses.
|
||||
const hint = screen.getByText(/live rate/).parentElement as HTMLElement
|
||||
expect(within(hint).getByText('$801.76')).toBeInTheDocument()
|
||||
expect(within(hint).getByText(/^685,26\s€$/)).toBeInTheDocument()
|
||||
expect(within(hint).getByText('$791.55')).toBeInTheDocument()
|
||||
// Each share next to what it counts as, the figure the row's "you lent" is made of.
|
||||
expect(screen.getByText(/Split 2 ways · \$400\.88 → \$395\.77 each/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-086: the final budget names the bill by what was entered beside its booked figure', async () => {
|
||||
const user = userEvent.setup()
|
||||
mount([hotel()], {
|
||||
balances: [
|
||||
{ user_id: 1, username: 'alice', avatar_url: null, balance: 395.78 },
|
||||
{ user_id: 2, username: 'bob', avatar_url: null, balance: -395.78 },
|
||||
],
|
||||
flows: [{ from: { user_id: 2, username: 'bob' }, to: { user_id: 1, username: 'alice' }, amount: 395.78 }],
|
||||
finalBudgets: [
|
||||
{
|
||||
user_id: 1, username: 'alice', avatar_url: null, expenses: 791.55, reimbursed: 0, pending: 395.78, final: 395.77,
|
||||
sources: { fronted: [{ item_id: 401, cents: 79155 }], moved: [], outstanding: [{ from_user_id: 2, to_user_id: 1, cents: 39578 }] },
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const card = (await screen.findByText('Final budget')).parentElement as HTMLElement
|
||||
await user.click(await within(card).findByRole('button', { name: /You/ }))
|
||||
expect(within(card).getAllByText('+$791.55')).toHaveLength(2)
|
||||
expect(within(card).getByText('Aparthotel Silver')).toBeInTheDocument()
|
||||
expect(within(card).getByText('· $801.76')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-089: the final budget lists a bill that reads as typed without a second amount', async () => {
|
||||
const user = userEvent.setup()
|
||||
mount([hotel({ exchange_rate: 1.1551 })], {
|
||||
balances: [
|
||||
{ user_id: 1, username: 'alice', avatar_url: null, balance: 400.88 },
|
||||
{ user_id: 2, username: 'bob', avatar_url: null, balance: -400.88 },
|
||||
],
|
||||
flows: [{ from: { user_id: 2, username: 'bob' }, to: { user_id: 1, username: 'alice' }, amount: 400.88 }],
|
||||
finalBudgets: [
|
||||
{
|
||||
user_id: 1, username: 'alice', avatar_url: null, expenses: 801.76, reimbursed: 0, pending: 400.88, final: 400.88,
|
||||
sources: { fronted: [{ item_id: 401, cents: 80176 }], moved: [], outstanding: [{ from_user_id: 2, to_user_id: 1, cents: 40088 }] },
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const card = (await screen.findByText('Final budget')).parentElement as HTMLElement
|
||||
await user.click(await within(card).findByRole('button', { name: /You/ }))
|
||||
expect(within(card).getAllByText('+$801.76')).toHaveLength(2)
|
||||
expect(within(card).queryByText('· $801.76')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-083: an expense saved without a currency opens in the trip currency, not the display one', async () => {
|
||||
const user = userEvent.setup()
|
||||
let put: Record<string, unknown> | null = null
|
||||
server.use(http.put('/api/trips/1/budget/405', async ({ request }) => {
|
||||
put = await request.json() as Record<string, unknown>
|
||||
return HttpResponse.json({ item: hotel({ id: 405, currency: 'EUR' }) })
|
||||
}))
|
||||
mount([hotel({ id: 405, name: 'Tram pass', category: 'transport', total_price: 100, currency: null, exchange_rate: 1, payers: [{ user_id: 1, amount: 100 }] })])
|
||||
|
||||
await screen.findByText('Tram pass')
|
||||
// The list reads the missing currency as the trip's own.
|
||||
expect(screen.getByText(/100,00\s€ → \$115\.51/)).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByTitle('Edit'))
|
||||
expect(await screen.findByDisplayValue('100,00')).toBeInTheDocument()
|
||||
// Seeding the display currency here would label 100 euro as 100 dollars, and a
|
||||
// plain save would then store it that way.
|
||||
expect(screen.getByText(/^EUR/)).toBeInTheDocument()
|
||||
expect(screen.queryByText(/^USD/)).toBeNull()
|
||||
|
||||
// Saving without touching anything keeps the 100 euro.
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(put).toMatchObject({ total_price: 100, currency: 'EUR' }))
|
||||
})
|
||||
})
|
||||
|
||||
// ── A bill the server cannot convert: VND on an AUD trip ────────────────────────
|
||||
describe('CostsPanel: a bill the server cannot convert', () => {
|
||||
// The reporter's setup: an AUD trip whose server cannot fetch rates while the browser
|
||||
// can. An 8,920,000 VND dinner that never froze a rate was counted as 8,920,000 AUD.
|
||||
// The settlement now leaves it out and lists it, and an editor's browser lends its AUD
|
||||
// table to freeze a rate on it.
|
||||
const pho = () => expense({
|
||||
id: 501, name: 'Pho', category: 'food', total_price: 8920000, currency: 'VND', exchange_rate: 1,
|
||||
expense_date: '2026-09-20',
|
||||
payers: [{ user_id: 1, amount: 8920000 }],
|
||||
members: [{ user_id: 1, username: 'alice' }, { user_id: 2, username: 'bob' }],
|
||||
})
|
||||
const leftOut = { balances: [], flows: [], settlements: [], currency: 'AUD', unconverted: { item_ids: [501], settlement_ids: [], currencies: ['VND'] } }
|
||||
|
||||
beforeEach(() => {
|
||||
seedAlice()
|
||||
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'AUD' } })
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'AUD' }) })
|
||||
clearExchangeRateCache()
|
||||
resetFreezeAttempts()
|
||||
localStorage.setItem('trek_fx_AUD', JSON.stringify({ rates: { AUD: 1, VND: 18241.3, EUR: 0.61 }, ts: Date.now() }))
|
||||
})
|
||||
afterEach(clearExchangeRateCache)
|
||||
|
||||
it('FE-W5COSTS-090: VND/AUD regression: an editor heals the bill with the cached quote and the healed balances load', async () => {
|
||||
let healed = false
|
||||
const frozen: unknown[] = []
|
||||
server.use(
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [pho()] })),
|
||||
http.get('/api/trips/1/budget/settlement', () => HttpResponse.json(healed
|
||||
? {
|
||||
// 8,920,000 VND at 18,241.3 is 489.00 AUD, half of it Bob's.
|
||||
balances: [
|
||||
{ user_id: 1, username: 'alice', avatar_url: null, balance: 244.5 },
|
||||
{ user_id: 2, username: 'bob', avatar_url: null, balance: -244.5 },
|
||||
],
|
||||
flows: [{ from: { user_id: 2, username: 'bob' }, to: { user_id: 1, username: 'alice' }, amount: 244.5 }],
|
||||
settlements: [],
|
||||
currency: 'AUD',
|
||||
unconverted: { item_ids: [], settlement_ids: [], currencies: [] },
|
||||
}
|
||||
: leftOut)),
|
||||
http.post('/api/trips/1/budget/freeze-rates', async ({ request }) => {
|
||||
frozen.push(await request.json())
|
||||
healed = true
|
||||
return HttpResponse.json({ items: [{ ...pho(), exchange_rate: 18241.3 }], settlements: [], unresolved: [] })
|
||||
}),
|
||||
)
|
||||
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
|
||||
|
||||
// Only the currency the settlement is missing, at the rate the browser holds.
|
||||
await waitFor(() => expect(frozen).toEqual([{ fallback_fx: { base: 'AUD', rates: { VND: 18241.3 } } }]))
|
||||
// The settlement is read again and Bob's half can be settled.
|
||||
expect(await screen.findByRole('button', { name: 'Settle' })).toBeInTheDocument()
|
||||
expect(screen.getAllByText(/244\.50/).length).toBeGreaterThan(0)
|
||||
// Nothing on the page counts the bill as 8,920,000 dollars any more.
|
||||
expect(screen.queryByText(/\$8,920,000/)).toBeNull()
|
||||
expect(frozen).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-091: a viewer\'s browser never freezes anything', async () => {
|
||||
seedStore(usePermissionsStore, { permissions: { budget_edit: 'admin' } })
|
||||
let frozen = 0
|
||||
server.use(http.post('/api/trips/1/budget/freeze-rates', () => {
|
||||
frozen += 1
|
||||
return HttpResponse.json({ items: [], settlements: [], unresolved: [] })
|
||||
}))
|
||||
mount([pho()], leftOut)
|
||||
|
||||
await screen.findByText('Pho')
|
||||
await new Promise(r => setTimeout(r, 50))
|
||||
expect(frozen).toBe(0)
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-092: settle-up in the display currency lends its rate and asks the settlement in it', async () => {
|
||||
// Read in euros: the browser has the AUD table, the server has no quote at all.
|
||||
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'EUR' } })
|
||||
const asked: { base: string | null; baseRate: string | null }[] = []
|
||||
const posted: Record<string, unknown>[] = []
|
||||
server.use(
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] })),
|
||||
http.get('/api/trips/1/budget/settlement', ({ request }) => {
|
||||
const url = new URL(request.url)
|
||||
asked.push({ base: url.searchParams.get('base'), baseRate: url.searchParams.get('base_rate') })
|
||||
return HttpResponse.json({
|
||||
balances: [], settlements: [], currency: 'EUR', unconverted: { item_ids: [], settlement_ids: [], currencies: [] },
|
||||
flows: [{ from: { user_id: 2, username: 'bob' }, to: { user_id: 1, username: 'alice' }, amount: 20 }],
|
||||
})
|
||||
}),
|
||||
http.post('/api/trips/1/budget/settlements', async ({ request }) => {
|
||||
posted.push(await request.json() as Record<string, unknown>)
|
||||
return HttpResponse.json({ settlement: { id: 1 } })
|
||||
}),
|
||||
)
|
||||
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Settle' }))
|
||||
await waitFor(() => expect(posted).toHaveLength(1))
|
||||
// The transfer freezes at the rate the settlement was labelled with, so it cancels its
|
||||
// flow to the cent.
|
||||
expect(posted[0]).toMatchObject({ from_user_id: 2, to_user_id: 1, amount: 20, currency: 'EUR', fallback_fx: { base: 'AUD', rates: { EUR: 0.61 } } })
|
||||
expect(asked.length).toBeGreaterThan(0)
|
||||
expect(asked.every(a => a.base === 'EUR' && a.baseRate === '0.61')).toBe(true)
|
||||
|
||||
const settleAll = screen.getByRole('button', { name: 'Settle up' })
|
||||
fireEvent.click(settleAll)
|
||||
await waitFor(() => expect(posted).toHaveLength(2))
|
||||
expect(posted[1]).toMatchObject({ amount: 20, currency: 'EUR', fallback_fx: { base: 'AUD', rates: { EUR: 0.61 } } })
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-093: a payment added by hand lends the rate for its currency too', async () => {
|
||||
const user = userEvent.setup()
|
||||
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'EUR' } })
|
||||
let posted: Record<string, unknown> | null = null
|
||||
server.use(http.post('/api/trips/1/budget/settlements', async ({ request }) => {
|
||||
posted = await request.json() as Record<string, unknown>
|
||||
return HttpResponse.json({ settlement: { id: 1 } })
|
||||
}))
|
||||
mount([])
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Add payment' }))
|
||||
await user.type(await screen.findByPlaceholderText('0.00'), '25')
|
||||
const submits = screen.getAllByRole('button', { name: 'Add payment' })
|
||||
await user.click(submits[submits.length - 1])
|
||||
|
||||
await waitFor(() => expect(posted).toBeTruthy())
|
||||
expect(posted).toMatchObject({ amount: 25, currency: 'EUR', fallback_fx: { base: 'AUD', rates: { EUR: 0.61 } } })
|
||||
})
|
||||
|
||||
it('FE-W5COSTS-094: a display rate the settlement query would refuse is not sent', async () => {
|
||||
// A trip in gold read in rials: 2.6 billion rials to the ounce is past the 1e9 the query
|
||||
// takes, and sent as `base_rate` it would fail the whole settlement with a 400.
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1, currency: 'XAU' }) })
|
||||
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'IRR' } })
|
||||
localStorage.setItem('trek_fx_XAU', JSON.stringify({ rates: { XAU: 1, IRR: 2.6e9 }, ts: Date.now() }))
|
||||
localStorage.setItem('trek_fx_IRR', JSON.stringify({ rates: { IRR: 1, XAU: 1 / 2.6e9 }, ts: Date.now() }))
|
||||
const asked: { base: string | null; baseRate: string | null }[] = []
|
||||
server.use(
|
||||
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [] })),
|
||||
http.get('/api/trips/1/budget/settlement', ({ request }) => {
|
||||
const url = new URL(request.url)
|
||||
asked.push({ base: url.searchParams.get('base'), baseRate: url.searchParams.get('base_rate') })
|
||||
return HttpResponse.json({
|
||||
balances: [], flows: [], settlements: [], currency: 'XAU', unconverted: { item_ids: [], settlement_ids: [], currencies: [] },
|
||||
})
|
||||
}),
|
||||
)
|
||||
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
|
||||
|
||||
await waitFor(() => expect(asked.length).toBeGreaterThan(0))
|
||||
// Still asked in rials, only without the figure; the server answers in the trip
|
||||
// currency when it has no quote of its own.
|
||||
expect(asked.every(a => a.base === 'IRR' && a.baseRate === null)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -9,7 +9,9 @@ import { useToast } from '../shared/Toast'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { budgetApi } from '../../api/client'
|
||||
import { saveWithReceipts } from './receiptUploads'
|
||||
import { useExchangeRates } from '../../hooks/useExchangeRates'
|
||||
import { convertBooked, convertedLine, tripAmountOf, useExchangeRates, withFallbackFx } from '../../hooks/useExchangeRates'
|
||||
import { splitShareLabel, useExpenseFx } from './expenseFx'
|
||||
import { useFreezeMissingRates } from './useFreezeMissingRates'
|
||||
import { useIsMobile } from '../../hooks/useIsMobile'
|
||||
import { formatMoney, currencyDecimals, currencyLocale, localizeAmountInput, amountToInputString } from '../../utils/formatters'
|
||||
import { downloadBlob, openFile } from '../../utils/fileDownload'
|
||||
@@ -21,7 +23,7 @@ import { SYMBOLS, currenciesWith, SPLIT_COLORS } from './BudgetPanel.constants'
|
||||
import { amountPattern, calculateTicketShares, finalBudgetFor, finalBudgetSources, hasTicketSplit, NOTE_MAX, paidByUser, payersBalanced, readTicketItems, readUserNote, rebalancePayers, settlementDate, splitEqualShares, writeTicketItems, type TicketItem } from './CostsPanel.helpers'
|
||||
import { COST_CATEGORY_LIST, catMeta } from './costsCategories'
|
||||
import { ReceiptPreviewModal } from './ReceiptPreviewModal'
|
||||
import type { BudgetParticipantFinal } from '@trek/shared'
|
||||
import type { BudgetParticipantFinal, BudgetUnconverted } from '@trek/shared'
|
||||
import type { BudgetItem, BudgetItemReceipt } from '../../types'
|
||||
import type { TripMember } from './BudgetPanelMemberChips'
|
||||
import GuestBadge from '../shared/GuestBadge'
|
||||
@@ -41,6 +43,9 @@ interface Settlement {
|
||||
// The currency the transfer was entered in. Legacy rows predate it (null) and are
|
||||
// read as the display currency, which is what the server assumes for them too.
|
||||
currency?: string | null
|
||||
// The rate frozen when the transfer was settled, in units of `currency` per 1 trip
|
||||
// currency (#1445). Absent, or exactly 1, on rows written before the freeze existed.
|
||||
exchange_rate?: number
|
||||
created_at?: string
|
||||
// The day the transfer actually happened; editable, unlike created_at (when it
|
||||
// was recorded). Null/absent on rows predating this field — settlementDate()
|
||||
@@ -56,6 +61,11 @@ interface SettlementData {
|
||||
// What the trip ends up costing each participant. Computed server-side off the
|
||||
// same ledger as the balances, so the breakdown can't contradict them.
|
||||
finalBudgets: BudgetParticipantFinal[]
|
||||
// The currency the figures are in: the display currency, or the trip's own when
|
||||
// neither the server nor `base_rate` could quote the pair.
|
||||
currency?: string
|
||||
// Rows no rate could convert, left out of every figure above.
|
||||
unconverted?: BudgetUnconverted
|
||||
}
|
||||
|
||||
// One row in the unified Costs ledger — either an expense or a settle-up payment,
|
||||
@@ -82,7 +92,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const base = (displayCurrency || trip?.currency || 'EUR').toUpperCase()
|
||||
// Pre-rework rows stored currency = NULL, meaning "the trip's own currency".
|
||||
const tripCurrency = (trip?.currency || base).toUpperCase()
|
||||
const { convert } = useExchangeRates(base)
|
||||
// Anchored on the trip currency's quote, the one the server books with (#2525).
|
||||
const { convert, displayPerTrip } = useExchangeRates(base, tripCurrency)
|
||||
const curOf = useCallback((e: BudgetItem) => (e.currency || tripCurrency), [tripCurrency])
|
||||
const [settlement, setSettlement] = useState<SettlementData | null>(null)
|
||||
// A failed settlement read leaves `settlement` null, which the empty views would
|
||||
@@ -116,14 +127,20 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const fmt = useCallback((v: number, c = base) => formatMoney(v, c, locale), [base, locale])
|
||||
const fmt0 = useCallback((v: number, c = base) => formatMoney(v, c, locale, { decimals: 0 }), [base, locale])
|
||||
|
||||
// The browser's own figure for the display currency goes along, for the server to
|
||||
// answer in it when it cannot fetch a quote itself.
|
||||
const loadSettlement = useCallback(() => {
|
||||
budgetApi.settlement(tripId, base)
|
||||
budgetApi.settlement(tripId, base, base !== tripCurrency ? displayPerTrip : null)
|
||||
.then(s => { setSettlement(s); setSettlementError(false) })
|
||||
.catch(() => setSettlementError(true))
|
||||
}, [tripId, base])
|
||||
}, [tripId, base, tripCurrency, displayPerTrip])
|
||||
|
||||
useEffect(() => { loadBudgetItems(tripId); loadSettlement() }, [tripId])
|
||||
useEffect(() => { loadSettlement() }, [budgetItems.length, base])
|
||||
useEffect(() => { loadSettlement() }, [budgetItems.length, loadSettlement])
|
||||
|
||||
// Rows the server could not count get a rate frozen from the browser's, and the
|
||||
// settlement is read again once they count.
|
||||
useFreezeMissingRates({ tripId, tripCurrency, canEdit, unconverted: settlement?.unconverted, onHealed: loadSettlement })
|
||||
|
||||
// The bottom-nav "+" on the Costs tab opens the add-expense modal via ?create=expense.
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
@@ -135,8 +152,24 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
}, [searchParams])
|
||||
|
||||
// ── derived expense maths (everything converted to the base currency) ────
|
||||
const baseTotal = (e: BudgetItem) => convert(e.total_price || 0, curOf(e))
|
||||
const myPaidOf = (e: BudgetItem) => convert(paidByUser(e, me), curOf(e))
|
||||
// Booked, not live: an expense entered in a foreign currency keeps the rate it was
|
||||
// entered at, which is the same rule the server settles by (#1335).
|
||||
const booked = useCallback(
|
||||
(amount: number, e: BudgetItem) => convertBooked(amount, e.currency, e.exchange_rate, tripCurrency, convert),
|
||||
[convert, tripCurrency],
|
||||
)
|
||||
const baseTotal = (e: BudgetItem) => booked(e.total_price || 0, e)
|
||||
// A transfer freezes its own rate at settle time, in its own table (#1445). One
|
||||
// without a currency predates that and was entered in the display currency, which
|
||||
// is how the server settles it too, not in the trip's.
|
||||
const settled = useCallback(
|
||||
(s: Settlement) => convertBooked(s.amount, s.currency || base, s.exchange_rate, tripCurrency, convert),
|
||||
[convert, tripCurrency, base],
|
||||
)
|
||||
const myPaidOf = (e: BudgetItem) => booked(paidByUser(e, me), e)
|
||||
// The line under an amount shown converted: what was entered, then where it went (#2525).
|
||||
const lineOf = (amount: number, e: BudgetItem, shown: number) =>
|
||||
convertedLine(amount, e.currency, e.exchange_rate, tripCurrency, base, shown)
|
||||
// "Unfinished": a recorded total nobody has paid yet — counts toward the trip
|
||||
// total but stays out of settlements until who-paid is filled in. A negative
|
||||
// total (a refund, #2176) is just as unfinished until its recipient is named.
|
||||
@@ -148,13 +181,15 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const myMember = (e.members || []).find(m => m.user_id === me)
|
||||
if (!myMember) return 0
|
||||
if (myMember.amount !== null && myMember.amount !== undefined) {
|
||||
return convert(myMember.amount, curOf(e))
|
||||
return booked(myMember.amount, e)
|
||||
}
|
||||
const shares = splitEqualShares(e.total_price || 0, e.members || [], e.id)
|
||||
const myShare = shares[me] || 0
|
||||
return convert(myShare, curOf(e))
|
||||
return booked(myShare, e)
|
||||
}
|
||||
|
||||
// `booked` carries the rates. They can land after the expenses, and without it in the
|
||||
// deps the cards kept the sums they were first added up with while the rows moved on.
|
||||
const totals = useMemo(() => {
|
||||
const totalSpend = budgetItems.reduce((a, e) => a + baseTotal(e), 0)
|
||||
const myPaid = budgetItems.reduce((a, e) => a + myPaidOf(e), 0)
|
||||
@@ -164,7 +199,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const outstanding = budgetItems.reduce((a, e) => (isUnfinished(e) ? a + baseTotal(e) : a), 0)
|
||||
const outstandingCount = budgetItems.filter(isUnfinished).length
|
||||
return { totalSpend, myPaid, myShare, owe, owed, outstanding, outstandingCount }
|
||||
}, [budgetItems, settlement, me])
|
||||
}, [budgetItems, settlement, me, booked])
|
||||
|
||||
// ── filtering + day grouping ────────────────────────────────────────────
|
||||
const filtered = useMemo(() => {
|
||||
@@ -178,7 +213,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const q = search.trim().toLowerCase()
|
||||
if (q) list = list.filter(e => e.name.toLowerCase().includes(q))
|
||||
return list
|
||||
}, [budgetItems, filter, search, catFilter, dayFilter, me])
|
||||
}, [budgetItems, filter, search, catFilter, dayFilter, me, booked])
|
||||
|
||||
// Settlements ("payments") shown inline in the ledger. They have no name, so a
|
||||
// text search hides them; they're excluded from the "owed" expense filter and,
|
||||
@@ -231,7 +266,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
// ── settle actions ──────────────────────────────────────────────────────
|
||||
const settleFlow = async (fromId: number, toId: number, amount: number) => {
|
||||
try {
|
||||
await budgetApi.createSettlement(tripId, { from_user_id: fromId, to_user_id: toId, amount, currency: base })
|
||||
await budgetApi.createSettlement(tripId, withFallbackFx({ from_user_id: fromId, to_user_id: toId, amount, currency: base }, tripCurrency))
|
||||
loadSettlement()
|
||||
} catch { toast.error(t('common.unknownError')) }
|
||||
}
|
||||
@@ -242,7 +277,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
const flows = settlement?.flows || []
|
||||
if (!flows.length) return
|
||||
try {
|
||||
for (const f of flows) await budgetApi.createSettlement(tripId, { from_user_id: f.from.user_id, to_user_id: f.to.user_id, amount: f.amount, currency: base })
|
||||
for (const f of flows) await budgetApi.createSettlement(tripId, withFallbackFx({ from_user_id: f.from.user_id, to_user_id: f.to.user_id, amount: f.amount, currency: base }, tripCurrency))
|
||||
} catch { toast.error(t('common.unknownError')) }
|
||||
// Refresh even when one transfer failed: the ones created before it are real,
|
||||
// and leaving them in the flow list invites a second, doubled settle-up.
|
||||
@@ -276,15 +311,20 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
}
|
||||
const fmtDate = (iso: string) => { if (!iso) return ''; try { return new Date(iso + 'T00:00:00Z').toLocaleDateString(locale, { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' }) } catch { return iso } }
|
||||
|
||||
const header = ['Date', 'Name', 'Category', 'Amount', 'Currency', 'Amount (' + base + ')', 'Note']
|
||||
// Read in another currency than the trip's, what each row counts as in the trip
|
||||
// currency too, the figure every sum is built from (#2525).
|
||||
const tripCol = tripCurrency !== base
|
||||
const header = ['Date', 'Name', 'Category', 'Amount', 'Currency', ...(tripCol ? ['Amount (' + tripCurrency + ')'] : []), 'Amount (' + base + ')', 'Note']
|
||||
const rows = [header.join(sep)]
|
||||
const items = budgetItems.slice().sort((a, b) => (a.expense_date || '').localeCompare(b.expense_date || ''))
|
||||
for (const e of items) {
|
||||
const cur = curOf(e)
|
||||
const note = readUserNote(e)
|
||||
const inTrip = tripAmountOf(e.total_price || 0, e.currency, e.exchange_rate, tripCurrency, convert)
|
||||
rows.push([
|
||||
esc(fmtDate(e.expense_date || '')), esc(e.name), esc(t(catMeta(e.category).labelKey)),
|
||||
(e.total_price || 0).toFixed(currencyDecimals(cur)), cur,
|
||||
...(tripCol ? [inTrip.toFixed(currencyDecimals(tripCurrency))] : []),
|
||||
baseTotal(e).toFixed(currencyDecimals(base)),
|
||||
esc(note),
|
||||
].join(sep))
|
||||
@@ -507,7 +547,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
)}
|
||||
|
||||
{(editingSettlement || addingPayment) && (
|
||||
<SettlementModal tripId={tripId} people={people} me={me} editing={editingSettlement} currency={base}
|
||||
<SettlementModal tripId={tripId} people={people} me={me} editing={editingSettlement} currency={base} tripCurrency={tripCurrency}
|
||||
onClose={() => { setEditingSettlement(null); setAddingPayment(false) }}
|
||||
onSaved={() => { setEditingSettlement(null); setAddingPayment(false); loadSettlement() }} />
|
||||
)}
|
||||
@@ -754,7 +794,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
function ExpenseRow({ e }: { e: BudgetItem }) {
|
||||
const c = catMeta(e.category)
|
||||
const Icon = c.Icon
|
||||
const cur = curOf(e)
|
||||
const line = lineOf(e.total_price || 0, e, baseTotal(e))
|
||||
const payers = (e.payers || []).filter(p => p.amount !== 0)
|
||||
const net = round2(myPaidOf(e) - myShareOf(e))
|
||||
const unfinished = isUnfinished(e)
|
||||
@@ -823,9 +863,9 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{cur !== base && (
|
||||
{line && (
|
||||
<div className="text-content-faint" style={{ marginTop: 4, fontSize: 'calc(12px * var(--fs-scale-body, 1))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{fmt(e.total_price, cur)} {'→'} {fmt(baseTotal(e))}
|
||||
{fmt(line.entered.amount, line.entered.currency)} {'→'} {fmt(line.into.amount, line.into.currency)}
|
||||
</div>
|
||||
)}
|
||||
{/* Under the name, because a chip reading "Y 122,00" says nothing on
|
||||
@@ -835,7 +875,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
{payers.map(p => (
|
||||
<span key={p.user_id} className="bg-surface-secondary border border-edge" title={personName(p.user_id)} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px 3px 3px', borderRadius: 999, fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))' }}>
|
||||
<Avatar id={p.user_id} size={18} />
|
||||
<span className="text-content" style={{ fontWeight: 700 }}>{fmt(convert(p.amount, cur))}</span>
|
||||
<span className="text-content" style={{ fontWeight: 700 }}>{fmt(booked(p.amount, e))}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
@@ -880,6 +920,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
function SettlementRow({ s }: { s: Settlement }) {
|
||||
// Legacy transfers carry no currency and were entered in the display base.
|
||||
const cur = (s.currency || base).toUpperCase()
|
||||
// Booked in the trip currency like an expense, so it is explained the same way.
|
||||
const line = convertedLine(s.amount, cur, s.exchange_rate, tripCurrency, base, settled(s))
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'stretch', gap: 8 }}>
|
||||
<div className="bg-surface-card border border-edge exp-row" style={{ flex: 1, minWidth: 0, display: 'grid', gridTemplateColumns: isMobile ? '46px 1fr auto' : '46px minmax(200px, 1fr) minmax(0, 1.5fr) auto', gap: isMobile ? 16 : 18, alignItems: 'center', borderRadius: 18, padding: '16px 20px' }}>
|
||||
@@ -887,7 +929,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<div className="text-content" style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600, marginBottom: 6 }}>
|
||||
{t('costs.payment')}
|
||||
{cur !== base && <span className="text-content-faint" style={{ fontWeight: 400, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}> · {fmt(s.amount, cur)} → {fmt(convert(s.amount, cur))}</span>}
|
||||
{line && <span className="text-content-faint" style={{ fontWeight: 400, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}> · {fmt(line.entered.amount, line.entered.currency)} → {fmt(line.into.amount, line.into.currency)}</span>}
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 7, minWidth: 0 }} title={`${personName(s.from_user_id)} → ${personName(s.to_user_id)}`}>
|
||||
<Avatar id={s.from_user_id} size={20} /><ArrowRight size={13} className="text-content-faint" /><Avatar id={s.to_user_id} size={20} />
|
||||
@@ -898,7 +940,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
on the same axis as every expense above it. */}
|
||||
{!isMobile && <span />}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, alignSelf: 'center' }}>
|
||||
<span className="bg-surface-secondary border border-edge text-content" style={{ display: 'inline-flex', alignItems: 'center', padding: '6px 13px', borderRadius: 999, fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 700, whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}>{fmt(convert(s.amount, cur))}</span>
|
||||
<span className="bg-surface-secondary border border-edge text-content" style={{ display: 'inline-flex', alignItems: 'center', padding: '6px 13px', borderRadius: 999, fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 700, whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}>{fmt(settled(s))}</span>
|
||||
</div>
|
||||
</div>
|
||||
{canEdit && (
|
||||
@@ -986,6 +1028,13 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
// server's display cents, not a conversion of the expense list done here.
|
||||
const signed = (v: number) => (v < 0 ? '−' : '+') + fmt(Math.abs(v))
|
||||
const { fronted, moved, outstanding } = finalBudgetSources(row, budgetItems)
|
||||
// Beside a converted row's name, what was entered, so the breakdown names the bill
|
||||
// the way the list above it does rather than by a figure nobody typed.
|
||||
const enteredOf = (itemId: number, shown: number) => {
|
||||
const e = budgetItems.find(i => i.id === itemId)
|
||||
const line = e ? lineOf(paidByUser(e, row.user_id), e, shown) : null
|
||||
return line ? fmt(line.entered.amount, line.entered.currency) : null
|
||||
}
|
||||
const lineCls = { display: 'flex', alignItems: 'baseline', gap: 10, fontSize: 'calc(12px * var(--fs-scale-body, 1))' } as const
|
||||
const detail = (label: string, value: string) => (
|
||||
<div style={lineCls}>
|
||||
@@ -1008,12 +1057,17 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
<div>
|
||||
<div className={labelCls}>{t('costs.finalExpenses')}</div>
|
||||
<div style={listCls}>
|
||||
{fronted.map(r => (
|
||||
<div key={r.item_id} style={lineCls}>
|
||||
<span className="text-content-muted" style={{ minWidth: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.name}</span>
|
||||
<span className="text-content" style={{ whiteSpace: 'nowrap' }}>{signed(r.amount)}</span>
|
||||
</div>
|
||||
))}
|
||||
{fronted.map(r => {
|
||||
const entered = enteredOf(r.item_id, r.amount)
|
||||
return (
|
||||
<div key={r.item_id} style={lineCls}>
|
||||
<span className="text-content-muted" style={{ minWidth: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.name}{entered && <span className="text-content-faint"> · {entered}</span>}
|
||||
</span>
|
||||
<span className="text-content" style={{ whiteSpace: 'nowrap' }}>{signed(r.amount)}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -1131,8 +1185,8 @@ function FlowPills({ ids, lead, Avatar, name }: { ids: number[]; lead: string; A
|
||||
// A transfer can be made in any currency — paying a rouble debt in euros is normal —
|
||||
// so it carries its own, defaulting to the display currency. The server freezes its
|
||||
// FX rate on write, the same way an expense's is frozen.
|
||||
function SettlementModal({ tripId, people, me, editing, currency, onClose, onSaved }: {
|
||||
tripId: number; people: TripMember[]; me: number; editing: Settlement | null; currency: string; onClose: () => void; onSaved: () => void
|
||||
function SettlementModal({ tripId, people, me, editing, currency, tripCurrency, onClose, onSaved }: {
|
||||
tripId: number; people: TripMember[]; me: number; editing: Settlement | null; currency: string; tripCurrency: string; onClose: () => void; onSaved: () => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const toast = useToast()
|
||||
@@ -1153,7 +1207,7 @@ function SettlementModal({ tripId, people, me, editing, currency, onClose, onSav
|
||||
const save = async () => {
|
||||
if (!valid) return
|
||||
setSaving(true)
|
||||
const data = { from_user_id: Number(fromId), to_user_id: Number(toId), amount: amt, currency: cur, settled_at: day }
|
||||
const data = withFallbackFx({ from_user_id: Number(fromId), to_user_id: Number(toId), amount: amt, currency: cur, settled_at: day }, tripCurrency)
|
||||
try {
|
||||
if (editing) await budgetApi.updateSettlement(tripId, editing.id, data)
|
||||
else await budgetApi.createSettlement(tripId, data)
|
||||
@@ -1223,12 +1277,13 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
const toast = useToast()
|
||||
const isMobile = useIsMobile()
|
||||
const { addBudgetItem, updateBudgetItem } = useTripStore()
|
||||
const { convert } = useExchangeRates(base)
|
||||
const sym = (c: string) => SYMBOLS[c] || (c + ' ')
|
||||
// A saved expense without a currency opens in the trip's own (#2525).
|
||||
const { tripCurrency: tripCur, editingCurrency, preview } = useExpenseFx(base, editing)
|
||||
|
||||
const [name, setName] = useState(editing?.name || prefill?.name || '')
|
||||
const [cat, setCat] = useState<string>(editing ? catMeta(editing.category).key : (prefill?.category || 'food'))
|
||||
const [currency, setCurrency] = useState((editing?.currency || base).toUpperCase())
|
||||
const [currency, setCurrency] = useState(editingCurrency)
|
||||
const [day, setDay] = useState(editing?.expense_date || localToday())
|
||||
const [note, setNote] = useState(() => readUserNote(editing))
|
||||
// Edit and prefill seeds are padded to the currency's decimals (#2175): the DB
|
||||
@@ -1236,7 +1291,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
// 5,00 as "5". A prefill has no currency of its own — it is read as `base`,
|
||||
// which is also what the currency field starts on.
|
||||
const [total, setTotal] = useState<string>(() => {
|
||||
if (editing) return editing.total_price ? amountToInputString(editing.total_price, (editing.currency || base).toUpperCase()) : ''
|
||||
if (editing) return editing.total_price ? amountToInputString(editing.total_price, editingCurrency) : ''
|
||||
if (prefill?.amount != null) return amountToInputString(prefill.amount, base)
|
||||
return ''
|
||||
})
|
||||
@@ -1320,6 +1375,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
}, [ticketItems])
|
||||
|
||||
const totalNum = isTicketMode ? ticketInfo.total : (Number.parseFloat(total) || 0)
|
||||
const fx = preview(totalNum, currency)
|
||||
const splitSum = [...participants].reduce((sum, id) => sum + (Number.parseFloat(customAmounts[id]) || 0), 0)
|
||||
const customBalanced = Math.round(splitSum * 100) === Math.round(totalNum * 100)
|
||||
// How much is still to be handed out, read on the total's own side: on a refund
|
||||
@@ -1577,12 +1633,18 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{currency !== base && totalNum !== 0 && (
|
||||
{fx && (
|
||||
<div className="bg-surface-secondary border border-edge text-content-muted" style={{ borderRadius: 10, padding: '10px 12px', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
|
||||
<span>{formatMoney(totalNum, currency, locale)}</span>
|
||||
<span className="text-content-faint">≈</span>
|
||||
<span className="text-content" style={{ fontWeight: 600 }}>{formatMoney(convert(totalNum, currency), base, locale)}</span>
|
||||
<span className="text-content-faint">· {t('costs.liveRate')}</span>
|
||||
{fx.inTrip != null && <>
|
||||
<span className="text-content-faint">→</span>
|
||||
<span className={fx.shown == null ? 'text-content' : undefined} style={fx.shown == null ? { fontWeight: 600 } : undefined}>{formatMoney(fx.inTrip, tripCur, locale)}</span>
|
||||
</>}
|
||||
{fx.shown != null && <>
|
||||
<span className="text-content-faint">≈</span>
|
||||
<span className="text-content" style={{ fontWeight: 600 }}>{formatMoney(fx.shown, base, locale)}</span>
|
||||
<span className="text-content-faint">· {t('costs.liveRate')}</span>
|
||||
</>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1809,7 +1871,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
|
||||
<div style={{ marginTop: 10, fontSize: 12.5, display: 'flex', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
|
||||
{splitMode === 'equally' ? (
|
||||
<span className="text-content-faint">
|
||||
{participants.size > 0 && t('costs.splitSummary', { count: participants.size, amount: sym(currency) + each.toFixed(2) })}
|
||||
{participants.size > 0 && t('costs.splitSummary', { count: participants.size, amount: splitShareLabel(each, currency, fx, participants.size, base, sym, locale) })}
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ fontWeight: 600, color: customBalanced ? '#16a34a' : '#dc2626' }}>
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { formatMoney } from '../../utils/formatters'
|
||||
import { editingCurrencyOf, expenseFxPreview, splitShareLabel } from './expenseFx'
|
||||
|
||||
// A euro trip read in dollars, converted with the euro's own quote: one euro is 1.1551
|
||||
// dollars today, and 1.17 on the day the hotel was booked (#2525).
|
||||
const convert = (amount: number, from: string | null | undefined): number =>
|
||||
(amount / ({ EUR: 1, USD: 1.1551, JPY: 170 } as Record<string, number>)[(from || 'USD').toUpperCase()]) * 1.1551
|
||||
const hotel = { currency: 'USD', exchange_rate: 1.17 }
|
||||
const base = { editing: hotel, editingCurrency: 'USD', tripCurrency: 'EUR', base: 'USD', convert }
|
||||
|
||||
describe('editingCurrencyOf', () => {
|
||||
it('opens a saved expense without a currency in the trip currency', () => {
|
||||
expect(editingCurrencyOf({ currency: null }, 'eur', 'USD')).toBe('EUR')
|
||||
expect(editingCurrencyOf({ currency: 'jpy' }, 'EUR', 'USD')).toBe('JPY')
|
||||
})
|
||||
|
||||
it('starts a new expense, or one on a trip without a currency, in the display currency', () => {
|
||||
expect(editingCurrencyOf(null, 'EUR', 'usd')).toBe('USD')
|
||||
expect(editingCurrencyOf({ currency: null }, null, 'usd')).toBe('USD')
|
||||
})
|
||||
})
|
||||
|
||||
describe('expenseFxPreview', () => {
|
||||
it('previews an edit that keeps the currency at the rate frozen on entry', () => {
|
||||
const fx = expenseFxPreview({ ...base, total: 801.76, currency: 'USD' })!
|
||||
expect(fx.inTrip).toBeCloseTo(685.26, 2)
|
||||
expect(fx.shown).toBeCloseTo(791.55, 2)
|
||||
})
|
||||
|
||||
it('has nothing to preview for a bill in the display currency that reads back as typed', () => {
|
||||
expect(expenseFxPreview({ ...base, editing: { currency: 'USD', exchange_rate: 1.1551 }, total: 12345.67, currency: 'USD' })).toBeNull()
|
||||
expect(expenseFxPreview({ ...base, editing: null, total: 250, currency: 'USD' })).toBeNull()
|
||||
expect(expenseFxPreview({ ...base, total: 0, currency: 'USD' })).toBeNull()
|
||||
})
|
||||
|
||||
it('previews a new or re-currencied amount at today\'s rate', () => {
|
||||
expect(expenseFxPreview({ ...base, editing: null, total: 1700, currency: 'JPY' })).toEqual({ inTrip: null, shown: convert(1700, 'JPY') })
|
||||
// Switching the hotel to yen re-freezes on save, so the old rate does not apply.
|
||||
expect(expenseFxPreview({ ...base, total: 1700, currency: 'JPY' })?.inTrip).toBeNull()
|
||||
})
|
||||
|
||||
it('stops at the trip amount when the viewer reads the trip currency', () => {
|
||||
expect(expenseFxPreview({ ...base, base: 'EUR', total: 801.76, currency: 'USD' })).toEqual({ inTrip: 801.76 / 1.17, shown: null })
|
||||
})
|
||||
})
|
||||
|
||||
describe('splitShareLabel', () => {
|
||||
const sym = (c: string) => (c === 'USD' ? '$' : c + ' ')
|
||||
|
||||
it('prints the entered share, then the share the row lends or borrows', () => {
|
||||
const fx = expenseFxPreview({ ...base, total: 801.76, currency: 'USD' })
|
||||
expect(splitShareLabel(400.88, 'USD', fx, 2, 'USD', sym, 'en-US')).toBe('$400.88 → $395.77')
|
||||
// Read in the trip currency, the share is the booked euros.
|
||||
const inEur = expenseFxPreview({ ...base, base: 'EUR', total: 801.76, currency: 'USD' })
|
||||
expect(splitShareLabel(400.88, 'USD', inEur, 2, 'EUR', sym, 'en-US')).toBe(`$400.88 → ${formatMoney(342.63, 'EUR', 'en-US')}`)
|
||||
})
|
||||
|
||||
it('prints the entered share alone when nothing is converted', () => {
|
||||
expect(splitShareLabel(125, 'USD', null, 2, 'USD', sym, 'en-US')).toBe('$125.00')
|
||||
expect(splitShareLabel(0, 'USD', { inTrip: null, shown: 10 }, 0, 'USD', sym, 'en-US')).toBe('$0.00')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,87 @@
|
||||
import { bookedInTrip, useExchangeRates } from '../../hooks/useExchangeRates'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { currencyDecimals, formatMoney } from '../../utils/formatters'
|
||||
|
||||
/**
|
||||
* The conversion preview of the expense editors, shared by the desktop ExpenseModal and the
|
||||
* phone MCostSheet so the two can never preview the same save differently (#2525). The
|
||||
* editors only lay it out.
|
||||
*/
|
||||
|
||||
interface EditedExpense {
|
||||
currency?: string | null
|
||||
exchange_rate?: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The currency an edited expense opens in. A saved expense without a currency is in the
|
||||
* trip's own, which is how the lists read it; opening it in the display currency relabelled
|
||||
* the amount, and a save then stored it in that currency.
|
||||
*/
|
||||
export function editingCurrencyOf(editing: EditedExpense | null | undefined, tripCurrency: string | null | undefined, base: string): string {
|
||||
return ((editing && (editing.currency || tripCurrency)) || base).toUpperCase()
|
||||
}
|
||||
|
||||
export interface ExpenseFx {
|
||||
/** The amount in the trip currency, when the save keeps a rate frozen on entry. */
|
||||
inTrip: number | null
|
||||
/** The amount in the display currency at today's rate; null when `inTrip` already is. */
|
||||
shown: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* What the amount being edited will count as. An edit that keeps the currency keeps the rate
|
||||
* frozen when the expense was entered (the server re-freezes only when the currency changes),
|
||||
* so it is previewed at that rate, the way the list will show it after the save. Anything
|
||||
* else is previewed at today's rate. Null when there is nothing to convert, including a bill
|
||||
* in the display currency that still reads back as typed.
|
||||
*/
|
||||
export function expenseFxPreview(args: {
|
||||
total: number
|
||||
currency: string
|
||||
editing: EditedExpense | null | undefined
|
||||
editingCurrency: string
|
||||
tripCurrency: string
|
||||
base: string
|
||||
convert: (amount: number, from: string | null | undefined) => number
|
||||
}): ExpenseFx | null {
|
||||
const { total, currency, editing, editingCurrency, tripCurrency, base, convert } = args
|
||||
if (total === 0) return null
|
||||
const inTrip = editing && currency === editingCurrency ? bookedInTrip(total, currency, editing.exchange_rate, tripCurrency) : null
|
||||
if (currency === base && inTrip == null) return null
|
||||
const shown = inTrip == null ? convert(total, currency) : convert(inTrip, tripCurrency)
|
||||
const unit = 10 ** currencyDecimals(base)
|
||||
if (currency === base && Math.round(shown * unit) === Math.round(total * unit)) return null
|
||||
return { inTrip, shown: inTrip != null && tripCurrency === base ? null : shown }
|
||||
}
|
||||
|
||||
/**
|
||||
* One equal share as the split summary prints it, "$400.88", followed by what that share
|
||||
* counts as when the amount is converted, "$400.88 → $390.54". That second figure is the
|
||||
* one the row's "you lent" is made of, so the editor and the row cannot disagree.
|
||||
*/
|
||||
export function splitShareLabel(
|
||||
each: number,
|
||||
currency: string,
|
||||
fx: ExpenseFx | null,
|
||||
participants: number,
|
||||
base: string,
|
||||
sym: (currency: string) => string,
|
||||
locale: string,
|
||||
): string {
|
||||
const entered = sym(currency) + each.toFixed(2)
|
||||
const whole = fx ? (fx.shown ?? fx.inTrip) : null
|
||||
if (whole == null || participants <= 0) return entered
|
||||
return `${entered} → ${formatMoney(whole / participants, base, locale)}`
|
||||
}
|
||||
|
||||
/** Everything an expense editor needs to preview a conversion, from the trip in the store. */
|
||||
export function useExpenseFx(base: string, editing: EditedExpense | null | undefined) {
|
||||
const storedTripCurrency = useTripStore(s => s.trip?.currency)
|
||||
const tripCurrency = (storedTripCurrency || base).toUpperCase()
|
||||
const { convert } = useExchangeRates(base, tripCurrency)
|
||||
const editingCurrency = editingCurrencyOf(editing, storedTripCurrency, base)
|
||||
const preview = (total: number, currency: string) =>
|
||||
expenseFxPreview({ total, currency, editing, editingCurrency, tripCurrency, base, convert })
|
||||
return { tripCurrency, editingCurrency, preview }
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// FE-FREEZE-RATES-001 to FE-FREEZE-RATES-006
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import type { BudgetUnconverted } from '@trek/shared'
|
||||
import { server } from '../../../tests/helpers/msw/server'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
import { buildBudgetItem } from '../../../tests/helpers/factories'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { setForcedOffline } from '../../sync/networkMode'
|
||||
import { clearExchangeRateCache } from '../../hooks/useExchangeRates'
|
||||
import { resetFreezeAttempts, useFreezeMissingRates } from './useFreezeMissingRates'
|
||||
|
||||
// The reporter's setup: an AUD trip whose server cannot fetch rates, and a VND bill that
|
||||
// never froze one. The browser has today's AUD table.
|
||||
const bill = () => buildBudgetItem({ id: 11, trip_id: 5, name: 'Pho', total_price: 8920000, currency: 'VND', exchange_rate: 1 })
|
||||
const pending: BudgetUnconverted = { item_ids: [11], settlement_ids: [3], currencies: ['VND'] }
|
||||
|
||||
type Props = Parameters<typeof useFreezeMissingRates>[0]
|
||||
|
||||
function mountHook(over: Partial<Props> = {}) {
|
||||
const onHealed = vi.fn()
|
||||
const props: Props = { tripId: 5, tripCurrency: 'AUD', canEdit: true, unconverted: pending, onHealed, ...over }
|
||||
const view = renderHook((p: Props) => useFreezeMissingRates(p), { initialProps: props })
|
||||
return { ...view, onHealed, props }
|
||||
}
|
||||
|
||||
let posted: unknown[] = []
|
||||
|
||||
function serveFreeze(reply: () => Response = () => HttpResponse.json({
|
||||
items: [{ ...bill(), exchange_rate: 18241.3 }],
|
||||
settlements: [{ id: 3, trip_id: 5, from_user_id: 2, to_user_id: 1, amount: 100000, currency: 'VND', exchange_rate: 18241.3 }],
|
||||
unresolved: [],
|
||||
})) {
|
||||
server.use(http.post('/api/trips/5/budget/freeze-rates', async ({ request }) => {
|
||||
posted.push(await request.json())
|
||||
return reply()
|
||||
}))
|
||||
}
|
||||
|
||||
/** Lets a heal that was never going to send anything run to its end. */
|
||||
const settle = () => act(async () => { await new Promise(r => setTimeout(r, 30)) })
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
resetFreezeAttempts()
|
||||
clearExchangeRateCache()
|
||||
posted = []
|
||||
localStorage.setItem('trek_fx_AUD', JSON.stringify({ rates: { AUD: 1, VND: 18241.3, EUR: 0.61 }, ts: Date.now() }))
|
||||
seedStore(useTripStore, { budgetItems: [bill()] })
|
||||
serveFreeze()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
setForcedOffline(false)
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('useFreezeMissingRates', () => {
|
||||
it('FE-FREEZE-RATES-001: lends the fresh rates for the listed currencies and reloads once rows count', async () => {
|
||||
const { onHealed } = mountHook()
|
||||
|
||||
await waitFor(() => expect(onHealed).toHaveBeenCalledTimes(1))
|
||||
// Only the currency the settlement is missing goes out, never the whole table.
|
||||
expect(posted).toEqual([{ fallback_fx: { base: 'AUD', rates: { VND: 18241.3 } } }])
|
||||
expect(useTripStore.getState().budgetItems[0].exchange_rate).toBe(18241.3)
|
||||
})
|
||||
|
||||
it('FE-FREEZE-RATES-002: asks once per set of rows, however often the settlement is read', async () => {
|
||||
const { onHealed, props, rerender } = mountHook()
|
||||
await waitFor(() => expect(onHealed).toHaveBeenCalledTimes(1))
|
||||
|
||||
// The same rows in another order, then again after a reload: nothing new to ask.
|
||||
rerender({ ...props, unconverted: { item_ids: [11], settlement_ids: [3], currencies: ['VND'] } })
|
||||
rerender({ ...props, unconverted: { settlement_ids: [3], item_ids: [11], currencies: ['VND'] } })
|
||||
await settle()
|
||||
expect(posted).toHaveLength(1)
|
||||
|
||||
// Another row is another attempt.
|
||||
rerender({ ...props, unconverted: { item_ids: [11, 12], settlement_ids: [3], currencies: ['VND'] } })
|
||||
await waitFor(() => expect(posted).toHaveLength(2))
|
||||
})
|
||||
|
||||
it('FE-FREEZE-RATES-003: never asks for a viewer, offline, or with nothing left out', async () => {
|
||||
mountHook({ canEdit: false })
|
||||
mountHook({ unconverted: { item_ids: [], settlement_ids: [], currencies: [] } })
|
||||
mountHook({ unconverted: undefined })
|
||||
setForcedOffline(true)
|
||||
mountHook({ unconverted: { item_ids: [21], settlement_ids: [], currencies: ['VND'] } })
|
||||
await settle()
|
||||
|
||||
expect(posted).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-FREEZE-RATES-004: sends nothing when the browser has no rate for the currency either', async () => {
|
||||
const { onHealed } = mountHook({ unconverted: { item_ids: [31], settlement_ids: [], currencies: ['JPY'] } })
|
||||
await settle()
|
||||
|
||||
expect(posted).toEqual([])
|
||||
expect(onHealed).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-FREEZE-RATES-005: does not reload when the server froze nothing', async () => {
|
||||
serveFreeze(() => HttpResponse.json({ items: [], settlements: [], unresolved: ['VND'] }))
|
||||
const { onHealed } = mountHook()
|
||||
|
||||
await waitFor(() => expect(posted).toHaveLength(1))
|
||||
await settle()
|
||||
expect(onHealed).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-FREEZE-RATES-006: a refused heal is logged, not thrown, and not retried in a loop', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
serveFreeze(() => HttpResponse.json({ error: 'The trip currency changed. Reload and try again.' }, { status: 409 }))
|
||||
const { onHealed, props, rerender } = mountHook()
|
||||
|
||||
await waitFor(() => expect(warn).toHaveBeenCalled())
|
||||
rerender({ ...props })
|
||||
await settle()
|
||||
expect(posted).toHaveLength(1)
|
||||
expect(onHealed).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { BudgetFallbackFx, BudgetUnconverted } from '@trek/shared'
|
||||
import { fetchFreshRates, isSendableRate } from '../../hooks/useExchangeRates'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { isEffectivelyOffline } from '../../sync/networkMode'
|
||||
|
||||
/**
|
||||
* Every set of rows already tried, by trip, trip currency and ids. The settlement lists a
|
||||
* row it cannot count until a rate is frozen on it; one the browser has no rate for either
|
||||
* stays listed, and without this every reload of the settlement would ask again.
|
||||
*/
|
||||
const tried = new Set<string>()
|
||||
|
||||
/** Test-only: the attempts outlive a vitest file's individual tests. */
|
||||
export function resetFreezeAttempts(): void {
|
||||
tried.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* Heals the rows the settlement leaves out (`unconverted`): expenses and transfers in a
|
||||
* foreign currency that never froze a rate, while the server cannot fetch one. That is the
|
||||
* setup where the server's own fetch fails and the browser's works, so an editor's browser
|
||||
* lends its fresh rates to POST …/budget/freeze-rates. The server still prefers its own rate
|
||||
* and never touches a row that is frozen already.
|
||||
*
|
||||
* Runs for an editor only, online, and once per set of rows. No request goes out when the
|
||||
* browser has no rate for any of the listed currencies either. `onHealed` runs when the
|
||||
* server froze something, so the caller can reload the settlement.
|
||||
*
|
||||
* Deliberately not in the mutation queue: the heal is derived and idempotent, and a replay
|
||||
* hours later would freeze a rate from another day.
|
||||
*/
|
||||
export function useFreezeMissingRates({ tripId, tripCurrency, canEdit, unconverted, onHealed }: {
|
||||
tripId: number
|
||||
tripCurrency: string
|
||||
canEdit: boolean
|
||||
unconverted: BudgetUnconverted | null | undefined
|
||||
onHealed: () => void
|
||||
}): void {
|
||||
const onHealedRef = useRef(onHealed)
|
||||
useEffect(() => { onHealedRef.current = onHealed })
|
||||
const mounted = useRef(true)
|
||||
useEffect(() => {
|
||||
mounted.current = true
|
||||
return () => { mounted.current = false }
|
||||
}, [])
|
||||
|
||||
const trip = (tripCurrency || '').toUpperCase()
|
||||
const itemIds = [...(unconverted?.item_ids ?? [])].sort((a, b) => a - b).join(',')
|
||||
const settlementIds = [...(unconverted?.settlement_ids ?? [])].sort((a, b) => a - b).join(',')
|
||||
const currencies = (unconverted?.currencies ?? []).join(',')
|
||||
|
||||
useEffect(() => {
|
||||
if (!canEdit || !trip || (!itemIds && !settlementIds) || isEffectivelyOffline()) return
|
||||
const key = `${tripId}:${trip}:${itemIds}:${settlementIds}`
|
||||
if (tried.has(key)) return
|
||||
tried.add(key)
|
||||
|
||||
const heal = async (): Promise<void> => {
|
||||
const rates = await fetchFreshRates(trip)
|
||||
const lent: Record<string, number> = {}
|
||||
for (const cur of currencies.split(',')) {
|
||||
const rate = rates?.[cur]
|
||||
if (isSendableRate(rate)) lent[cur] = rate
|
||||
}
|
||||
if (Object.keys(lent).length === 0) return
|
||||
const fallback: BudgetFallbackFx = { base: trip, rates: lent }
|
||||
const result = await useTripStore.getState().freezeMissingRates(tripId, fallback)
|
||||
if (mounted.current && (result.items.length > 0 || result.settlements.length > 0)) onHealedRef.current()
|
||||
}
|
||||
heal().catch((err: unknown) => console.warn('Could not freeze the missing exchange rates:', err))
|
||||
}, [canEdit, trip, tripId, itemIds, settlementIds, currencies])
|
||||
}
|
||||
@@ -708,4 +708,31 @@ describe('CollabChat', () => {
|
||||
{ timeout: 3000 }
|
||||
);
|
||||
});
|
||||
|
||||
// The strip shows the four pictures that will go out; the two the cap turned away
|
||||
// vanish without a word otherwise, and the sender believes all six were sent.
|
||||
it('FE-COMP-CHAT-037: picking more images than fit on one message says so, and says it once', async () => {
|
||||
const addToast = vi.fn();
|
||||
window.__addToast = addToast as unknown as typeof window.__addToast;
|
||||
let minted = 0;
|
||||
const createObjURL = vi.spyOn(URL, 'createObjectURL').mockImplementation(() => `blob:mock/${++minted}`);
|
||||
const revokeObjURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
|
||||
try {
|
||||
render(<CollabChat {...defaultProps} />);
|
||||
await screen.findByText('Start the conversation');
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
const files = Array.from({ length: 6 }, (_, i) => new File([new Uint8Array(8)], `${i}.png`, { type: 'image/png' }));
|
||||
|
||||
fireEvent.change(input, { target: { files } });
|
||||
|
||||
await waitFor(() => expect(document.querySelectorAll('img[src^="blob:mock/"]')).toHaveLength(4));
|
||||
expect(addToast).toHaveBeenCalledTimes(1);
|
||||
const [message, type] = addToast.mock.calls[0];
|
||||
expect(type).toBe('error');
|
||||
expect(message).not.toBe('Only JPEG, PNG, GIF and WebP images up to 10 MB are allowed');
|
||||
} finally {
|
||||
delete window.__addToast;
|
||||
createObjURL.mockRestore(); revokeObjURL.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -48,8 +48,8 @@ export default function CollabChat({ tripId, currentUser }: CollabChatProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{imagePreviews.length > 0 && <div style={{ display: 'flex', gap: 8, marginBottom: 8, overflowX: 'auto' }}>{imagePreviews.map((url, i) => <div key={url} style={{ position: 'relative' }}><img src={url} alt="" style={{ width: 56, height: 56, objectFit: 'cover', borderRadius: 8 }} /><button type="button" onClick={() => removeImage(i)} aria-label="Remove image" style={{ position: 'absolute', top: -6, right: -6, border: 0, borderRadius: '50%', background: 'var(--text-primary)', color: 'var(--bg-primary)', width: 18, height: 18, cursor: 'pointer' }}>×</button></div>)}</div>}
|
||||
{uploadProgress > 0 && uploadProgress < 100 && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 4 }}>Uploading {uploadProgress}%</div>}
|
||||
{imagePreviews.length > 0 && <div style={{ display: 'flex', gap: 8, marginBottom: 8, overflowX: 'auto' }}>{imagePreviews.map((url, i) => <div key={url} style={{ position: 'relative' }}><img src={url} alt="" style={{ width: 56, height: 56, objectFit: 'cover', borderRadius: 8 }} /><button type="button" onClick={() => removeImage(i)} aria-label={t('places.removeImage')} style={{ position: 'absolute', top: -6, right: -6, border: 0, borderRadius: '50%', background: 'var(--text-primary)', color: 'var(--bg-primary)', width: 18, height: 18, cursor: 'pointer' }}>×</button></div>)}</div>}
|
||||
{uploadProgress > 0 && uploadProgress < 100 && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 4 }}>{t('collab.chat.uploading', { percent: uploadProgress })}</div>}
|
||||
<div style={{ display: 'flex', alignItems: 'flex-end', gap: 6 }}>
|
||||
{/* Emoji button */}
|
||||
{canEdit && (
|
||||
@@ -63,7 +63,7 @@ export default function CollabChat({ tripId, currentUser }: CollabChatProps) {
|
||||
</button>
|
||||
)}
|
||||
|
||||
{canEdit && <><input ref={imageInputRef} type="file" accept="image/jpeg,image/png,image/gif,image/webp" multiple hidden onChange={e => { if (e.target.files) addImageFiles(e.target.files); e.currentTarget.value = '' }} /><button type="button" onClick={() => imageInputRef.current?.click()} aria-label="Attach images" style={{ width: 34, height: 34, borderRadius: '50%', border: 'none', background: 'transparent', color: 'var(--text-muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', padding: 0 }}><ImagePlus size={19} /></button></>}
|
||||
{canEdit && <><input ref={imageInputRef} type="file" accept="image/jpeg,image/png,image/gif,image/webp" multiple hidden onChange={e => { if (e.target.files) addImageFiles(e.target.files); e.currentTarget.value = '' }} /><button type="button" onClick={() => imageInputRef.current?.click()} aria-label={t('collab.chat.attachImages')} style={{ width: 34, height: 34, borderRadius: '50%', border: 'none', background: 'transparent', color: 'var(--text-muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', padding: 0 }}><ImagePlus size={19} /></button></>}
|
||||
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { useState } from 'react'
|
||||
import { X } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
|
||||
export function CollabChatAttachment({ attachment }: { attachment: { url: string; original_name?: string; mime_type?: string } }) {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const alt = attachment.original_name || t('collab.chat.attachedImage')
|
||||
return <>
|
||||
<img src={attachment.url} alt={attachment.original_name || 'Attached image'} onClick={() => setOpen(true)} style={{ display: 'block', width: 180, maxWidth: '100%', maxHeight: 220, objectFit: 'cover', borderRadius: 10, cursor: 'zoom-in', marginTop: 4 }} />
|
||||
{open && <div role="dialog" onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(0,0,0,.82)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}><button aria-label="Close image" onClick={() => setOpen(false)} style={{ position: 'fixed', top: 18, right: 18, background: 'rgba(255,255,255,.15)', color: '#fff', border: 0, borderRadius: '50%', width: 36, height: 36 }}><X size={20} /></button><img src={attachment.url} alt={attachment.original_name || 'Attached image'} onClick={e => e.stopPropagation()} style={{ maxWidth: '95vw', maxHeight: '90vh', objectFit: 'contain' }} /></div>}
|
||||
<img src={attachment.url} alt={alt} onClick={() => setOpen(true)} style={{ display: 'block', width: 180, maxWidth: '100%', maxHeight: 220, objectFit: 'cover', borderRadius: 10, cursor: 'zoom-in', marginTop: 4 }} />
|
||||
{open && <div role="dialog" onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(0,0,0,.82)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}><button aria-label={t('collab.chat.closeImage')} onClick={() => setOpen(false)} style={{ position: 'fixed', top: 18, right: 18, background: 'rgba(255,255,255,.15)', color: '#fff', border: 0, borderRadius: '50%', width: 36, height: 36 }}><X size={20} /></button><img src={attachment.url} alt={alt} onClick={e => e.stopPropagation()} style={{ maxWidth: '95vw', maxHeight: '90vh', objectFit: 'contain' }} /></div>}
|
||||
</>
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-LINKS-001 to FE-COMP-LINKS-008
|
||||
// FE-COMP-LINKS-001 to FE-COMP-LINKS-013
|
||||
|
||||
vi.mock('../../api/websocket', () => ({
|
||||
connect: vi.fn(),
|
||||
@@ -10,7 +10,9 @@ vi.mock('../../api/websocket', () => ({
|
||||
removeListener: vi.fn(),
|
||||
}));
|
||||
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { fireEvent, render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
@@ -63,7 +65,8 @@ describe('CollabLinks', () => {
|
||||
);
|
||||
render(<CollabLinks tripId={1} />);
|
||||
expect(await screen.findByText('Ferry timetable')).toBeInTheDocument();
|
||||
expect(screen.getByText('https://ferries.example/timetable')).toBeInTheDocument();
|
||||
// The chip shows the host, not the whole address, and links to the address itself.
|
||||
expect(screen.getByText('ferries.example')).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: /ferry timetable/i })).toHaveAttribute('href', 'https://ferries.example/timetable');
|
||||
});
|
||||
|
||||
@@ -118,6 +121,108 @@ describe('CollabLinks', () => {
|
||||
expect(screen.getByRole('button', { name: /delete link|collab\.links\.delete/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LINKS-009: a link can be edited in place, title and address alike', async () => {
|
||||
// #2414: a link used to be delete-and-add once it needed a correction.
|
||||
const user = userEvent.setup();
|
||||
let put: Record<string, unknown> | null = null;
|
||||
server.use(
|
||||
http.get('/api/trips/1/collab/links', () => HttpResponse.json({ links: [buildLink()] })),
|
||||
http.put('/api/trips/1/collab/links/1', async ({ request }) => {
|
||||
put = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ link: buildLink({ title: 'Ferry timetable 2026', url: 'https://ferries.example/2026' }) });
|
||||
}),
|
||||
);
|
||||
render(<CollabLinks tripId={1} />);
|
||||
await user.click(await screen.findByRole('button', { name: /edit link|collab\.links\.edit/i }));
|
||||
const title = await screen.findByLabelText(/link title|collab\.links\.titlePlaceholder/i);
|
||||
expect(title).toHaveValue('Ferry timetable');
|
||||
await user.clear(title);
|
||||
await user.type(title, 'Ferry timetable 2026');
|
||||
const url = screen.getByLabelText(/https|collab\.links\.urlPlaceholder/i);
|
||||
expect(url).toHaveValue('https://ferries.example/timetable');
|
||||
await user.clear(url);
|
||||
await user.type(url, 'https://ferries.example/2026');
|
||||
await user.click(screen.getByRole('button', { name: /save link|collab\.links\.save/i }));
|
||||
|
||||
await waitFor(() => expect(put).toEqual({ title: 'Ferry timetable 2026', url: 'https://ferries.example/2026' }));
|
||||
await waitFor(() => expect(screen.queryByLabelText(/link title|collab\.links\.titlePlaceholder/i)).not.toBeInTheDocument());
|
||||
expect(await screen.findByText('Ferry timetable 2026')).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: /ferry timetable 2026/i })).toHaveAttribute('href', 'https://ferries.example/2026');
|
||||
});
|
||||
|
||||
it('FE-COMP-LINKS-010: the chip is the link and opens the address in a new tab', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips/1/collab/links', () => HttpResponse.json({ links: [buildLink()] })),
|
||||
);
|
||||
render(<CollabLinks tripId={1} />);
|
||||
const open = await screen.findByRole('link', { name: /ferry timetable/i });
|
||||
expect(open).toHaveAttribute('href', 'https://ferries.example/timetable');
|
||||
expect(open).toHaveAttribute('target', '_blank');
|
||||
// The host stands beside the title; the whole address would not fit a chip.
|
||||
expect(screen.getByText('ferries.example')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LINKS-011: deleting asks first, and the DELETE goes out only once confirmed', async () => {
|
||||
// The link goes for every member, and on the phone the button is a thumb's
|
||||
// width from pin: the notes panel guards the same way.
|
||||
const user = userEvent.setup();
|
||||
let deleted = false;
|
||||
server.use(
|
||||
http.get('/api/trips/1/collab/links', () => HttpResponse.json({ links: [buildLink()] })),
|
||||
http.delete('/api/trips/1/collab/links/1', () => { deleted = true; return HttpResponse.json({ success: true }); }),
|
||||
);
|
||||
render(<CollabLinks tripId={1} />);
|
||||
await user.click(await screen.findByRole('button', { name: /delete link|collab\.links\.delete/i }));
|
||||
expect(await screen.findByText(/delete link\?|collab\.links\.confirmDeleteTitle/i)).toBeInTheDocument();
|
||||
expect(deleted).toBe(false);
|
||||
expect(screen.getByText('Ferry timetable')).toBeInTheDocument();
|
||||
|
||||
// The confirm button of the question itself, found by its role rather than a colour class.
|
||||
const question = screen.getByText(/delete link\?|collab\.links\.confirmDeleteTitle/i).closest('.trek-modal-enter') as HTMLElement;
|
||||
await user.click(within(question).getByRole('button', { name: /^(delete|common\.delete)$/i }));
|
||||
await waitFor(() => expect(deleted).toBe(true));
|
||||
await waitFor(() => expect(screen.queryByText('Ferry timetable')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-COMP-LINKS-012: a corrected address gets a fresh favicon attempt', async () => {
|
||||
// The icon remembers a favicon that failed, and an edit keeps the chip's id,
|
||||
// so the corrected address kept the generic glyph until the panel remounted.
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
http.get('/api/trips/1/collab/links', () => HttpResponse.json({ links: [buildLink({ url: 'https://old.example/page' })] })),
|
||||
http.put('/api/trips/1/collab/links/1', () => HttpResponse.json({ link: buildLink({ url: 'https://new.example/page' }) })),
|
||||
);
|
||||
render(<CollabLinks tripId={1} />);
|
||||
const chip = await screen.findByRole('link', { name: /ferry timetable/i });
|
||||
fireEvent.error(chip.querySelector('img') as HTMLImageElement);
|
||||
await waitFor(() => expect(chip.querySelector('img')).toBeNull());
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /edit link|collab\.links\.edit/i }));
|
||||
const url = await screen.findByLabelText(/https|collab\.links\.urlPlaceholder/i);
|
||||
await user.clear(url);
|
||||
await user.type(url, 'https://new.example/page');
|
||||
await user.click(screen.getByRole('button', { name: /save link|collab\.links\.save/i }));
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('link', { name: /ferry timetable/i }).querySelector('img'))
|
||||
.toHaveAttribute('src', 'https://new.example/favicon.ico'));
|
||||
});
|
||||
|
||||
it('FE-COMP-LINKS-013: on touch the chip actions are finger-sized and apart', () => {
|
||||
// jsdom lays nothing out, so the rule is the assertion. The phone Collab tab
|
||||
// mounts this chip; 22px buttons a pixel apart put delete one slip from pin.
|
||||
const css = readFileSync(resolve(process.cwd(), 'src/index.css'), 'utf8');
|
||||
const at = css.indexOf('@media (hover: none) {\n .collab-link-chip__actions');
|
||||
expect(at, 'touch rules for the chip actions missing from index.css').toBeGreaterThan(-1);
|
||||
const touch = css.slice(at, css.indexOf('\n}', at));
|
||||
expect(touch).toMatch(/\.collab-link-chip__actions \{[^}]*gap:\s*4px/);
|
||||
const action = /\.collab-link-chip__action \{([^}]*)\}/.exec(touch)?.[1] ?? '';
|
||||
for (const side of ['width', 'height']) {
|
||||
expect(Number(new RegExp(`${side}:\\s*(\\d+)px`).exec(action)?.[1]), side).toBeGreaterThanOrEqual(24);
|
||||
}
|
||||
// The height comes back through the margin, so the chip itself stays 36px.
|
||||
expect(action).toMatch(/margin:\s*-4px 0/);
|
||||
});
|
||||
|
||||
it('FE-COMP-LINKS-008: a viewer without edit rights gets no add button', async () => {
|
||||
// collab_edit reserved for the owner, on somebody else's trip.
|
||||
seedStore(usePermissionsStore, { permissions: { collab_edit: 'trip_owner' } });
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { CSSProperties, FormEvent, useEffect, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { ExternalLink, Link2, Pin, Plus, Trash2, X } from 'lucide-react'
|
||||
import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react'
|
||||
import { collabApi } from '../../api/client'
|
||||
import { addListener, removeListener } from '../../api/websocket'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import ConfirmDialog from '../shared/ConfirmDialog'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import { useToast } from '../shared/Toast'
|
||||
|
||||
@@ -18,23 +19,34 @@ interface CollabLink {
|
||||
pinned: boolean | number
|
||||
}
|
||||
|
||||
function LinkIcon({ url, title }: { url: string; title: string }) {
|
||||
function LinkIcon({ url }: { url: string }) {
|
||||
const [failed, setFailed] = useState(false)
|
||||
let favicon = ''
|
||||
try { favicon = new URL('/favicon.ico', url).href } catch { /* not a parseable url, fall through to the glyph */ }
|
||||
if (!favicon || failed) return <span aria-hidden="true" style={{ display: 'grid', placeItems: 'center', width: 28, height: 28, flex: '0 0 28px', borderRadius: 7, background: 'var(--bg-secondary)', color: 'var(--text-faint)' }}><Link2 size={15} /></span>
|
||||
return <img src={favicon} alt="" aria-hidden="true" title={title} onError={() => setFailed(true)} style={{ width: 28, height: 28, flex: '0 0 28px', borderRadius: 7, objectFit: 'contain', background: 'var(--bg-secondary)' }} />
|
||||
return (
|
||||
<span className="collab-link-chip__icon" aria-hidden="true">
|
||||
{!favicon || failed ? <Link2 size={13} /> : <img src={favicon} alt="" onError={() => setFailed(true)} />}
|
||||
<span className="collab-link-chip__go"><ExternalLink size={13} /></span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The part of the address worth a chip's width: the host, without a leading www. */
|
||||
function hostOf(url: string): string {
|
||||
try { return new URL(url).hostname.replace(/^www\./, '') } catch { return url }
|
||||
}
|
||||
|
||||
/**
|
||||
* The add form as a modal, like the poll and note panels next to it. Inline it
|
||||
* pushed the list down and gave the panel a second header, which is what made
|
||||
* this tab read as a different app from its four siblings.
|
||||
* The add and edit form as a modal, like the poll and note panels next to it.
|
||||
* Inline it pushed the list down and gave the panel a second header, which is
|
||||
* what made this tab read as a different app from its four siblings. With a
|
||||
* link handed in it edits that link (#2414): a link used to be delete-and-add
|
||||
* once its title or address needed a correction.
|
||||
*/
|
||||
function AddLinkModal({ onClose, onCreate }: { onClose: () => void; onCreate: (link: { title: string; url: string }) => Promise<void> }) {
|
||||
function LinkModal({ link, onClose, onSave }: { link?: CollabLink; onClose: () => void; onSave: (link: { title: string; url: string }) => Promise<void> }) {
|
||||
const { t } = useTranslation()
|
||||
const [title, setTitle] = useState('')
|
||||
const [url, setUrl] = useState('')
|
||||
const [title, setTitle] = useState(link?.title ?? '')
|
||||
const [url, setUrl] = useState(link?.url ?? '')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const valid = title.trim().length > 0 && url.trim().length > 0
|
||||
|
||||
@@ -43,10 +55,10 @@ function AddLinkModal({ onClose, onCreate }: { onClose: () => void; onCreate: (l
|
||||
if (!valid || busy) return
|
||||
setBusy(true)
|
||||
try {
|
||||
await onCreate({ title: title.trim(), url: url.trim() })
|
||||
await onSave({ title: title.trim(), url: url.trim() })
|
||||
onClose()
|
||||
} catch {
|
||||
// add() already said what went wrong; the form stays open with the input in it.
|
||||
// The caller already said what went wrong; the form stays open with the input in it.
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
@@ -66,7 +78,7 @@ function AddLinkModal({ onClose, onCreate }: { onClose: () => void; onCreate: (l
|
||||
<div role="presentation" style={{ position: 'fixed', inset: 0, background: 'var(--overlay-bg, rgba(0,0,0,0.35))', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999, padding: 16, fontFamily: FONT }} onClick={e => { if (e.target === e.currentTarget) onClose() }}>
|
||||
<form style={{ background: 'var(--bg-card)', borderRadius: 16, width: '100%', maxWidth: 400, maxHeight: '90vh', overflow: 'auto', border: '1px solid var(--border-faint)' }} onSubmit={submit}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px 12px', borderBottom: '1px solid var(--border-faint)' }}>
|
||||
<h3 style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 700, color: 'var(--text-primary)', margin: 0 }}>{t('collab.links.add')}</h3>
|
||||
<h3 style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 700, color: 'var(--text-primary)', margin: 0 }}>{t(link ? 'collab.links.edit' : 'collab.links.add')}</h3>
|
||||
<button type="button" onClick={onClose} aria-label={t('collab.links.cancel')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', padding: 2, display: 'flex' }}><X size={16} /></button>
|
||||
</div>
|
||||
<div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
@@ -99,6 +111,8 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
|
||||
const toast = useToast()
|
||||
const [links, setLinks] = useState<CollabLink[]>([])
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [editing, setEditing] = useState<CollabLink | null>(null)
|
||||
const [pendingDeleteId, setPendingDeleteId] = useState<number | null>(null)
|
||||
|
||||
// Both are new objects on every render, so depending on them would reload the
|
||||
// list after each keystroke and drop a link that was just added back out of it.
|
||||
@@ -168,6 +182,17 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
|
||||
}
|
||||
}
|
||||
|
||||
const edit = async (link: CollabLink, data: { title: string; url: string }) => {
|
||||
try {
|
||||
const d = await collabApi.updateLink(tripId, link.id, data)
|
||||
setLinks(v => v.map(x => x.id === link.id ? d.link : x))
|
||||
} catch (err) {
|
||||
console.error('Failed to edit collab link:', err)
|
||||
toast.error(t('common.error'))
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
const remove = async (id: number) => {
|
||||
try {
|
||||
await collabApi.deleteLink(tripId, id)
|
||||
@@ -197,36 +222,56 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="chat-scroll" style={{ flex: 1, overflowY: 'auto', padding: '0 12px 12px' }}>
|
||||
{/* Content: one chip per link, two to a row (see .collab-link-chip). The chip is
|
||||
the link, with the host beside the title; the actions sit in its tail. */}
|
||||
<div className="chat-scroll collab-link-grid" style={{ flex: 1, overflowY: 'auto', padding: '2px 12px 12px' }}>
|
||||
{links.length === 0 ? (
|
||||
<EmptyState scene="links" title={t('collab.links.empty')} />
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column' }}>
|
||||
<div className="collab-link-grid__cells">
|
||||
{links.map(link => (
|
||||
<div key={link.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 6px', borderBottom: '1px solid var(--border-faint)' }}>
|
||||
<LinkIcon url={link.url} title={link.title} />
|
||||
<a href={link.url} target="_blank" rel="noreferrer" style={{ flex: 1, minWidth: 0, color: 'var(--text-primary)', textDecoration: 'none' }}>
|
||||
<div style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{link.title}</div>
|
||||
<div style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{link.url}</div>
|
||||
<div key={link.id} className={link.pinned ? 'collab-link-chip collab-link-chip--pinned' : 'collab-link-chip'}>
|
||||
<a className="collab-link-chip__main" href={link.url} target="_blank" rel="noreferrer" title={t('collab.links.open')}>
|
||||
{/* Keyed on the address: the icon remembers a favicon that failed, and
|
||||
an edit keeps the chip's id, so a corrected address got the glyph. */}
|
||||
<LinkIcon key={link.url} url={link.url} />
|
||||
<span className="collab-link-chip__text">
|
||||
<span className="collab-link-chip__title">{link.title}</span>
|
||||
<span className="collab-link-chip__host">{hostOf(link.url)}</span>
|
||||
</span>
|
||||
</a>
|
||||
<ExternalLink size={15} color="var(--text-faint)" aria-hidden="true" />
|
||||
{canEdit && <>
|
||||
<button type="button" onClick={() => toggle(link)} aria-label={link.pinned ? t('collab.links.unpin') : t('collab.links.pin')} style={{ border: 0, background: 'transparent', color: link.pinned ? 'var(--accent)' : 'var(--text-faint)', cursor: 'pointer' }}>
|
||||
<Pin size={15} fill={link.pinned ? 'currentColor' : 'none'} aria-hidden="true" />
|
||||
</button>
|
||||
<button type="button" onClick={() => remove(link.id)} aria-label={t('collab.links.delete')} style={{ border: 0, background: 'transparent', color: 'var(--text-faint)', cursor: 'pointer' }}>
|
||||
<Trash2 size={15} aria-hidden="true" />
|
||||
</button>
|
||||
</>}
|
||||
{canEdit && (
|
||||
<span className="collab-link-chip__actions">
|
||||
<button type="button" className="collab-link-chip__action" onClick={() => setEditing(link)} aria-label={t('collab.links.edit')} title={t('collab.links.edit')}>
|
||||
<Pencil size={13} aria-hidden="true" />
|
||||
</button>
|
||||
<button type="button" className={link.pinned ? 'collab-link-chip__action collab-link-chip__action--on' : 'collab-link-chip__action'} onClick={() => toggle(link)} aria-label={link.pinned ? t('collab.links.unpin') : t('collab.links.pin')} title={link.pinned ? t('collab.links.unpin') : t('collab.links.pin')}>
|
||||
<Pin size={13} fill={link.pinned ? 'currentColor' : 'none'} aria-hidden="true" />
|
||||
</button>
|
||||
<button type="button" className="collab-link-chip__action" onClick={() => setPendingDeleteId(link.id)} aria-label={t('collab.links.delete')} title={t('collab.links.delete')}>
|
||||
<Trash2 size={13} aria-hidden="true" />
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Create Modal */}
|
||||
{showForm && <AddLinkModal onClose={() => setShowForm(false)} onCreate={add} />}
|
||||
{/* Create and edit modals */}
|
||||
{showForm && <LinkModal onClose={() => setShowForm(false)} onSave={add} />}
|
||||
{editing && <LinkModal key={editing.id} link={editing} onClose={() => setEditing(null)} onSave={data => edit(editing, data)} />}
|
||||
|
||||
{/* The delete is shared: the link goes for every member, and on the phone the
|
||||
button is a thumb's width from pin. Same guard as the notes panel. */}
|
||||
<ConfirmDialog
|
||||
isOpen={pendingDeleteId !== null}
|
||||
onClose={() => setPendingDeleteId(null)}
|
||||
onConfirm={() => (pendingDeleteId !== null ? remove(pendingDeleteId) : undefined)}
|
||||
title={t('collab.links.confirmDeleteTitle')}
|
||||
message={t('collab.links.confirmDeleteBody')}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -201,7 +201,9 @@ describe('CollabNotes', () => {
|
||||
// Deleting now asks for confirmation first — the note stays until confirmed.
|
||||
expect(screen.getByText('Delete note?')).toBeInTheDocument();
|
||||
expect(screen.getByText('Remove Me')).toBeInTheDocument();
|
||||
await user.click(document.querySelector('button.bg-red-600') as HTMLElement);
|
||||
// The confirm button of the question itself, found by its role rather than a colour class.
|
||||
const question = screen.getByText('Delete note?').closest('.trek-modal-enter') as HTMLElement;
|
||||
await user.click(within(question).getByRole('button', { name: 'Delete' }));
|
||||
await waitFor(() => expect(screen.queryByText('Remove Me')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* FE-CHATIMG-001..006 — the pictures pinned to a chat message before it is sent.
|
||||
* FE-CHATIMG-001..009: the pictures pinned to a chat message before it is sent.
|
||||
*
|
||||
* The reason this file exists: the hook used to create object URLs and enqueue
|
||||
* the preview state from inside a `setFiles` updater. React invokes an updater
|
||||
@@ -11,7 +11,7 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { StrictMode } from 'react'
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { useChatImages, MAX_CHAT_IMAGES } from './useChatImages'
|
||||
import { useChatImages, MAX_CHAT_IMAGES, type ChatImageDrop } from './useChatImages'
|
||||
|
||||
let nextUrl = 0
|
||||
const revoked: string[] = []
|
||||
@@ -92,4 +92,44 @@ describe('useChatImages', () => {
|
||||
expect(result.current.files).toEqual([])
|
||||
expect(revoked.sort()).toEqual(['blob:mock/1', 'blob:mock/2'])
|
||||
})
|
||||
|
||||
// The strip shows what will be sent, so a picture the cap turned away is as gone as
|
||||
// one of the wrong kind. The sender hears about both, and hears which it was.
|
||||
it('FE-CHATIMG-007: a pick past the cap is reported as an overflow and is not a clean add', () => {
|
||||
const { result } = strict()
|
||||
const drops: ChatImageDrop[] = []
|
||||
let ok = true
|
||||
|
||||
act(() => {
|
||||
ok = result.current.add(Array.from({ length: MAX_CHAT_IMAGES + 2 }, (_, i) => img(`${i}.png`)), d => drops.push(d))
|
||||
})
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(drops).toEqual([{ rejected: 0, overflow: 2 }])
|
||||
expect(result.current.files).toHaveLength(MAX_CHAT_IMAGES)
|
||||
})
|
||||
|
||||
it('FE-CHATIMG-008: a wrong kind and an overflow in one pick are told apart', () => {
|
||||
const { result } = strict()
|
||||
act(() => { result.current.add([img('a.png'), img('b.png'), img('c.png')]) })
|
||||
const drops: ChatImageDrop[] = []
|
||||
|
||||
act(() => {
|
||||
result.current.add([new File(['x'], 'notes.pdf', { type: 'application/pdf' }), img('d.png'), img('e.png')], d => drops.push(d))
|
||||
})
|
||||
|
||||
expect(result.current.files.map(f => f.name)).toEqual(['a.png', 'b.png', 'c.png', 'd.png'])
|
||||
expect(drops).toEqual([{ rejected: 1, overflow: 1 }])
|
||||
})
|
||||
|
||||
it('FE-CHATIMG-009: a pick that fits is a clean add and reports nothing', () => {
|
||||
const { result } = strict()
|
||||
const onDrop = vi.fn()
|
||||
let ok = false
|
||||
|
||||
act(() => { ok = result.current.add([img('a.png')], onDrop) })
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(onDrop).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -28,11 +28,24 @@ interface PickedImage {
|
||||
url: string
|
||||
}
|
||||
|
||||
/**
|
||||
* What an add() left out: files of the wrong type or over the size limit, and
|
||||
* valid files past the cap of MAX_CHAT_IMAGES. Either can be zero, both cannot.
|
||||
*/
|
||||
export interface ChatImageDrop {
|
||||
rejected: number
|
||||
overflow: number
|
||||
}
|
||||
|
||||
export interface ChatImages {
|
||||
files: File[]
|
||||
previews: string[]
|
||||
/** Returns false when something was dropped, so the caller can say why. */
|
||||
add: (incoming: FileList | File[]) => boolean
|
||||
/**
|
||||
* Returns false when something was dropped, so the caller can say why. The
|
||||
* optional callback tells it what was dropped, because a picture past the cap
|
||||
* is a different message from a picture of the wrong kind.
|
||||
*/
|
||||
add: (incoming: FileList | File[], onDrop?: (drop: ChatImageDrop) => void) => boolean
|
||||
remove: (index: number) => void
|
||||
clear: () => void
|
||||
}
|
||||
@@ -52,7 +65,7 @@ export function useChatImages(): ChatImages {
|
||||
itemsRef.current = []
|
||||
}, [])
|
||||
|
||||
const add = useCallback((incoming: FileList | File[]) => {
|
||||
const add = useCallback((incoming: FileList | File[], onDrop?: (drop: ChatImageDrop) => void) => {
|
||||
const all = Array.from(incoming)
|
||||
const valid = all.filter(f => CHAT_IMAGE_TYPES.includes(f.type) && f.size <= MAX_CHAT_IMAGE_BYTES)
|
||||
const room = MAX_CHAT_IMAGES - itemsRef.current.length
|
||||
@@ -61,7 +74,11 @@ export function useChatImages(): ChatImages {
|
||||
// Only the new files get a URL; the ones already in the list keep theirs.
|
||||
commit([...itemsRef.current, ...added.map(file => ({ file, url: URL.createObjectURL(file) }))])
|
||||
}
|
||||
return valid.length === all.length
|
||||
// A picture the cap turned away is as gone as one of the wrong kind: the strip
|
||||
// shows what will be sent, and the sender deserves to hear why it is short.
|
||||
const drop = { rejected: all.length - valid.length, overflow: valid.length - added.length }
|
||||
if (drop.rejected || drop.overflow) onDrop?.(drop)
|
||||
return drop.rejected === 0 && drop.overflow === 0
|
||||
}, [commit])
|
||||
|
||||
const remove = useCallback((index: number) => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { addListener, removeListener } from '../../api/websocket'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useChatImages } from './useChatImages'
|
||||
import { useChatImages, MAX_CHAT_IMAGES } from './useChatImages'
|
||||
import { useToast } from '../shared/Toast'
|
||||
|
||||
export function useCollabChat(tripId: any, currentUser: any) {
|
||||
@@ -122,7 +122,10 @@ export function useCollabChat(tripId: any, currentUser: any) {
|
||||
|
||||
/* ── send ── */
|
||||
const addImageFiles = useCallback((incoming: File[] | FileList) => {
|
||||
if (!images.add(incoming)) toast.error(t('collab.chat.imageRejected'))
|
||||
images.add(incoming, ({ rejected, overflow }) => {
|
||||
if (rejected) toast.error(t('collab.chat.imageRejected'))
|
||||
if (overflow) toast.error(t('collab.chat.imageLimit', { max: MAX_CHAT_IMAGES }))
|
||||
})
|
||||
}, [images, toast, t])
|
||||
const removeImage = images.remove
|
||||
const handlePaste = useCallback((e: ClipboardEvent) => { if (e.clipboardData.files.length) addImageFiles(e.clipboardData.files) }, [addImageFiles])
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// FE-COMP-COLEXPORT-001 to FE-COMP-COLEXPORT-008
|
||||
import React from 'react';
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { useTranslation } from '../../i18n/TranslationContext';
|
||||
import CollectionExportMenu from './CollectionExportMenu';
|
||||
|
||||
type MenuProps = Omit<React.ComponentProps<typeof CollectionExportMenu>, 't'>;
|
||||
|
||||
function Harness(props: MenuProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<CollectionExportMenu {...props} t={t} />
|
||||
<button type="button">Somewhere else</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function renderMenu(overrides: Partial<MenuProps> = {}) {
|
||||
const props: MenuProps = { onExport: vi.fn(), ...overrides };
|
||||
render(<Harness {...props} />);
|
||||
return props;
|
||||
}
|
||||
|
||||
const trigger = () => screen.getByRole('button', { name: 'Export' });
|
||||
const items = () => screen.getAllByRole('menuitem');
|
||||
|
||||
describe('CollectionExportMenu (#2301)', () => {
|
||||
it('FE-COMP-COLEXPORT-001: is a closed menu button until pressed', () => {
|
||||
renderMenu();
|
||||
expect(trigger()).toHaveAttribute('aria-haspopup', 'menu');
|
||||
expect(trigger()).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(screen.queryByRole('menu')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLEXPORT-002: offers both formats, each with its extension and what it is for', async () => {
|
||||
renderMenu();
|
||||
await userEvent.click(trigger());
|
||||
|
||||
const menu = screen.getByRole('menu', { name: 'Download this list as a file' });
|
||||
expect(trigger()).toHaveAttribute('aria-expanded', 'true');
|
||||
expect(trigger()).toHaveAttribute('aria-controls', menu.id);
|
||||
expect(items().map(item => item.textContent)).toEqual([
|
||||
'TREK list.trekcollection.jsonFor another TREK, with labels and status',
|
||||
'GPX.gpxWaypoints for OsmAnd, Organic Maps, Garmin and other map apps',
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-COMP-COLEXPORT-003: exports the picked format, closes and gives focus back', async () => {
|
||||
const props = renderMenu();
|
||||
await userEvent.click(trigger());
|
||||
|
||||
await userEvent.click(screen.getByRole('menuitem', { name: /GPX/ }));
|
||||
|
||||
expect(props.onExport).toHaveBeenCalledWith('gpx');
|
||||
expect(screen.queryByRole('menu')).toBeNull();
|
||||
expect(trigger()).toHaveFocus();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLEXPORT-004: moves focus into the menu and walks it with the arrow keys, Home and End', async () => {
|
||||
renderMenu();
|
||||
await userEvent.click(trigger());
|
||||
await waitFor(() => expect(items()[0]).toHaveFocus());
|
||||
|
||||
await userEvent.keyboard('{ArrowDown}');
|
||||
expect(items()[1]).toHaveFocus();
|
||||
// Past the end wraps round, as it does in every menu.
|
||||
await userEvent.keyboard('{ArrowDown}');
|
||||
expect(items()[0]).toHaveFocus();
|
||||
await userEvent.keyboard('{ArrowUp}');
|
||||
expect(items()[1]).toHaveFocus();
|
||||
await userEvent.keyboard('{Home}');
|
||||
expect(items()[0]).toHaveFocus();
|
||||
await userEvent.keyboard('{End}');
|
||||
expect(items()[1]).toHaveFocus();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLEXPORT-005: opens from the keyboard and picks with Enter', async () => {
|
||||
const props = renderMenu();
|
||||
trigger().focus();
|
||||
|
||||
await userEvent.keyboard('{ArrowDown}');
|
||||
await waitFor(() => expect(items()[0]).toHaveFocus());
|
||||
await userEvent.keyboard('{Enter}');
|
||||
|
||||
expect(props.onExport).toHaveBeenCalledWith('trek');
|
||||
});
|
||||
|
||||
it('FE-COMP-COLEXPORT-006: closes on Escape without exporting, and gives focus back', async () => {
|
||||
const props = renderMenu();
|
||||
await userEvent.click(trigger());
|
||||
await waitFor(() => expect(items()[0]).toHaveFocus());
|
||||
|
||||
await userEvent.keyboard('{Escape}');
|
||||
|
||||
expect(screen.queryByRole('menu')).toBeNull();
|
||||
expect(trigger()).toHaveFocus();
|
||||
expect(props.onExport).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLEXPORT-007: closes on a click anywhere else, and on Tab', async () => {
|
||||
renderMenu();
|
||||
await userEvent.click(trigger());
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Somewhere else' }));
|
||||
expect(screen.queryByRole('menu')).toBeNull();
|
||||
|
||||
await userEvent.click(trigger());
|
||||
await waitFor(() => expect(items()[0]).toHaveFocus());
|
||||
await userEvent.keyboard('{Tab}');
|
||||
expect(screen.queryByRole('menu')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLEXPORT-008: cannot be opened while an export is still running', async () => {
|
||||
renderMenu({ exporting: true });
|
||||
expect(trigger()).toBeDisabled();
|
||||
await userEvent.click(trigger());
|
||||
expect(screen.queryByRole('menu')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import React, { useCallback, useEffect, useId, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { Download, FileJson, Loader2, Route, type LucideIcon } from 'lucide-react'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition'
|
||||
import { COLLECTION_FILE_EXTENSION, COLLECTION_GPX_EXTENSION, type CollectionExportFormat } from './collectionFile'
|
||||
|
||||
interface CollectionExportMenuProps {
|
||||
onExport: (format: CollectionExportFormat) => void
|
||||
exporting?: boolean
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
interface FormatOption {
|
||||
format: CollectionExportFormat
|
||||
icon: LucideIcon
|
||||
label: string
|
||||
extension: string
|
||||
hint: string
|
||||
}
|
||||
|
||||
/** Wide enough for the longest hint on one or two lines at the default text size. */
|
||||
const MENU_WIDTH = 300
|
||||
|
||||
/**
|
||||
* Export in the list hero: a menu of the two formats a list can leave in (#2301).
|
||||
*
|
||||
* The TREK file carries everything and is for another TREK; GPX carries the
|
||||
* places as waypoints and is for every other map app. Choosing is the whole
|
||||
* interaction, so it is a menu rather than a dialog.
|
||||
*
|
||||
* Portalled, because the hero clips its overflow, and placed against the
|
||||
* trigger's right edge, where the button sits. A menu in the WAI-ARIA sense:
|
||||
* focus moves into it on open, the arrow keys, Home and End walk it, Escape
|
||||
* closes it and gives focus back to the button, and Tab leaves it closed.
|
||||
*/
|
||||
export default function CollectionExportMenu({ onExport, exporting, t }: CollectionExportMenuProps): React.ReactElement {
|
||||
const [open, setOpen] = useState(false)
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
const menuRef = useRef<HTMLDivElement>(null)
|
||||
const menuId = useId()
|
||||
const anchored = useAnchoredPosition(triggerRef, open, { estimatedHeight: 150, offset: 6 })
|
||||
// Focusable only once positioned: until then the menu is hidden, and a hidden
|
||||
// element refuses focus.
|
||||
const placed = open && anchored !== null
|
||||
|
||||
const options: FormatOption[] = [
|
||||
{
|
||||
format: 'trek', icon: FileJson, label: t('collections.file.formatTrek'),
|
||||
extension: COLLECTION_FILE_EXTENSION, hint: t('collections.file.formatTrekHint'),
|
||||
},
|
||||
{
|
||||
format: 'gpx', icon: Route, label: 'GPX',
|
||||
extension: COLLECTION_GPX_EXTENSION, hint: t('collections.file.formatGpxHint'),
|
||||
},
|
||||
]
|
||||
|
||||
const items = () => Array.from(menuRef.current?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [])
|
||||
|
||||
const close = useCallback((refocus: boolean) => {
|
||||
setOpen(false)
|
||||
if (refocus) triggerRef.current?.focus()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (placed) menuRef.current?.querySelector<HTMLElement>('[role="menuitem"]')?.focus()
|
||||
}, [placed])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onPointerDown = (e: MouseEvent) => {
|
||||
const target = e.target as Node
|
||||
if (triggerRef.current?.contains(target) || menuRef.current?.contains(target)) return
|
||||
close(false)
|
||||
}
|
||||
document.addEventListener('mousedown', onPointerDown)
|
||||
return () => document.removeEventListener('mousedown', onPointerDown)
|
||||
}, [open, close])
|
||||
|
||||
const onMenuKeyDown = (e: React.KeyboardEvent) => {
|
||||
const all = items()
|
||||
const at = all.indexOf(document.activeElement as HTMLElement)
|
||||
const focus = (index: number) => {
|
||||
e.preventDefault()
|
||||
all[(index + all.length) % all.length]?.focus()
|
||||
}
|
||||
if (e.key === 'ArrowDown') focus(at + 1)
|
||||
else if (e.key === 'ArrowUp') focus(at - 1)
|
||||
else if (e.key === 'Home') focus(0)
|
||||
else if (e.key === 'End') focus(all.length - 1)
|
||||
else if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
close(true)
|
||||
} else if (e.key === 'Tab') close(false)
|
||||
}
|
||||
|
||||
const pick = (format: CollectionExportFormat) => {
|
||||
close(true)
|
||||
onExport(format)
|
||||
}
|
||||
|
||||
// Pinned by its right edge, under the button, so it grows leftwards into the hero.
|
||||
const right = anchored ? Math.max(8, window.innerWidth - anchored.left - anchored.width) : 8
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
onClick={() => setOpen(o => !o)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'ArrowDown' && !open) {
|
||||
e.preventDefault()
|
||||
setOpen(true)
|
||||
}
|
||||
}}
|
||||
disabled={exporting}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
aria-controls={open ? menuId : undefined}
|
||||
aria-label={t('collections.file.export')}
|
||||
title={t('collections.file.exportTitle')}
|
||||
className="col-glass-btn"
|
||||
>
|
||||
{exporting ? <Loader2 size={15} className="animate-spin" /> : <Download size={15} />}
|
||||
<span className="txt">{t('collections.file.export')}</span>
|
||||
</button>
|
||||
{open && createPortal(
|
||||
<div
|
||||
ref={menuRef}
|
||||
id={menuId}
|
||||
role="menu"
|
||||
aria-label={t('collections.file.exportTitle')}
|
||||
onKeyDown={onMenuKeyDown}
|
||||
className="trek-popover-enter fixed z-[var(--z-toast)] p-1.5 rounded-xl border border-edge bg-surface-card shadow-dropdown"
|
||||
style={{
|
||||
...(anchored?.flipped ? { bottom: anchored.bottom } : { top: anchored?.top ?? 0 }),
|
||||
right,
|
||||
width: MENU_WIDTH,
|
||||
maxWidth: 'calc(100vw - 16px)',
|
||||
visibility: anchored ? 'visible' : 'hidden',
|
||||
}}
|
||||
>
|
||||
{options.map(option => (
|
||||
<button
|
||||
key={option.format}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
tabIndex={-1}
|
||||
onClick={() => pick(option.format)}
|
||||
className="w-full flex items-start gap-3 px-3 py-2.5 rounded-lg text-left transition-colors hover:bg-surface-hover focus:bg-surface-hover focus:outline-none"
|
||||
>
|
||||
<option.icon size={16} className="mt-0.5 shrink-0 text-content-faint" aria-hidden />
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="flex items-baseline justify-between gap-3">
|
||||
<span className="text-body font-semibold text-content">{option.label}</span>
|
||||
<span className="text-caption text-content-faint">{option.extension}</span>
|
||||
</span>
|
||||
<span className="block text-caption text-content-muted">{option.hint}</span>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -172,8 +172,10 @@ describe('CollectionHero', () => {
|
||||
const all = [...document.querySelectorAll('.col-hero-actions button')];
|
||||
expect(all).toEqual(actions);
|
||||
|
||||
// Export asks which format first (#2301).
|
||||
await userEvent.click(actions[1]);
|
||||
expect(onExport).toHaveBeenCalledTimes(1);
|
||||
await userEvent.click(screen.getByRole('menuitem', { name: /TREK list/ }));
|
||||
expect(onExport).toHaveBeenCalledWith('trek');
|
||||
});
|
||||
|
||||
it('FE-COMP-COLHERO-013: has no Export button where there is no list to export', () => {
|
||||
@@ -186,8 +188,9 @@ describe('CollectionHero', () => {
|
||||
renderHero({ canEdit: false, canShare: false, isOwner: false, onExport });
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Export' }));
|
||||
await userEvent.click(screen.getByRole('menuitem', { name: /GPX/ }));
|
||||
|
||||
expect(onExport).toHaveBeenCalledTimes(1);
|
||||
expect(onExport).toHaveBeenCalledWith('gpx');
|
||||
expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import React from 'react'
|
||||
import { avatarSrc } from '../../utils/avatarSrc'
|
||||
import { Share2, Users, Link2, Pencil, Download, Loader2 } from 'lucide-react'
|
||||
import { Share2, Users, Link2, Pencil } from 'lucide-react'
|
||||
import type { CollectionMember, CollectionLink } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import CollectionExportMenu from './CollectionExportMenu'
|
||||
import type { CollectionExportFormat } from './collectionFile'
|
||||
|
||||
const AV_COLORS = ['#6366f1', '#ec4899', '#14b8a6', '#f97316', '#8b5cf6', '#3b82f6', '#ef4444', '#22c55e']
|
||||
|
||||
@@ -27,7 +29,7 @@ interface CollectionHeroProps {
|
||||
shareMemberCount: number
|
||||
onShare: () => void
|
||||
/** Absent on the "All saved" pseudo-list, which is a view rather than a list. */
|
||||
onExport?: () => void
|
||||
onExport?: (format: CollectionExportFormat) => void
|
||||
exporting?: boolean
|
||||
t: TranslationFn
|
||||
}
|
||||
@@ -98,19 +100,7 @@ export default function CollectionHero({
|
||||
<span className="txt">{t('common.edit')}</span>
|
||||
</button>
|
||||
)}
|
||||
{onExport && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onExport}
|
||||
disabled={exporting}
|
||||
aria-label={t('collections.file.export')}
|
||||
title={t('collections.file.exportTitle')}
|
||||
className="col-glass-btn"
|
||||
>
|
||||
{exporting ? <Loader2 size={15} className="animate-spin" /> : <Download size={15} />}
|
||||
<span className="txt">{t('collections.file.export')}</span>
|
||||
</button>
|
||||
)}
|
||||
{onExport && <CollectionExportMenu onExport={onExport} exporting={exporting} t={t} />}
|
||||
{canShare && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-COLDETAIL-001 to FE-COMP-COLDETAIL-043
|
||||
// FE-COMP-COLDETAIL-001 to FE-COMP-COLDETAIL-048
|
||||
import React from 'react';
|
||||
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
@@ -602,3 +602,89 @@ describe('CollectionPlaceDetail: editable address', () => {
|
||||
expect(screen.getByPlaceholderText('Street, City, Country')).toHaveValue('Somewhere');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Cover controls sit beside the close button ───────────────────────────────
|
||||
|
||||
describe('CollectionPlaceDetail: cover controls', () => {
|
||||
it('FE-COMP-COLDETAIL-044: the camera sits in the top right row, just left of the close button', async () => {
|
||||
renderDetail({ canEdit: true, onUploadImage: vi.fn() });
|
||||
const camera = await screen.findByRole('button', { name: 'Upload image' });
|
||||
const close = screen.getByRole('button', { name: 'Close' });
|
||||
|
||||
const row = close.parentElement as HTMLElement;
|
||||
expect(camera.parentElement).toBe(row);
|
||||
expect(camera.nextElementSibling).toBe(close);
|
||||
// Same class as the close button, so the same round look, hover and phone size.
|
||||
expect(camera).toHaveClass('col-detail-close');
|
||||
// The category chip keeps the top left corner to itself.
|
||||
const chip = screen.getByText('Food').closest('.col-detail-cover-cat') as HTMLElement;
|
||||
expect(row.contains(chip)).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-COLDETAIL-045: with a custom cover the row reads remove, change, close and change still opens the picker', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDetail({ canEdit: true, onUploadImage: vi.fn(), place: { ...place, image_url: '/uploads/places/mock.jpg' } });
|
||||
const change = await screen.findByRole('button', { name: 'Change image' });
|
||||
const remove = screen.getByRole('button', { name: 'Remove image' });
|
||||
const close = screen.getByRole('button', { name: 'Close' });
|
||||
|
||||
expect(Array.from((close.parentElement as HTMLElement).querySelectorAll('button'))).toEqual([remove, change, close]);
|
||||
expect(remove).toHaveClass('col-detail-close');
|
||||
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
const clicked = vi.fn();
|
||||
input.addEventListener('click', clicked);
|
||||
await user.click(change);
|
||||
expect(clicked).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-COLDETAIL-046: while an upload runs the camera spins, ignores clicks and the remove control steps aside', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onUploadImage = vi.fn(() => new Promise<void>(() => {}));
|
||||
renderDetail({ canEdit: true, onUploadImage, place: { ...place, image_url: '/uploads/places/mock.jpg' } });
|
||||
await screen.findByRole('button', { name: 'Change image' });
|
||||
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { files: [new File(['x'], 'cover.png', { type: 'image/png' })] } });
|
||||
|
||||
const change = screen.getByRole('button', { name: 'Change image' });
|
||||
await waitFor(() => expect(change.querySelector('.animate-spin')).not.toBeNull());
|
||||
expect(screen.queryByRole('button', { name: 'Remove image' })).not.toBeInTheDocument();
|
||||
expect(change.nextElementSibling).toBe(screen.getByRole('button', { name: 'Close' }));
|
||||
|
||||
const clicked = vi.fn();
|
||||
input.addEventListener('click', clicked);
|
||||
await user.click(change);
|
||||
expect(clicked).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLDETAIL-047: a long category shares the top bar with the controls and ellipsizes instead of running under them', async () => {
|
||||
const long = 'Restaurants, cafes and late night bars';
|
||||
renderDetail({
|
||||
canEdit: true,
|
||||
onUploadImage: vi.fn(),
|
||||
place: { ...place, image_url: '/uploads/places/mock.jpg', category: { id: 1, name: long, color: '#f00', icon: null } },
|
||||
});
|
||||
const controls = (await screen.findByRole('button', { name: 'Close' })).parentElement as HTMLElement;
|
||||
const text = screen.getByText(long);
|
||||
const chip = text.closest('.col-detail-cover-cat') as HTMLElement;
|
||||
const bar = controls.parentElement as HTMLElement;
|
||||
|
||||
expect(controls.querySelectorAll('button')).toHaveLength(3);
|
||||
// Chip first, controls last in one flex bar: the chip only gets what the buttons leave.
|
||||
expect(Array.from(bar.children)).toEqual([chip, controls]);
|
||||
expect(bar).toHaveClass('absolute', 'flex', 'left-[14px]', 'right-[12px]', 'top-[12px]');
|
||||
expect(controls).toHaveClass('ms-auto', 'flex-none');
|
||||
expect(chip).toHaveClass('min-w-0');
|
||||
expect(text).toHaveClass('truncate');
|
||||
});
|
||||
|
||||
it('FE-COMP-COLDETAIL-048: without a category the controls still hold the end of the bar', async () => {
|
||||
renderDetail({ canEdit: true, onUploadImage: vi.fn(), place: { ...place, category: undefined } });
|
||||
const controls = (await screen.findByRole('button', { name: 'Close' })).parentElement as HTMLElement;
|
||||
|
||||
expect(document.querySelector('.col-detail-cover-cat')).toBeNull();
|
||||
expect(Array.from((controls.parentElement as HTMLElement).children)).toEqual([controls]);
|
||||
expect(controls).toHaveClass('ms-auto');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -180,39 +180,45 @@ export default function CollectionPlaceDetail({
|
||||
<div className="col-detail-cover" style={banner ? undefined : { backgroundImage: entityGradient(place.id) }}>
|
||||
{banner && <img src={banner} alt="" />}
|
||||
<div className="col-detail-cover-scrim" />
|
||||
{place.category?.name && (
|
||||
<span className="col-detail-cover-cat" style={{ ['--cat' as string]: place.category.color || '#6366f1' }}>
|
||||
<CatIcon size={12} /> {place.category.name}
|
||||
</span>
|
||||
)}
|
||||
<button type="button" className="col-detail-close" onClick={onClose} aria-label={t('common.close')}><X size={16} /></button>
|
||||
{canEdit && onUploadImage && (
|
||||
<div style={{ position: 'absolute', top: 10, left: 10, display: 'flex', gap: 6, zIndex: 2 }}>
|
||||
<Tooltip label={place.image_url ? t('places.changeImage') : t('places.uploadImage')} placement="bottom">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { if (!imgBusy) coverInputRef.current?.click() }}
|
||||
aria-label={place.image_url ? t('places.changeImage') : t('places.uploadImage')}
|
||||
style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 30, height: 30, borderRadius: 8, border: 'none', cursor: imgBusy ? 'default' : 'pointer', background: 'rgba(0,0,0,0.55)', color: '#fff', backdropFilter: 'blur(4px)' }}
|
||||
>
|
||||
{imgBusy ? <Loader2 size={15} className="animate-spin" /> : <Camera size={15} />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{place.image_url && !imgBusy && (
|
||||
<Tooltip label={t('places.removeImage')} placement="bottom">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleImageRemove}
|
||||
aria-label={t('places.removeImage')}
|
||||
style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 30, height: 30, borderRadius: 8, border: 'none', cursor: 'pointer', background: 'rgba(0,0,0,0.55)', color: '#fff', backdropFilter: 'blur(4px)' }}
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{/* Chip and cover controls share the top bar. The controls keep the end and
|
||||
never shrink, so a long category name ellipsizes instead of sliding under
|
||||
them, however many buttons there are and whatever size phones give them. */}
|
||||
<div className="absolute left-[14px] right-[12px] top-[12px] z-[2] flex items-center gap-[8px]">
|
||||
{place.category?.name && (
|
||||
<span className="col-detail-cover-cat min-w-0" style={{ ['--cat' as string]: place.category.color || '#6366f1' }}>
|
||||
<CatIcon size={12} className="flex-none" />
|
||||
<span className="truncate">{place.category.name}</span>
|
||||
</span>
|
||||
)}
|
||||
{/* The cover controls wear the close button's class, so they get its look,
|
||||
hover and phone size. */}
|
||||
<div className="ms-auto flex flex-none gap-[6px]">
|
||||
{canEdit && onUploadImage && (
|
||||
<>
|
||||
<input ref={coverInputRef} type="file" accept="image/jpeg,image/png,image/gif,image/webp,.heic,.heif" style={{ display: 'none' }} onChange={handleCoverPick} />
|
||||
{place.image_url && !imgBusy && (
|
||||
<Tooltip label={t('places.removeImage')} placement="bottom">
|
||||
<button type="button" className="col-detail-close" onClick={handleImageRemove} aria-label={t('places.removeImage')}>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip label={place.image_url ? t('places.changeImage') : t('places.uploadImage')} placement="bottom">
|
||||
<button
|
||||
type="button"
|
||||
className="col-detail-close"
|
||||
style={imgBusy ? { cursor: 'default' } : undefined}
|
||||
onClick={() => { if (!imgBusy) coverInputRef.current?.click() }}
|
||||
aria-label={place.image_url ? t('places.changeImage') : t('places.uploadImage')}
|
||||
>
|
||||
{imgBusy ? <Loader2 size={16} className="animate-spin" /> : <Camera size={16} />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
</>
|
||||
)}
|
||||
<input ref={coverInputRef} type="file" accept="image/jpeg,image/png,image/gif,image/webp,.heic,.heif" style={{ display: 'none' }} onChange={handleCoverPick} />
|
||||
<button type="button" className="col-detail-close" onClick={onClose} aria-label={t('common.close')}><X size={16} /></button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="col-detail-head">
|
||||
{editing
|
||||
? <input value={name} onChange={e => setName(e.target.value)} className="col-detail-name-input" autoFocus aria-label={t('collections.listName')} />
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// FE-COMP-COLLIMPORT-001 to FE-COMP-COLLIMPORT-010
|
||||
// FE-COMP-COLLIMPORT-001 to FE-COMP-COLLIMPORT-026
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { CollectionFile } from '@trek/shared';
|
||||
import type { Collection, CollectionFile } from '@trek/shared';
|
||||
import { useTranslation } from '../../i18n/TranslationContext';
|
||||
import ImportCollectionModal from './ImportCollectionModal';
|
||||
import type { GpxReader } from './collectionFile';
|
||||
|
||||
// The modal takes `t` as a prop, so this harness forwards the real English
|
||||
// translator and the assertions read as the strings a person sees.
|
||||
@@ -23,6 +24,7 @@ const listFile: CollectionFile = {
|
||||
function renderModal(overrides: Partial<React.ComponentProps<typeof ImportCollectionModal>> = {}) {
|
||||
const props = {
|
||||
onImport: vi.fn().mockResolvedValue(undefined),
|
||||
onReadGpx: vi.fn().mockRejectedValue(new Error('no GPX expected here')),
|
||||
onClose: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
@@ -33,7 +35,7 @@ function renderModal(overrides: Partial<React.ComponentProps<typeof ImportCollec
|
||||
/** Put a file into the hidden input the way a file picker would. */
|
||||
async function choose(content: string, name = 'list.trekcollection.json') {
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
const file = new File([content], name, { type: 'application/json' });
|
||||
const file = new File([content], name, { type: name.endsWith('.gpx') ? 'application/gpx+xml' : 'application/json' });
|
||||
// jsdom's File has no usable text(); the component awaits it.
|
||||
Object.defineProperty(file, 'text', { value: () => Promise.resolve(content) });
|
||||
await userEvent.upload(input, file);
|
||||
@@ -45,7 +47,6 @@ describe('ImportCollectionModal (#2198)', () => {
|
||||
it('FE-COMP-COLLIMPORT-001: opens asking for a file, with Import not yet possible', () => {
|
||||
renderModal();
|
||||
expect(screen.getByText('Choose a list file')).toBeInTheDocument();
|
||||
expect(screen.getByText('.trekcollection.json')).toBeInTheDocument();
|
||||
expect(importButton()).toBeDisabled();
|
||||
});
|
||||
|
||||
@@ -142,3 +143,188 @@ describe('ImportCollectionModal (#2198)', () => {
|
||||
expect(props.onImport).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ImportCollectionModal with a GPX (#2301)', () => {
|
||||
const gpx = '<?xml version="1.0"?><gpx version="1.1"><wpt lat="1" lon="2"><name>Pena Palace</name></wpt></gpx>';
|
||||
const gpxFile: CollectionFile = {
|
||||
format: 'trek.collection', version: 1, name: 'Sintra loop',
|
||||
places: [{ name: 'Pena Palace' }, { name: 'Moorish Castle' }],
|
||||
} as CollectionFile;
|
||||
const refusal = (code: string) => Object.assign(new Error('Request failed'), { response: { status: 400, data: { error: 'no', code } } });
|
||||
|
||||
it('FE-COMP-COLLIMPORT-011: says which files it takes', () => {
|
||||
renderModal();
|
||||
expect(screen.getByText('.trekcollection.json · .gpx')).toBeInTheDocument();
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
expect(input.accept).toContain('.gpx');
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-012: shows what a GPX holds, and what of it will not become a place', async () => {
|
||||
const onReadGpx = vi.fn().mockResolvedValue({ file: gpxFile, skipped: 2, track_points: 8 });
|
||||
const props = renderModal({ onReadGpx });
|
||||
|
||||
await choose(gpx, 'sintra.gpx');
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Sintra loop')).toBeInTheDocument());
|
||||
expect(onReadGpx).toHaveBeenCalledWith(gpx, 'sintra.gpx');
|
||||
expect(screen.getByText('2 places')).toBeInTheDocument();
|
||||
expect(screen.getByText('2 waypoints without usable coordinates are left out.')).toBeInTheDocument();
|
||||
expect(screen.getByText('This file also has 8 track points. Tracks are not imported, only waypoints.')).toBeInTheDocument();
|
||||
// The note about ratings and members is about TREK files; a GPX never had any.
|
||||
expect(screen.queryByText(/Ratings, members/)).toBeNull();
|
||||
|
||||
await userEvent.click(importButton());
|
||||
await waitFor(() => expect(props.onImport).toHaveBeenCalledWith(gpxFile, undefined));
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-013: imports a GPX under a name the person typed', async () => {
|
||||
const props = renderModal({ onReadGpx: vi.fn().mockResolvedValue({ file: gpxFile, skipped: 0, track_points: 0 }) });
|
||||
await choose(gpx, 'sintra.gpx');
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Sintra loop')).toBeInTheDocument());
|
||||
|
||||
await userEvent.clear(screen.getByRole('textbox'));
|
||||
await userEvent.type(screen.getByRole('textbox'), 'Sintra with the kids');
|
||||
await userEvent.click(importButton());
|
||||
|
||||
await waitFor(() => expect(props.onImport).toHaveBeenCalledWith(gpxFile, 'Sintra with the kids'));
|
||||
expect(screen.queryByText(/track points/)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-014: will not make an empty list of a GPX that only has a track', async () => {
|
||||
const trackOnly = { ...gpxFile, places: [] };
|
||||
renderModal({ onReadGpx: vi.fn().mockResolvedValue({ file: trackOnly, skipped: 0, track_points: 120 }) });
|
||||
|
||||
await choose(gpx, 'track.gpx');
|
||||
|
||||
await waitFor(() => expect(screen.getByText('This GPX file has no waypoints, so there is nothing to import.')).toBeInTheDocument());
|
||||
expect(screen.getByText('This file also has 120 track points. Tracks are not imported, only waypoints.')).toBeInTheDocument();
|
||||
expect(importButton()).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-015: says in its own words why a GPX was refused', async () => {
|
||||
const onReadGpx = vi.fn()
|
||||
.mockRejectedValueOnce(refusal('not-gpx'))
|
||||
.mockRejectedValueOnce(refusal('too-many-places'))
|
||||
.mockRejectedValueOnce(refusal('unreadable'));
|
||||
renderModal({ onReadGpx });
|
||||
|
||||
await choose(gpx, 'a.gpx');
|
||||
await waitFor(() => expect(screen.getByText('That is not a GPX file.')).toBeInTheDocument());
|
||||
await choose(gpx, 'b.gpx');
|
||||
await waitFor(() => expect(screen.getByText(
|
||||
'That file has more than 1000 places. Split it and import the parts one at a time.',
|
||||
)).toBeInTheDocument());
|
||||
await choose(gpx, 'c.gpx');
|
||||
await waitFor(() => expect(screen.getByText('That file could not be read.')).toBeInTheDocument());
|
||||
expect(importButton()).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-016: says it is reading while the server reads, and why it could not', async () => {
|
||||
let fail: ((err: unknown) => void) | null = null;
|
||||
const onReadGpx = vi.fn<GpxReader>(() => new Promise((_, reject) => { fail = reject; }));
|
||||
renderModal({ onReadGpx });
|
||||
|
||||
await choose(gpx, 'slow.gpx');
|
||||
await waitFor(() => expect(screen.getByText('Reading the file…')).toBeInTheDocument());
|
||||
|
||||
fail!(Object.assign(new Error('x'), { response: { status: 503, data: { error: 'The server is busy' } } }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('The server is busy')).toBeInTheDocument());
|
||||
expect(screen.getByText('Choose a list file')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ── The same file into a list that is already there (#2301 follow-up) ────────
|
||||
|
||||
describe('ImportCollectionModal into an existing list', () => {
|
||||
const lists = [
|
||||
{ id: 7, owner_id: 1, name: 'Lisbon 2027', color: '#22c55e', place_count: 4 },
|
||||
{ id: 9, owner_id: 1, name: 'Porto', color: '#3b82f6', place_count: 2 },
|
||||
] as Collection[];
|
||||
|
||||
const intoProps = (over: Partial<React.ComponentProps<typeof ImportCollectionModal>> = {}) =>
|
||||
renderModal({ onImportInto: vi.fn().mockResolvedValue(undefined), lists, ...over });
|
||||
|
||||
it('FE-COMP-COLLIMPORT-020: offers the choice only once a file has been read', async () => {
|
||||
intoProps();
|
||||
expect(screen.queryByText('Add to a list')).not.toBeInTheDocument();
|
||||
|
||||
await choose(JSON.stringify(listFile));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Add to a list')).toBeInTheDocument());
|
||||
expect(screen.getByText('New list')).toBeInTheDocument();
|
||||
// A new list stays the default, so nothing changes for anyone who ignores it.
|
||||
expect(screen.getByDisplayValue('Lisbon')).toBeInTheDocument();
|
||||
expect(importButton()).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-021: keeps to a new list when there is nothing to add to', async () => {
|
||||
renderModal({ onImportInto: vi.fn(), lists: [] });
|
||||
await choose(JSON.stringify(listFile));
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Lisbon')).toBeInTheDocument());
|
||||
|
||||
expect(screen.queryByText('Add to a list')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-022: adds the file to the list that was picked, and asks for no name', async () => {
|
||||
const props = intoProps();
|
||||
await choose(JSON.stringify(listFile));
|
||||
await waitFor(() => expect(screen.getByText('Add to a list')).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByText('Add to a list'));
|
||||
expect(screen.queryByDisplayValue('Lisbon')).not.toBeInTheDocument();
|
||||
await userEvent.click(screen.getByText('Porto'));
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Add to list' }));
|
||||
|
||||
await waitFor(() => expect(props.onImportInto).toHaveBeenCalledWith(expect.objectContaining({ name: 'Lisbon' }), 9));
|
||||
expect(props.onImport).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-023: starts on the list that is open, whatever order they come in', async () => {
|
||||
const props = intoProps({ defaultListId: 9 });
|
||||
await choose(JSON.stringify(listFile));
|
||||
await waitFor(() => expect(screen.getByText('Add to a list')).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByText('Add to a list'));
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Add to list' }));
|
||||
|
||||
await waitFor(() => expect(props.onImportInto).toHaveBeenCalledWith(expect.anything(), 9));
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-024: says what adding to a list does and does not do', async () => {
|
||||
intoProps();
|
||||
await choose(JSON.stringify(listFile));
|
||||
await waitFor(() => expect(screen.getByText('Add to a list')).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByText('Add to a list'));
|
||||
|
||||
expect(screen.getByText(/Places the list already has stay as they are/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-025: keeps the dialog open and says why when adding fails', async () => {
|
||||
const onImportInto = vi.fn().mockRejectedValue(
|
||||
Object.assign(new Error('x'), { response: { status: 403, data: { error: 'You have read-only access to this list' } } }),
|
||||
);
|
||||
intoProps({ onImportInto });
|
||||
await choose(JSON.stringify(listFile));
|
||||
await waitFor(() => expect(screen.getByText('Add to a list')).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByText('Add to a list'));
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Add to list' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('You have read-only access to this list')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-026: goes back to a new list with the name it started with', async () => {
|
||||
const props = intoProps();
|
||||
await choose(JSON.stringify(listFile));
|
||||
await waitFor(() => expect(screen.getByText('Add to a list')).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByText('Add to a list'));
|
||||
await userEvent.click(screen.getByText('New list'));
|
||||
await userEvent.click(importButton());
|
||||
|
||||
await waitFor(() => expect(props.onImport).toHaveBeenCalledWith(expect.objectContaining({ name: 'Lisbon' }), undefined));
|
||||
expect(props.onImportInto).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,19 +1,152 @@
|
||||
import React, { useRef, useState } from 'react'
|
||||
import { Upload, FileJson, Loader2, MapPin, Tag, AlertCircle } from 'lucide-react'
|
||||
import React, { useMemo, useRef, useState } from 'react'
|
||||
import { Upload, FileJson, Loader2, MapPin, Tag, AlertCircle, Route, Info, Plus, FolderInput, Check, Search, Bookmark } from 'lucide-react'
|
||||
import Modal from '../shared/Modal'
|
||||
import type { CollectionFile } from '@trek/shared'
|
||||
import { MAX_COLLECTION_FILE_PLACES, type Collection, type CollectionFile } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import { readCollectionFile, type CollectionFileError, COLLECTION_FILE_EXTENSION } from './collectionFile'
|
||||
import {
|
||||
readCollectionFile,
|
||||
type CollectionFileError,
|
||||
type GpxLeftovers,
|
||||
type GpxReader,
|
||||
COLLECTION_FILE_EXTENSION,
|
||||
COLLECTION_GPX_EXTENSION,
|
||||
} from './collectionFile'
|
||||
|
||||
interface ImportCollectionModalProps {
|
||||
onImport: (file: CollectionFile, name?: string) => Promise<void>
|
||||
/** Adds the file to a list that is already there. Without it the dialog only makes new ones. */
|
||||
onImportInto?: (file: CollectionFile, collectionId: number) => Promise<void>
|
||||
/** The lists this person may add to; the server applies the same rule again. */
|
||||
lists?: Collection[]
|
||||
/** The list that is open, so the obvious target is the one already selected. */
|
||||
defaultListId?: number | null
|
||||
/** Reads a GPX into a list file (#2301); the server does the parsing. */
|
||||
onReadGpx: GpxReader
|
||||
onClose: () => void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
/** Keyed by the error type, so a new way for a file to fail does not build without its words. */
|
||||
const ERROR_KEYS: Record<CollectionFileError, string> = {
|
||||
'too-large': 'collections.file.errorTooLarge',
|
||||
unreadable: 'collections.file.errorUnreadable',
|
||||
'not-a-collection': 'collections.file.errorNotACollection',
|
||||
'not-gpx': 'collections.file.errorNotGpx',
|
||||
'too-many-places': 'collections.file.errorTooManyPlaces',
|
||||
}
|
||||
|
||||
/** What a GPX held besides its places, said before anything is imported. */
|
||||
function GpxNotes({ leftovers, placeCount, t }: { leftovers: GpxLeftovers; placeCount: number; t: TranslationFn }) {
|
||||
const notes = [
|
||||
placeCount === 0 && t('collections.file.gpxEmpty'),
|
||||
leftovers.skipped > 0 && t('collections.file.gpxSkipped', { count: leftovers.skipped }),
|
||||
leftovers.trackPoints > 0 && t('collections.file.gpxTrack', { count: leftovers.trackPoints }),
|
||||
].filter(Boolean)
|
||||
if (notes.length === 0) return null
|
||||
return (
|
||||
<ul className="flex flex-col gap-1">
|
||||
{notes.map(note => (
|
||||
<li key={note as string} className="flex items-start gap-2 text-[12px] text-content-muted">
|
||||
<Info size={13} className="shrink-0 mt-0.5 text-content-faint" />
|
||||
<span>{note}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/** One of the two answers to "where do these places go", as a card you can tap. */
|
||||
function TargetCard({ active, icon: Icon, title, hint, onClick }: {
|
||||
active: boolean
|
||||
icon: typeof Plus
|
||||
title: string
|
||||
hint: string
|
||||
onClick: () => void
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-pressed={active}
|
||||
className={`relative flex flex-col items-start gap-1.5 px-3 py-3 rounded-xl border text-left transition-colors ${
|
||||
active ? 'border-accent bg-surface-hover' : 'border-edge hover:bg-surface-hover'
|
||||
}`}
|
||||
>
|
||||
<span className={`w-8 h-8 rounded-lg flex items-center justify-center ${active ? 'bg-accent text-accent-text' : 'bg-surface-input text-content-muted'}`}>
|
||||
<Icon size={15} />
|
||||
</span>
|
||||
<span className="text-[13px] font-semibold text-content">{title}</span>
|
||||
<span className="text-[11.5px] text-content-faint leading-snug">{hint}</span>
|
||||
{active && (
|
||||
<span className="absolute top-2 right-2 w-4 h-4 rounded-full bg-accent text-accent-text flex items-center justify-center">
|
||||
<Check size={11} strokeWidth={3} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** The lists the file may be added to, the open one first. */
|
||||
function ListChoice({ lists, selectedId, onSelect, t }: {
|
||||
lists: Collection[]
|
||||
selectedId: number | null
|
||||
onSelect: (id: number) => void
|
||||
t: TranslationFn
|
||||
}) {
|
||||
const [search, setSearch] = useState('')
|
||||
const shown = useMemo(() => {
|
||||
const q = search.trim().toLowerCase()
|
||||
return q ? lists.filter(l => l.name.toLowerCase().includes(q)) : lists
|
||||
}, [lists, search])
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
{lists.length > 5 && (
|
||||
<div className="relative">
|
||||
<Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-content-faint" />
|
||||
<input
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('collections.file.searchLists')}
|
||||
className="w-full pl-8 pr-3 py-2 rounded-lg border border-edge bg-surface-input text-content text-[13px] outline-none focus:border-accent"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col gap-1 max-h-[34vh] overflow-y-auto -mx-1 px-1">
|
||||
{shown.map(list => {
|
||||
const active = list.id === selectedId
|
||||
return (
|
||||
<button
|
||||
key={list.id}
|
||||
type="button"
|
||||
onClick={() => onSelect(list.id)}
|
||||
aria-pressed={active}
|
||||
className={`flex items-center gap-3 px-3 py-2.5 rounded-xl border text-left transition-colors ${
|
||||
active ? 'border-accent bg-surface-hover' : 'border-edge bg-surface-card hover:bg-surface-hover'
|
||||
}`}
|
||||
>
|
||||
<span className="w-9 h-9 min-w-[36px] rounded-lg flex items-center justify-center shrink-0 text-white" style={{ background: list.color || '#6366f1' }}>
|
||||
<Bookmark size={15} />
|
||||
</span>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block text-[13px] font-semibold text-content truncate">{list.name}</span>
|
||||
<span className="block text-[11.5px] text-content-faint">{t('collections.placeCount', { count: list.place_count ?? 0 })}</span>
|
||||
</span>
|
||||
{active && <Check size={16} className="shrink-0 text-accent" />}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{shown.length === 0 && (
|
||||
<p className="text-center text-[13px] text-content-faint py-6">{t('collections.noOtherLists')}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a list file and make a list of it (#2198).
|
||||
* Read a list file or a GPX and make a list of it (#2198, #2301).
|
||||
*
|
||||
* Two steps on purpose. A file from somebody else is an unknown quantity, so
|
||||
* it is read and shown first — how many places, which labels, what the list is
|
||||
@@ -22,27 +155,58 @@ interface ImportCollectionModalProps {
|
||||
* "Lisbon (from Ana)" on the way in, and renaming it afterwards means finding
|
||||
* the list editor.
|
||||
*
|
||||
* The file never leaves the browser as a file: it is parsed here, and what
|
||||
* goes to the server is the parsed list, through the same contract the server
|
||||
* validates against.
|
||||
* A list file never leaves the browser as a file: it is parsed here. A GPX is
|
||||
* read by the server into the same kind of list file, and from then on the two
|
||||
* are one path: what goes to the import is a list file, through the same
|
||||
* contract the server validates against.
|
||||
*
|
||||
* The file can go into a list that is already there instead of a new one. That
|
||||
* is a choice rather than the default, because the two do different things: a
|
||||
* new list is the file as it stands, while adding to a list leaves everything
|
||||
* in it alone and skips the places it already has.
|
||||
*/
|
||||
export default function ImportCollectionModal({ onImport, onClose, t }: ImportCollectionModalProps): React.ReactElement {
|
||||
export default function ImportCollectionModal({
|
||||
onImport, onImportInto, lists, defaultListId, onReadGpx, onClose, t,
|
||||
}: ImportCollectionModalProps): React.ReactElement {
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const [file, setFile] = useState<CollectionFile | null>(null)
|
||||
const [leftovers, setLeftovers] = useState<GpxLeftovers | null>(null)
|
||||
const [name, setName] = useState('')
|
||||
const [error, setError] = useState<CollectionFileError | 'failed' | null>(null)
|
||||
const [failedMessage, setFailedMessage] = useState<string | null>(null)
|
||||
const [reading, setReading] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [dragging, setDragging] = useState(false)
|
||||
const [target, setTarget] = useState<'new' | 'existing'>('new')
|
||||
// The open list first: it is the one somebody importing from inside a list means.
|
||||
const targets = useMemo(() => {
|
||||
const all = lists ?? []
|
||||
const open = all.find(l => l.id === defaultListId)
|
||||
return open ? [open, ...all.filter(l => l.id !== open.id)] : all
|
||||
}, [lists, defaultListId])
|
||||
const [listId, setListId] = useState<number | null>(() => targets[0]?.id ?? null)
|
||||
const canChoose = !!onImportInto && targets.length > 0
|
||||
const intoExisting = canChoose && target === 'existing'
|
||||
|
||||
const take = async (chosen: File | undefined) => {
|
||||
if (!chosen) return
|
||||
if (!chosen || reading) return
|
||||
setError(null)
|
||||
setFailedMessage(null)
|
||||
const result = await readCollectionFile(chosen)
|
||||
setFile(result.file)
|
||||
setError(result.error)
|
||||
if (result.file) setName(result.file.name)
|
||||
setReading(true)
|
||||
try {
|
||||
const result = await readCollectionFile(chosen, onReadGpx)
|
||||
setFile(result.file)
|
||||
setLeftovers(result.gpx ?? null)
|
||||
setError(result.error)
|
||||
if (result.file) setName(result.file.name)
|
||||
} catch (err) {
|
||||
setFile(null)
|
||||
setLeftovers(null)
|
||||
setError('failed')
|
||||
setFailedMessage(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setReading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const onDrop = (e: React.DragEvent) => {
|
||||
@@ -57,8 +221,12 @@ export default function ImportCollectionModal({ onImport, onClose, t }: ImportCo
|
||||
setError(null)
|
||||
setFailedMessage(null)
|
||||
try {
|
||||
const trimmed = name.trim()
|
||||
await onImport(file, trimmed && trimmed !== file.name ? trimmed : undefined)
|
||||
if (intoExisting && listId != null) {
|
||||
await onImportInto!(file, listId)
|
||||
} else {
|
||||
const trimmed = name.trim()
|
||||
await onImport(file, trimmed && trimmed !== file.name ? trimmed : undefined)
|
||||
}
|
||||
} catch (err) {
|
||||
setError('failed')
|
||||
setFailedMessage(getApiErrorMessage(err, t('common.error')))
|
||||
@@ -69,10 +237,10 @@ export default function ImportCollectionModal({ onImport, onClose, t }: ImportCo
|
||||
|
||||
const errorText = error === 'failed'
|
||||
? (failedMessage ?? t('common.error'))
|
||||
: error === 'too-large' ? t('collections.file.errorTooLarge')
|
||||
: error === 'unreadable' ? t('collections.file.errorUnreadable')
|
||||
: error === 'not-a-collection' ? t('collections.file.errorNotACollection')
|
||||
: null
|
||||
: error ? t(ERROR_KEYS[error], { count: MAX_COLLECTION_FILE_PLACES }) : null
|
||||
|
||||
// A GPX of nothing but a track would make an empty list, which is never what was meant.
|
||||
const nothingToImport = !!leftovers && !!file && file.places.length === 0
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -88,11 +256,11 @@ export default function ImportCollectionModal({ onImport, onClose, t }: ImportCo
|
||||
<button
|
||||
type="button"
|
||||
onClick={submit}
|
||||
disabled={!file || busy || !name.trim()}
|
||||
disabled={!file || busy || nothingToImport || (intoExisting ? listId == null : !name.trim())}
|
||||
className="px-4 py-2 rounded-lg text-[13px] font-semibold bg-accent text-accent-text disabled:opacity-50 transition-opacity inline-flex items-center gap-2"
|
||||
>
|
||||
{busy && <Loader2 size={14} className="animate-spin" />}
|
||||
{t('collections.file.confirm')}
|
||||
{intoExisting ? t('collections.file.confirmInto') : t('collections.file.confirm')}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
@@ -101,7 +269,7 @@ export default function ImportCollectionModal({ onImport, onClose, t }: ImportCo
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept=".json,application/json"
|
||||
accept=".json,application/json,.gpx,application/gpx+xml"
|
||||
className="hidden"
|
||||
onChange={e => { void take(e.target.files?.[0]); e.target.value = '' }}
|
||||
/>
|
||||
@@ -113,19 +281,23 @@ export default function ImportCollectionModal({ onImport, onClose, t }: ImportCo
|
||||
onDragOver={e => { e.preventDefault(); setDragging(true) }}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={onDrop}
|
||||
disabled={reading}
|
||||
aria-busy={reading}
|
||||
className={`flex flex-col items-center justify-center gap-2 px-4 py-10 rounded-xl border border-dashed transition-colors ${
|
||||
dragging ? 'border-accent bg-surface-hover' : 'border-edge hover:bg-surface-hover'
|
||||
}`}
|
||||
>
|
||||
<Upload size={22} className="text-content-faint" />
|
||||
<span className="text-[13px] font-medium text-content">{t('collections.file.choose')}</span>
|
||||
<span className="text-[11.5px] text-content-faint">{COLLECTION_FILE_EXTENSION}</span>
|
||||
{reading ? <Loader2 size={22} className="text-content-faint animate-spin" /> : <Upload size={22} className="text-content-faint" />}
|
||||
<span className="text-[13px] font-medium text-content">
|
||||
{reading ? t('collections.file.reading') : t('collections.file.choose')}
|
||||
</span>
|
||||
<span className="text-[11.5px] text-content-faint">{COLLECTION_FILE_EXTENSION} · {COLLECTION_GPX_EXTENSION}</span>
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-3 px-3 py-2.5 rounded-xl border border-edge bg-surface-card">
|
||||
<span className="w-9 h-9 min-w-[36px] rounded-lg flex items-center justify-center shrink-0 text-white" style={{ background: file.color || '#6366f1' }}>
|
||||
<FileJson size={15} />
|
||||
{leftovers ? <Route size={15} /> : <FileJson size={15} />}
|
||||
</span>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block text-[13px] font-semibold text-content truncate">{file.name}</span>
|
||||
@@ -145,17 +317,47 @@ export default function ImportCollectionModal({ onImport, onClose, t }: ImportCo
|
||||
<p className="text-[12px] text-content-muted whitespace-pre-wrap">{file.description}</p>
|
||||
)}
|
||||
|
||||
<label className="flex flex-col gap-1.5">
|
||||
<span className="text-[12px] font-medium text-content-muted">{t('collections.listName')}</span>
|
||||
<input
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
maxLength={120}
|
||||
className="w-full px-3 py-2 rounded-lg border border-edge bg-surface-input text-content text-[13px] outline-none focus:border-accent"
|
||||
/>
|
||||
</label>
|
||||
{leftovers && <GpxNotes leftovers={leftovers} placeCount={file.places.length} t={t} />}
|
||||
|
||||
<p className="text-[11.5px] text-content-faint">{t('collections.file.hint')}</p>
|
||||
{canChoose && (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<TargetCard
|
||||
active={target === 'new'}
|
||||
icon={Plus}
|
||||
title={t('collections.file.targetNew')}
|
||||
hint={t('collections.file.targetNewHint')}
|
||||
onClick={() => setTarget('new')}
|
||||
/>
|
||||
<TargetCard
|
||||
active={intoExisting}
|
||||
icon={FolderInput}
|
||||
title={t('collections.file.targetExisting')}
|
||||
hint={t('collections.file.targetExistingHint')}
|
||||
onClick={() => setTarget('existing')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{intoExisting ? (
|
||||
<>
|
||||
<ListChoice lists={targets} selectedId={listId} onSelect={setListId} t={t} />
|
||||
<p className="text-[11.5px] text-content-faint">{t('collections.file.intoHint')}</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<label className="flex flex-col gap-1.5">
|
||||
<span className="text-[12px] font-medium text-content-muted">{t('collections.listName')}</span>
|
||||
<input
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
maxLength={120}
|
||||
className="w-full px-3 py-2 rounded-lg border border-edge bg-surface-input text-content text-[13px] outline-none focus:border-accent"
|
||||
/>
|
||||
</label>
|
||||
|
||||
{!leftovers && <p className="text-[11.5px] text-content-faint">{t('collections.file.hint')}</p>}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
// FE-COLL-FILE-001 to FE-COLL-FILE-012
|
||||
// FE-COLL-FILE-001 to FE-COLL-FILE-020
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { collectionFileName, downloadCollectionFile, readCollectionFile, COLLECTION_FILE_EXTENSION } from './collectionFile'
|
||||
import {
|
||||
collectionFileName,
|
||||
downloadCollectionFile,
|
||||
downloadCollectionGpx,
|
||||
readCollectionFile,
|
||||
COLLECTION_FILE_EXTENSION,
|
||||
COLLECTION_GPX_EXTENSION,
|
||||
type GpxReader,
|
||||
} from './collectionFile'
|
||||
import type { CollectionFile } from '@trek/shared'
|
||||
|
||||
const file = (over: Partial<CollectionFile> = {}): CollectionFile => ({
|
||||
@@ -8,10 +16,16 @@ const file = (over: Partial<CollectionFile> = {}): CollectionFile => ({
|
||||
} as CollectionFile)
|
||||
|
||||
/** A File whose text() the jsdom build does not provide on its own. */
|
||||
function asFile(content: string, size = content.length): File {
|
||||
return { size, text: () => Promise.resolve(content) } as unknown as File
|
||||
function asFile(content: string, size = content.length, name = 'list.trekcollection.json'): File {
|
||||
return { size, name, text: () => Promise.resolve(content) } as unknown as File
|
||||
}
|
||||
|
||||
/** A reader that must not be reached: a list file is never sent to the server. */
|
||||
const noGpx: GpxReader = () => { throw new Error('a list file went to the GPX reader') }
|
||||
|
||||
/** A rejection the way axios delivers the server's refusal. */
|
||||
const refused = (code: string) => Object.assign(new Error('Request failed'), { response: { status: 400, data: { error: 'no', code } } })
|
||||
|
||||
describe('collectionFileName', () => {
|
||||
it('FE-COLL-FILE-001: turns a list name into a short ascii file name', () => {
|
||||
expect(collectionFileName('Lisbon')).toBe('lisbon' + COLLECTION_FILE_EXTENSION)
|
||||
@@ -23,69 +37,94 @@ describe('collectionFileName', () => {
|
||||
const name = collectionFileName('a'.repeat(200))
|
||||
expect(name).toBe('a'.repeat(40) + COLLECTION_FILE_EXTENSION)
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-013: names a GPX the same way, with its own extension', () => {
|
||||
expect(collectionFileName('Wochenende in Rom!', COLLECTION_GPX_EXTENSION)).toBe('wochenende-in-rom.gpx')
|
||||
})
|
||||
})
|
||||
|
||||
describe('downloadCollectionFile', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
describe('downloads', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-003: hands the browser a named JSON blob and releases it afterwards', () => {
|
||||
/** Captures what would be downloaded, and under which name. */
|
||||
function captureDownload() {
|
||||
vi.useFakeTimers()
|
||||
const revoke = vi.fn()
|
||||
const created: Blob[] = []
|
||||
const names: string[] = []
|
||||
vi.stubGlobal('URL', {
|
||||
createObjectURL: (b: Blob) => { created.push(b); return 'blob:x' },
|
||||
revokeObjectURL: revoke,
|
||||
})
|
||||
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
|
||||
expect(this.download).toBe('lisbon' + COLLECTION_FILE_EXTENSION)
|
||||
expect(this.href).toContain('blob:')
|
||||
names.push(this.download)
|
||||
})
|
||||
return { revoke, created, names, click }
|
||||
}
|
||||
|
||||
it('FE-COLL-FILE-003: hands the browser a named JSON blob and releases it afterwards', () => {
|
||||
const { revoke, created, names, click } = captureDownload()
|
||||
|
||||
downloadCollectionFile(file())
|
||||
|
||||
expect(click).toHaveBeenCalledTimes(1)
|
||||
expect(names).toEqual(['lisbon' + COLLECTION_FILE_EXTENSION])
|
||||
expect(created[0].type).toBe('application/json')
|
||||
expect(document.querySelector('a')).toBeNull()
|
||||
expect(revoke).not.toHaveBeenCalled()
|
||||
vi.runAllTimers()
|
||||
expect(revoke).toHaveBeenCalledWith('blob:x')
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-014: hands the browser a GPX under the list name', async () => {
|
||||
const { created, names } = captureDownload()
|
||||
|
||||
downloadCollectionGpx('Lisbon', '<gpx/>')
|
||||
|
||||
expect(names).toEqual(['lisbon.gpx'])
|
||||
expect(created[0].type).toBe('application/gpx+xml')
|
||||
expect(await created[0].text()).toBe('<gpx/>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('readCollectionFile', () => {
|
||||
it('FE-COLL-FILE-004: reads one of ours', async () => {
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file())))
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file())), noGpx)
|
||||
expect(result.error).toBeNull()
|
||||
expect(result.file?.name).toBe('Lisbon')
|
||||
expect(result.gpx).toBeUndefined()
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-005: refuses a file too large to be one, without reading it', async () => {
|
||||
const text = vi.fn()
|
||||
const huge = { size: 1024 * 1024 + 1, text } as unknown as File
|
||||
const result = await readCollectionFile(huge)
|
||||
const result = await readCollectionFile(huge, noGpx)
|
||||
expect(result).toEqual({ file: null, error: 'too-large' })
|
||||
expect(text).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-006: says a file is unreadable when it is not JSON', async () => {
|
||||
expect(await readCollectionFile(asFile('not json at all'))).toEqual({ file: null, error: 'unreadable' })
|
||||
expect(await readCollectionFile(asFile('not json at all'), noGpx)).toEqual({ file: null, error: 'unreadable' })
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-007: says a JSON that is not a list is not a list', async () => {
|
||||
for (const content of ['{}', '[]', 'null', '"a string"', JSON.stringify({ format: 'something.else', version: 1, name: 'x', places: [] })]) {
|
||||
expect(await readCollectionFile(asFile(content)), content).toEqual({ file: null, error: 'not-a-collection' })
|
||||
expect(await readCollectionFile(asFile(content), noGpx), content).toEqual({ file: null, error: 'not-a-collection' })
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-008: refuses a list with no name, since the list would have none', async () => {
|
||||
const result = await readCollectionFile(asFile(JSON.stringify({ format: 'trek.collection', version: 1, name: '', places: [] })))
|
||||
const result = await readCollectionFile(asFile(JSON.stringify({ format: 'trek.collection', version: 1, name: '', places: [] })), noGpx)
|
||||
expect(result.error).toBe('not-a-collection')
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-009: reads an empty list, which is a list somebody has not filled yet', async () => {
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file({ places: [] }))))
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file({ places: [] }))), noGpx)
|
||||
expect(result.error).toBeNull()
|
||||
expect(result.file?.places).toEqual([])
|
||||
})
|
||||
@@ -94,20 +133,66 @@ describe('readCollectionFile', () => {
|
||||
// The envelope counts places; each one is validated where it is written.
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file({
|
||||
places: [{ name: 'Fine' }, { nonsense: true }] as never,
|
||||
}))))
|
||||
}))), noGpx)
|
||||
expect(result.error).toBeNull()
|
||||
expect(result.file?.places).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-011: refuses a file carrying more places than the contract allows', async () => {
|
||||
const tooMany = Array.from({ length: 1001 }, (_, i) => ({ name: `Place ${i}` }))
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file({ places: tooMany as never }))))
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file({ places: tooMany as never }))), noGpx)
|
||||
expect(result.error).toBe('not-a-collection')
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-012: reads a file from a later version, since its additions are optional', async () => {
|
||||
const result = await readCollectionFile(asFile(JSON.stringify({ ...file(), version: 99, somethingNew: 'x' })))
|
||||
const result = await readCollectionFile(asFile(JSON.stringify({ ...file(), version: 99, somethingNew: 'x' })), noGpx)
|
||||
expect(result.error).toBeNull()
|
||||
expect(result.file?.version).toBe(99)
|
||||
})
|
||||
})
|
||||
|
||||
describe('readCollectionFile with a GPX (#2301)', () => {
|
||||
const gpx = '<?xml version="1.0"?><gpx version="1.1"><wpt lat="1" lon="2"><name>A</name></wpt></gpx>'
|
||||
|
||||
it('FE-COLL-FILE-015: sends a GPX to the reader with its file name and keeps what did not become a place', async () => {
|
||||
const read = vi.fn<GpxReader>().mockResolvedValue({ file: file({ name: 'Favourites' }), skipped: 2, track_points: 40 })
|
||||
|
||||
const result = await readCollectionFile(asFile(gpx, gpx.length, 'favourites.gpx'), read)
|
||||
|
||||
expect(read).toHaveBeenCalledWith(gpx, 'favourites.gpx')
|
||||
expect(result).toEqual({ file: expect.objectContaining({ name: 'Favourites' }), error: null, gpx: { skipped: 2, trackPoints: 40 } })
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-016: knows a GPX by what it is, not by what it is called', async () => {
|
||||
const read = vi.fn<GpxReader>().mockResolvedValue({ file: file(), skipped: 0, track_points: 0 })
|
||||
// A byte-order mark and a blank line before the declaration, under a .xml name.
|
||||
await readCollectionFile(asFile(String.fromCharCode(0xfeff) + '\n ' + gpx, 100, 'export.xml'), read)
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-017: holds a GPX to the same size limit, before reading it', async () => {
|
||||
const read = vi.fn<GpxReader>()
|
||||
expect(await readCollectionFile(asFile(gpx, 1024 * 1024 + 1, 'big.gpx'), read)).toEqual({ file: null, error: 'too-large' })
|
||||
expect(read).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-018: turns the reason the server refused a GPX into the dialog\'s own', async () => {
|
||||
for (const code of ['unreadable', 'not-gpx', 'too-many-places', 'too-large'] as const) {
|
||||
const read = vi.fn<GpxReader>().mockRejectedValue(refused(code))
|
||||
expect(await readCollectionFile(asFile(gpx), read), code).toEqual({ file: null, error: code, gpx: null })
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-019: passes on a failure that was not about the file', async () => {
|
||||
const offline = vi.fn<GpxReader>().mockRejectedValue(new Error('Network Error'))
|
||||
await expect(readCollectionFile(asFile(gpx), offline)).rejects.toThrow('Network Error')
|
||||
|
||||
const unknownCode = vi.fn<GpxReader>().mockRejectedValue(refused('something-new'))
|
||||
await expect(readCollectionFile(asFile(gpx), unknownCode)).rejects.toThrow('Request failed')
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-020: says a file is unreadable when its text cannot be had at all', async () => {
|
||||
const broken = { size: 10, name: 'x.gpx', text: () => Promise.reject(new Error('gone')) } as unknown as File
|
||||
expect(await readCollectionFile(broken, noGpx)).toEqual({ file: null, error: 'unreadable' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,34 +1,46 @@
|
||||
import { collectionFileSchema, MAX_COLLECTION_FILE_BYTES, type CollectionFile } from '@trek/shared'
|
||||
import {
|
||||
COLLECTION_GPX_PROBLEMS,
|
||||
collectionFileSchema,
|
||||
MAX_COLLECTION_FILE_BYTES,
|
||||
type CollectionFile,
|
||||
type CollectionGpxProblem,
|
||||
type CollectionGpxReadResult,
|
||||
} from '@trek/shared'
|
||||
|
||||
/**
|
||||
* The browser half of list export and import (#2198).
|
||||
* The browser half of list export and import (#2198, #2301).
|
||||
*
|
||||
* The file itself is built by the server, which is also where the decision
|
||||
* about what may leave the instance lives (`collection-file.schema.ts`). This
|
||||
* module only hands the JSON to the browser as a download, and reads a chosen
|
||||
* file back into something the import request will accept.
|
||||
* Both files are built by the server, which is also where the decision about
|
||||
* what may leave the instance lives (`collection-file.schema.ts`). This module
|
||||
* only hands one to the browser as a download, and reads a chosen file back
|
||||
* into something the import request will accept.
|
||||
*
|
||||
* A file that arrives here is a stranger's JSON and is treated as one: read
|
||||
* locally, never uploaded, parsed rather than evaluated, size-capped before
|
||||
* parsing, and put through the shared contract so a field this build does not
|
||||
* know is dropped instead of travelling on to the server.
|
||||
* A file that arrives here is a stranger's and is treated as one. A list file
|
||||
* is read locally, never uploaded, parsed rather than evaluated, size-capped
|
||||
* before parsing, and put through the shared contract so a field this build
|
||||
* does not know is dropped instead of travelling on. A GPX is size-capped the
|
||||
* same way and then sent as text to the server, which reads it with the XML
|
||||
* library the trip importer already uses and hands back a list file: one side
|
||||
* that parses XML, and it is the one that enforces the limits.
|
||||
*/
|
||||
|
||||
export const COLLECTION_FILE_EXTENSION = '.trekcollection.json'
|
||||
export const COLLECTION_GPX_EXTENSION = '.gpx'
|
||||
|
||||
/** The two ways a list can leave: whole, for another TREK, or as waypoints for everything else. */
|
||||
export type CollectionExportFormat = 'trek' | 'gpx'
|
||||
|
||||
/** A file name from a list name: lowercase, ascii-ish, short. */
|
||||
export function collectionFileName(name: string): string {
|
||||
export function collectionFileName(name: string, extension = COLLECTION_FILE_EXTENSION): string {
|
||||
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40)
|
||||
return `${slug || 'collection'}${COLLECTION_FILE_EXTENSION}`
|
||||
return `${slug || 'collection'}${extension}`
|
||||
}
|
||||
|
||||
/** Hand the file to the browser as a download. */
|
||||
export function downloadCollectionFile(file: CollectionFile): void {
|
||||
const json = JSON.stringify(file, null, 2)
|
||||
const url = URL.createObjectURL(new Blob([json], { type: 'application/json' }))
|
||||
function download(content: string, type: string, fileName: string): void {
|
||||
const url = URL.createObjectURL(new Blob([content], { type }))
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = collectionFileName(file.name)
|
||||
a.download = fileName
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
@@ -37,12 +49,30 @@ export function downloadCollectionFile(file: CollectionFile): void {
|
||||
setTimeout(() => URL.revokeObjectURL(url), 0)
|
||||
}
|
||||
|
||||
export type CollectionFileError = 'too-large' | 'unreadable' | 'not-a-collection'
|
||||
/** Hand the file to the browser as a download. */
|
||||
export function downloadCollectionFile(file: CollectionFile): void {
|
||||
download(JSON.stringify(file, null, 2), 'application/json', collectionFileName(file.name))
|
||||
}
|
||||
|
||||
/** Hand a list's GPX to the browser as a download, named like its list file would be. */
|
||||
export function downloadCollectionGpx(listName: string, gpx: string): void {
|
||||
download(gpx, 'application/gpx+xml', collectionFileName(listName, COLLECTION_GPX_EXTENSION))
|
||||
}
|
||||
|
||||
export type CollectionFileError = 'not-a-collection' | CollectionGpxProblem
|
||||
|
||||
/** What a GPX held that did not become a place. */
|
||||
export interface GpxLeftovers {
|
||||
/** Waypoints without usable coordinates. */
|
||||
skipped: number
|
||||
/** Track points and unnamed route points: lines, not places. */
|
||||
trackPoints: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Exactly one of the two is set.
|
||||
* Exactly one of `file` and `error` is set; `gpx` only when the file was one.
|
||||
*
|
||||
* Two nullable fields rather than a discriminated union on an `ok` flag: the
|
||||
* Nullable fields rather than a discriminated union on an `ok` flag: the
|
||||
* client compiles with `strict: false`, and without `strictNullChecks` a
|
||||
* `{ok: true} | {ok: false}` union does not narrow, so every read of the
|
||||
* failure branch would need a cast.
|
||||
@@ -50,20 +80,57 @@ export type CollectionFileError = 'too-large' | 'unreadable' | 'not-a-collection
|
||||
export interface ParsedCollectionFile {
|
||||
file: CollectionFile | null
|
||||
error: CollectionFileError | null
|
||||
gpx?: GpxLeftovers | null
|
||||
}
|
||||
|
||||
/** Reads a GPX document into a list file. The server does that, so the caller supplies it. */
|
||||
export type GpxReader = (gpx: string, fileName: string) => Promise<CollectionGpxReadResult>
|
||||
|
||||
/** A list file is JSON and JSON never opens with `<`, so this is all the sniffing a GPX needs. */
|
||||
function looksLikeXml(text: string): boolean {
|
||||
const withoutBom = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
|
||||
return withoutBom.trimStart().startsWith('<')
|
||||
}
|
||||
|
||||
/** The reason the server gave for refusing a GPX, when it gave one this build knows. */
|
||||
function gpxProblemOf(err: unknown): CollectionGpxProblem | null {
|
||||
const code: unknown = (err as { response?: { data?: { code?: unknown } } } | null)?.response?.data?.code
|
||||
return COLLECTION_GPX_PROBLEMS.find(problem => problem === code) ?? null
|
||||
}
|
||||
|
||||
async function readGpx(text: string, fileName: string, reader: GpxReader): Promise<ParsedCollectionFile> {
|
||||
try {
|
||||
const result = await reader(text, fileName)
|
||||
return { file: result.file, error: null, gpx: { skipped: result.skipped, trackPoints: result.track_points } }
|
||||
} catch (err) {
|
||||
const problem = gpxProblemOf(err)
|
||||
// No code means the failure was not the file's (offline, a 500), and that
|
||||
// is for the dialog to report as it reports a failed import.
|
||||
if (!problem) throw err
|
||||
return { file: null, error: problem, gpx: null }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a chosen file into a list file, or say why it is not one.
|
||||
*
|
||||
* The three failures are kept apart because they are three different things a
|
||||
* person can do something about: a file too big to be one of ours, a file that
|
||||
* is not JSON at all, and a JSON that is not a TREK list.
|
||||
* The failures are kept apart because they are different things a person can
|
||||
* do something about: a file too big to be one of ours, a file that is not
|
||||
* readable at all, a JSON that is not a TREK list, an XML that is not a GPX,
|
||||
* and a GPX with more places than a list may hold.
|
||||
*/
|
||||
export async function readCollectionFile(file: File): Promise<ParsedCollectionFile> {
|
||||
export async function readCollectionFile(file: File, readGpxFile: GpxReader): Promise<ParsedCollectionFile> {
|
||||
if (file.size > MAX_COLLECTION_FILE_BYTES) return { file: null, error: 'too-large' }
|
||||
let text: string
|
||||
try {
|
||||
text = await file.text()
|
||||
} catch {
|
||||
return { file: null, error: 'unreadable' }
|
||||
}
|
||||
if (looksLikeXml(text)) return readGpx(text, file.name ?? '', readGpxFile)
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(await file.text())
|
||||
raw = JSON.parse(text)
|
||||
} catch {
|
||||
return { file: null, error: 'unreadable' }
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-DAWARICH-ACCEPT-001 to FE-DAWARICH-ACCEPT-024
|
||||
// FE-DAWARICH-ACCEPT-001 to FE-DAWARICH-ACCEPT-026
|
||||
/**
|
||||
* The review step between a detector's guess and a row in somebody's trip.
|
||||
*
|
||||
@@ -11,7 +11,8 @@
|
||||
* pinning, and it is the one a refactor breaks first.
|
||||
*
|
||||
* The rest is the shape of the three targets. `place` needs a trip and offers a
|
||||
* day, `journal` needs a journey and asks for a story, `bucket_list` needs a
|
||||
* day (and no date: the day IS where it lands, and the server reads no date for
|
||||
* a place), `journal` needs a journey, a date and a story, `bucket_list` needs a
|
||||
* matched wish and hides the clock entirely because ticking a wish off uses the
|
||||
* recorded timestamp and nothing else. Each of the three can be in a state
|
||||
* where there is nothing to write to (no trips, no journeys, no matched wish),
|
||||
@@ -173,20 +174,20 @@ describe('DawarichAcceptDialog', () => {
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Café Reichard am Dom' } })
|
||||
fireEvent.change(screen.getByLabelText('Notes'), { target: { value: 'Two hours and a lot of cake.' } })
|
||||
typeDate('2026-09-12')
|
||||
fireEvent.change(screen.getByLabelText('Arrived'), { target: { value: '09:00' } })
|
||||
fireEvent.change(screen.getByLabelText('Left'), { target: { value: '11:45' } })
|
||||
pick('Not on a day yet', 'Day 1')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
|
||||
// The day is the only calendar fact a place carries: there is no date in
|
||||
// this body because there is no date field on this rail.
|
||||
expect(onConfirm).toHaveBeenCalledWith({
|
||||
target: 'place',
|
||||
tripId: 31,
|
||||
dayId: 401,
|
||||
name: 'Café Reichard am Dom',
|
||||
notes: 'Two hours and a lot of cake.',
|
||||
date: '2026-09-12',
|
||||
time: '09:00',
|
||||
endTime: '11:45',
|
||||
})
|
||||
@@ -381,10 +382,11 @@ describe('DawarichAcceptDialog', () => {
|
||||
it('FE-DAWARICH-ACCEPT-018: a recording with no readable clock or date sends neither', () => {
|
||||
// Dawarich has shipped date-only and non-ISO timestamps; the clock parser
|
||||
// answers with an empty string rather than a guess, and an empty string must
|
||||
// not reach the body as `time: ""`.
|
||||
// not reach the body as `time: ""` or `date: ""`. On the journal rail,
|
||||
// because that is the one rail that shows the date beside the clock.
|
||||
const { onConfirm } = open({
|
||||
trips: TRIPS,
|
||||
daysForTrip,
|
||||
target: 'journal',
|
||||
journals: JOURNALS,
|
||||
suggestion: stay({ startedAt: '2026-09-10', endedAt: '2026-09-10', localDate: '' }),
|
||||
})
|
||||
|
||||
@@ -392,8 +394,8 @@ describe('DawarichAcceptDialog', () => {
|
||||
expect(screen.getByLabelText('Left')).toHaveValue('')
|
||||
expect(screen.getByRole('button', { name: 'Date' })).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
expect(onConfirm).toHaveBeenCalledWith({ target: 'place', tripId: 31 })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add entry' }))
|
||||
expect(onConfirm).toHaveBeenCalledWith({ target: 'journal', journalId: 71 })
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-019: the fields follow the stay, and survive a re-render of the same one', () => {
|
||||
@@ -524,4 +526,43 @@ describe('DawarichAcceptDialog', () => {
|
||||
endTime: '12:40',
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-025: the place rail offers no date, because the day picker is where a place lands', () => {
|
||||
open({ trips: TRIPS, daysForTrip })
|
||||
|
||||
// A place has no date of its own: the server reads a date for a journal
|
||||
// entry and for nothing else, so a date field on this rail was one whose
|
||||
// change moved the place nowhere while the toast still said it landed.
|
||||
// The clock stays, the server does read that.
|
||||
expect(screen.queryByText('Date')).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Enter date manually' })).toBeNull()
|
||||
expect(screen.getByLabelText('Arrived')).toHaveValue('10:15')
|
||||
expect(screen.getByLabelText('Left')).toHaveValue('12:40')
|
||||
expect(screen.getByRole('button', { name: 'Not on a day yet' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-026: a corrected date travels with a journal entry, and never with a place', () => {
|
||||
// Both rails on one stay, so the dialog holds the corrected date in state
|
||||
// across the switch: the same shape as switching rails with a note typed.
|
||||
const { onConfirm, update } = open({ target: 'journal', journals: JOURNALS, trips: TRIPS, daysForTrip })
|
||||
|
||||
expect(screen.getByText('Date')).toBeInTheDocument()
|
||||
typeDate('2026-09-12')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add entry' }))
|
||||
expect(onConfirm).toHaveBeenLastCalledWith({
|
||||
target: 'journal',
|
||||
journalId: 71,
|
||||
date: '2026-09-12',
|
||||
time: '10:15',
|
||||
endTime: '12:40',
|
||||
})
|
||||
|
||||
// Same stay, now as a place. The corrected date is still in state and would
|
||||
// be silently dropped by the server; it must not be in the body at all,
|
||||
// so what the dialog claims to send is what is actually written.
|
||||
update({ target: 'place' })
|
||||
expect(screen.queryByText('Date')).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
expect(onConfirm).toHaveBeenLastCalledWith({ target: 'place', tripId: 31, time: '10:15', endTime: '12:40' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -114,7 +114,10 @@ export default function DawarichAcceptDialog({
|
||||
}
|
||||
if (name.trim() && name.trim() !== suggestion.name) body.name = name.trim()
|
||||
if (notes.trim()) body.notes = notes.trim()
|
||||
if (date && date !== suggestion.localDate) body.date = date
|
||||
// Only an entry carries a date. A place lands on the day chosen below and
|
||||
// the server reads nothing else for it, so a date corrected on the journal
|
||||
// rail must not ride along when the same stay is then added as a place.
|
||||
if (target === 'journal' && date && date !== suggestion.localDate) body.date = date
|
||||
if (time) body.time = time
|
||||
if (endTime) body.endTime = endTime
|
||||
onConfirm(body)
|
||||
@@ -199,15 +202,27 @@ export default function DawarichAcceptDialog({
|
||||
itself from the OS locale and a native `type="time"` ignores the 12h/24h
|
||||
setting outright (#2067) — and neither follows the colour scheme. The
|
||||
date column is the wide one because a localized date is long and a
|
||||
clock never is. */}
|
||||
clock never is.
|
||||
|
||||
The date is the journal rail's alone. A place has no date of its own:
|
||||
the day picker below is where it lands, and a date field beside that
|
||||
picker was a second answer to the same question, one the server never
|
||||
read. The two clocks then share the row the way they do on the place
|
||||
form. */}
|
||||
{target !== 'bucket_list' && (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-[minmax(0,1fr)_124px_124px] gap-2">
|
||||
<div>
|
||||
<span className="block text-caption font-medium mb-1.5 text-content-secondary">
|
||||
{t('dawarich.accept.date')}
|
||||
</span>
|
||||
<CustomDatePicker value={date} onChange={setDate} />
|
||||
</div>
|
||||
<div
|
||||
className={`grid grid-cols-1 gap-2 ${
|
||||
target === 'journal' ? 'sm:grid-cols-[minmax(0,1fr)_124px_124px]' : 'sm:grid-cols-2'
|
||||
}`}
|
||||
>
|
||||
{target === 'journal' && (
|
||||
<div>
|
||||
<span className="block text-caption font-medium mb-1.5 text-content-secondary">
|
||||
{t('dawarich.accept.date')}
|
||||
</span>
|
||||
<CustomDatePicker value={date} onChange={setDate} />
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<span className="block text-caption font-medium mb-1.5 text-content-secondary">
|
||||
{t('dawarich.accept.from')}
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { DawarichAccept, DawarichSuggestion, DawarichSuggestionTarget } fro
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useDawarichSuggestions } from '../../hooks/useDawarichSuggestions'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useIsPhone } from '../../mobile/useIsPhone'
|
||||
import { relativeTime } from '../../utils/relativeTime'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
@@ -123,6 +124,9 @@ export default function DawarichSuggestionsPanel({
|
||||
allowPlace: trips.length > 0,
|
||||
// The trip name is noise when every row is from the same trip.
|
||||
showTrip: tripId === undefined,
|
||||
// In the trip rail the arrival is the half that places a stop; how long somebody stood
|
||||
// there is a second figure on a row that already does not wrap.
|
||||
showDuration: tripId === undefined,
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -277,13 +281,21 @@ export default function DawarichSuggestionsPanel({
|
||||
* The actions fade in on hover on a pointer device and stay visible on touch,
|
||||
* where there is no hover to reveal them.
|
||||
*/
|
||||
function SuggestionRow({
|
||||
/**
|
||||
* One stay, as a card with its actions clipped to the side.
|
||||
*
|
||||
* Exported because the journal draws these rows in its own timeline now — folded into a
|
||||
* day rather than stacked in a panel above it — and a second copy of a row this detailed
|
||||
* would be two things to keep in step, plus a straight hit on the duplication budget.
|
||||
*/
|
||||
export function SuggestionRow({
|
||||
suggestion,
|
||||
busy,
|
||||
allowJournal = false,
|
||||
allowPlace = false,
|
||||
showTrip = false,
|
||||
showDate = false,
|
||||
showDuration = true,
|
||||
phone = false,
|
||||
onAccept,
|
||||
onDismiss,
|
||||
@@ -295,6 +307,8 @@ function SuggestionRow({
|
||||
allowPlace?: boolean
|
||||
showTrip?: boolean
|
||||
showDate?: boolean
|
||||
/** How long the stay lasted. Off in the trip rail, where the arrival is the useful half. */
|
||||
showDuration?: boolean
|
||||
/** Rendered inside the phone shell, which has its own palette and its own reach. */
|
||||
phone?: boolean
|
||||
onAccept?: (target: DawarichSuggestionTarget) => void
|
||||
@@ -302,6 +316,9 @@ function SuggestionRow({
|
||||
onRestore?: () => void
|
||||
}): React.ReactElement {
|
||||
const { t, locale } = useTranslation()
|
||||
// The traveller's own clock: these times used to come straight out of the timestamp, so
|
||||
// a 12-hour setting got 24-hour times here and nowhere else.
|
||||
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
|
||||
|
||||
return (
|
||||
<div className="flex items-stretch gap-[6px] px-3 py-[5px]">
|
||||
@@ -348,8 +365,8 @@ function SuggestionRow({
|
||||
{showDate && (
|
||||
<Badge icon={CalendarDays}>{formatDayHeading(suggestion.localDate, locale)}</Badge>
|
||||
)}
|
||||
<Badge icon={Clock}>{timeRange(suggestion.startedAt, suggestion.endedAt)}</Badge>
|
||||
<Badge icon={Hourglass}>{formatDuration(suggestion.durationMinutes, t)}</Badge>
|
||||
<Badge icon={Clock}>{timeRange(suggestion.startedAt, suggestion.endedAt, is12h)}</Badge>
|
||||
{showDuration && <Badge icon={Hourglass}>{formatDuration(suggestion.durationMinutes, t)}</Badge>}
|
||||
|
||||
{suggestion.state === 'accepted' && (
|
||||
<Badge icon={Check} tone="success">
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
formatDayOption,
|
||||
formatDuration,
|
||||
groupByDay,
|
||||
openStaysByDate,
|
||||
timeRange,
|
||||
} from './dawarichSuggestionModel'
|
||||
|
||||
@@ -105,12 +106,22 @@ describe('clockOf / timeRange', () => {
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGMODEL-006: a range when both ends read, the arrival alone when the end does not', () => {
|
||||
expect(timeRange('2026-09-10T10:15:00+02:00', '2026-09-10T12:40:00+02:00')).toBe('10:15 – 12:40')
|
||||
expect(timeRange('2026-09-10T10:15:00+02:00', 'nonsense')).toBe('10:15')
|
||||
expect(timeRange('2026-09-10T10:15:00+02:00', '2026-09-10T12:40:00+02:00', false)).toBe('10:15 – 12:40')
|
||||
expect(timeRange('2026-09-10T10:15:00+02:00', 'nonsense', false)).toBe('10:15')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGMODEL-007: no arrival, no range', () => {
|
||||
expect(timeRange('nonsense', '2026-09-10T12:40:00+02:00')).toBe('')
|
||||
expect(timeRange('nonsense', '2026-09-10T12:40:00+02:00', false)).toBe('')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGMODEL-012: a twelve-hour clock gets twelve-hour times, both ends of the range', () => {
|
||||
// These were cut out of the timestamp and printed as they stood, so a traveller on a
|
||||
// 12-hour clock read every Dawarich time in 24-hour while the rest of the app obeyed
|
||||
// the setting.
|
||||
expect(timeRange('2026-09-10T10:15:00+02:00', '2026-09-10T12:40:00+02:00', true)).toBe('10:15 AM – 12:40 PM')
|
||||
expect(timeRange('2026-09-10T14:05:00+02:00', '2026-09-10T23:00:00+02:00', true)).toBe('2:05 PM – 11:00 PM')
|
||||
// Midnight is 12 AM, not 0 AM, and noon is 12 PM.
|
||||
expect(timeRange('2026-09-10T00:30:00+02:00', '2026-09-10T12:00:00+02:00', true)).toBe('12:30 AM – 12:00 PM')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -156,3 +167,49 @@ describe('formatDayOption', () => {
|
||||
expect(formatDayOption(1, null, 'en-GB', t)).toEqual({ label: 'planner.dayN:{"n":1}', badge: undefined })
|
||||
})
|
||||
})
|
||||
|
||||
describe('openStaysByDate', () => {
|
||||
it('FE-DAWARICH-SUGMODEL-015: buckets the open stays by their own local day', () => {
|
||||
// What a journal timeline asks for: it draws one day and folds that day's stays into
|
||||
// it, so it looks them up by date rather than walking a flat list per day.
|
||||
const byDate = openStaysByDate([
|
||||
stay({ id: 1, localDate: '2026-09-10' }),
|
||||
stay({ id: 2, localDate: '2026-09-11' }),
|
||||
stay({ id: 3, localDate: '2026-09-10' }),
|
||||
])
|
||||
|
||||
expect([...byDate.keys()].sort()).toEqual(['2026-09-10', '2026-09-11'])
|
||||
expect(byDate.get('2026-09-10')!.map(s => s.id)).toEqual([1, 3])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGMODEL-016: within a day they are in the order they were lived', () => {
|
||||
// A run of stays reads as an afternoon only in that order; whatever order the server
|
||||
// sent them in is not it.
|
||||
const byDate = openStaysByDate([
|
||||
stay({ id: 1, localDate: '2026-09-10', startedAt: '2026-09-10T16:00:00+02:00' }),
|
||||
stay({ id: 2, localDate: '2026-09-10', startedAt: '2026-09-10T08:30:00+02:00' }),
|
||||
stay({ id: 3, localDate: '2026-09-10', startedAt: '2026-09-10T12:15:00+02:00' }),
|
||||
])
|
||||
|
||||
expect(byDate.get('2026-09-10')!.map(s => s.id)).toEqual([2, 3, 1])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGMODEL-017: only what is still waiting', () => {
|
||||
// An accepted stay is an entry on that timeline already, and a dismissed one was waved
|
||||
// away on purpose; offering either again is offering to do it twice.
|
||||
const byDate = openStaysByDate([
|
||||
stay({ id: 1, localDate: '2026-09-10', state: 'accepted' }),
|
||||
stay({ id: 2, localDate: '2026-09-10', state: 'dismissed' }),
|
||||
stay({ id: 3, localDate: '2026-09-10' }),
|
||||
])
|
||||
|
||||
expect(byDate.get('2026-09-10')!.map(s => s.id)).toEqual([3])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGMODEL-018: a day whose every stay is handled is not a day at all', () => {
|
||||
// An empty bucket would draw a fold saying "0 stays" on a day that has none.
|
||||
const byDate = openStaysByDate([stay({ id: 1, localDate: '2026-09-10', state: 'accepted' })])
|
||||
|
||||
expect(byDate.size).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { DawarichSuggestion } from '@trek/shared'
|
||||
import { dayColor } from '../Map/dawarichTrail'
|
||||
import { formatClockTime } from '../../utils/formatters'
|
||||
|
||||
/**
|
||||
* Pure shaping for the suggestions panel — no React, so the grouping and the
|
||||
@@ -33,7 +34,9 @@ export function groupByDay(suggestions: DawarichSuggestion[]): SuggestionDay[] {
|
||||
else byDate.set(stay.localDate, [stay])
|
||||
}
|
||||
|
||||
const oldestFirst = [...byDate.keys()].sort()
|
||||
// ISO dates, so lexicographic order IS chronological order. Spelled out rather than
|
||||
// left bare, and deliberately not locale-aware, which would vary by runtime.
|
||||
const oldestFirst = [...byDate.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
|
||||
return oldestFirst
|
||||
.map((date, index) => ({
|
||||
date,
|
||||
@@ -44,6 +47,30 @@ export function groupByDay(suggestions: DawarichSuggestion[]): SuggestionDay[] {
|
||||
.reverse()
|
||||
}
|
||||
|
||||
/**
|
||||
* The stays still waiting, by the local day they happened on.
|
||||
*
|
||||
* What a journal timeline needs: it draws one day at a time and folds that day's stays
|
||||
* into it, so it asks by date rather than walking a flat list per day. Only `new` ones —
|
||||
* an accepted stay is already an entry on that timeline and a dismissed one was waved
|
||||
* away on purpose — and within a day the order is the order they were lived in, which is
|
||||
* what makes a run of them read as an afternoon.
|
||||
*
|
||||
* A Map rather than the day list `groupByDay` builds: that one is ordered newest-first for
|
||||
* a panel to print, and this one is looked up by the day the timeline is already drawing.
|
||||
*/
|
||||
export function openStaysByDate(suggestions: DawarichSuggestion[]): Map<string, DawarichSuggestion[]> {
|
||||
const byDate = new Map<string, DawarichSuggestion[]>();
|
||||
for (const stay of suggestions) {
|
||||
if (stay.state !== 'new') continue;
|
||||
const bucket = byDate.get(stay.localDate);
|
||||
if (bucket) bucket.push(stay);
|
||||
else byDate.set(stay.localDate, [stay]);
|
||||
}
|
||||
for (const stays of byDate.values()) stays.sort((a, b) => (a.startedAt < b.startedAt ? -1 : 1));
|
||||
return byDate;
|
||||
}
|
||||
|
||||
/** `HH:MM` out of an ISO timestamp, in the offset the timestamp carries. */
|
||||
export function clockOf(iso: string): string {
|
||||
return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(iso) ? iso.slice(11, 16) : ''
|
||||
@@ -54,10 +81,15 @@ export function clockOf(iso: string): string {
|
||||
*
|
||||
* An en dash with hair spaces rather than a hyphen: this is a range, and it sits
|
||||
* next to times often enough that the difference is visible.
|
||||
*
|
||||
* `is12h` is not optional on purpose. These clocks were cut straight out of the
|
||||
* timestamp and printed, so a traveller on a 12-hour clock read every Dawarich time in
|
||||
* 24-hour while the rest of the app obeyed the setting. A required argument makes the
|
||||
* next caller answer the question rather than inherit the bug.
|
||||
*/
|
||||
export function timeRange(startedAt: string, endedAt: string): string {
|
||||
const from = clockOf(startedAt)
|
||||
const to = clockOf(endedAt)
|
||||
export function timeRange(startedAt: string, endedAt: string, is12h: boolean): string {
|
||||
const from = formatClockTime(clockOf(startedAt), is12h)
|
||||
const to = formatClockTime(clockOf(endedAt), is12h)
|
||||
if (!from) return ''
|
||||
return to ? `${from} – ${to}` : from
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// FE-COMP-FILEMANAGER-001 to FE-COMP-FILEMANAGER-012
|
||||
// FE-COMP-FILEMANAGER-001 to FE-COMP-FILEMANAGER-038
|
||||
import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { useDocSyncOfferStore } from '../../store/docSyncOfferStore';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser, buildTrip } from '../../../tests/helpers/factories';
|
||||
import type { TripFile } from '../../types';
|
||||
@@ -104,6 +105,15 @@ beforeEach(() => {
|
||||
}),
|
||||
);
|
||||
|
||||
// Document sync, as a fresh install has it: every provider off, nothing bound.
|
||||
useDocSyncOfferStore.setState({ bound: {}, providers: null });
|
||||
server.use(
|
||||
http.get('/api/trips/:tripId/docsync/providers', () => HttpResponse.json([])),
|
||||
http.get('/api/trips/:tripId/docsync/links', () => HttpResponse.json([])),
|
||||
http.get('/api/trips/:tripId/docsync/connections', () => HttpResponse.json([])),
|
||||
http.get('/api/trips/:tripId/docsync/status', () => HttpResponse.json({ links: [], items: {} })),
|
||||
);
|
||||
|
||||
// Stub window.confirm
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
});
|
||||
@@ -631,4 +641,60 @@ describe('FileManager', () => {
|
||||
expect(call[0]).toBeInstanceOf(FormData);
|
||||
});
|
||||
});
|
||||
|
||||
describe('document sync button', () => {
|
||||
const paperless = { id: 'paperless', name: 'Paperless-ngx', description: null, icon: 'paperless', available: true, fields: [] };
|
||||
const trashButton = () => screen.getByText('Trash').closest('button') as HTMLButtonElement;
|
||||
|
||||
it('FE-COMP-FILEMANAGER-036: with no provider on and nothing bound there is no sync button, and the trash sits flush right', async () => {
|
||||
const asked: string[] = [];
|
||||
server.use(
|
||||
http.get('/api/trips/:tripId/docsync/links', () => {
|
||||
asked.push('links');
|
||||
return HttpResponse.json([]);
|
||||
}),
|
||||
);
|
||||
render(<FileManager {...defaultProps} />);
|
||||
|
||||
await waitFor(() => expect(asked).toContain('links'));
|
||||
expect(screen.queryByTitle('Document sync')).not.toBeInTheDocument();
|
||||
expect(trashButton()).toHaveStyle({ marginLeft: 'auto' });
|
||||
});
|
||||
|
||||
it('FE-COMP-FILEMANAGER-037: somebody who may bind the trip gets it once a provider is on, and it opens the panel', async () => {
|
||||
server.use(http.get('/api/trips/:tripId/docsync/providers', () => HttpResponse.json([paperless])));
|
||||
render(<FileManager {...defaultProps} />);
|
||||
const user = userEvent.setup();
|
||||
|
||||
const button = await screen.findByTitle('Document sync');
|
||||
expect(button).toHaveStyle({ marginLeft: 'auto' });
|
||||
expect(trashButton().style.marginLeft).toBe('');
|
||||
|
||||
await user.click(button);
|
||||
expect(await screen.findByText('Connect a provider')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-FILEMANAGER-038: a member sees it on a bound trip only', async () => {
|
||||
seedStore(useAuthStore, { user: buildUser({ id: 999, role: 'user' }), isAuthenticated: true });
|
||||
server.use(
|
||||
http.get('/api/trips/:tripId/docsync/providers', () => HttpResponse.json([paperless])),
|
||||
http.get('/api/trips/:tripId/docsync/links', () => HttpResponse.json([{ id: 1, providerId: 'paperless' }])),
|
||||
);
|
||||
const { unmount } = render(<FileManager {...defaultProps} />);
|
||||
expect(await screen.findByTitle('Document sync')).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
useDocSyncOfferStore.setState({ bound: {}, providers: null });
|
||||
const asked: string[] = [];
|
||||
server.use(
|
||||
http.get('/api/trips/:tripId/docsync/links', () => {
|
||||
asked.push('links');
|
||||
return HttpResponse.json([]);
|
||||
}),
|
||||
);
|
||||
render(<FileManager {...defaultProps} />);
|
||||
await waitFor(() => expect(asked).toContain('links'));
|
||||
expect(screen.queryByTitle('Document sync')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ import { isMarkdown } from './FileManager.helpers'
|
||||
import { FileManagerToolbar } from './FileManagerToolbar'
|
||||
import { TrashView } from './FileManagerTrashView'
|
||||
import { FilesView } from './FileManagerFilesView'
|
||||
import DocSyncPanel from './docsync/DocSyncPanel'
|
||||
|
||||
export default function FileManager(props: FileManagerProps) {
|
||||
const S = useFileManager(props)
|
||||
@@ -24,6 +25,19 @@ export default function FileManager(props: FileManagerProps) {
|
||||
? <MarkdownPreviewModal {...S} />
|
||||
: <PdfPreviewModal {...S} />)}
|
||||
|
||||
{/* Document sync opens as its own dialog: it is configuration for the
|
||||
documents on this screen, so it belongs here rather than in settings,
|
||||
but it is a task with a beginning and an end and does not belong
|
||||
inside the list it configures. */}
|
||||
{S.showDocSync && (
|
||||
<DocSyncPanel
|
||||
tripId={props.tripId}
|
||||
tripTitle={S.trip?.title}
|
||||
canManage={S.canManageSync}
|
||||
onClose={() => S.setShowDocSync(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Toolbar */}
|
||||
<FileManagerToolbar {...S} />
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Star, Trash2 } from 'lucide-react'
|
||||
import { FolderSync, Star, Trash2 } from 'lucide-react'
|
||||
import type { FileManagerState } from './useFileManager'
|
||||
|
||||
export function FileManagerToolbar(S: FileManagerState) {
|
||||
const { showTrash, t, files, filterType, setFilterType, toggleTrash } = S
|
||||
const { showTrash, t, files, filterType, setFilterType, toggleTrash, setShowDocSync, docSyncOffered } = S
|
||||
return (
|
||||
<div style={{ padding: '24px 28px 0', flexShrink: 0 }} className="max-md:!px-4 max-md:!pt-4">
|
||||
<div style={{
|
||||
@@ -63,12 +63,29 @@ export function FileManagerToolbar(S: FileManagerState) {
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Opens the sync panel. Placed next to the trash rather than in a menu
|
||||
because the question it answers, "where do these documents live",
|
||||
belongs on the same screen as the documents. Only where there is
|
||||
something behind it: see useDocSyncOffered. */}
|
||||
{docSyncOffered && (
|
||||
<button type="button" onClick={() => setShowDocSync(true)} title={t('docsync.title')} style={{
|
||||
appearance: 'none', border: '1px solid var(--edge)', cursor: 'pointer', fontFamily: 'inherit',
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
padding: '9px 12px', borderRadius: 10, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500,
|
||||
background: 'transparent', color: 'var(--content-muted)', flexShrink: 0, marginLeft: 'auto',
|
||||
}}>
|
||||
<FolderSync size={14} strokeWidth={2.5} /> <span className="hidden sm:inline">{t('docsync.title')}</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* The first of the two takes the free space, so without the sync
|
||||
button the trash sits flush right the way it always has. */}
|
||||
<button type="button" onClick={toggleTrash} style={{
|
||||
appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
padding: '9px 14px', borderRadius: 10, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500,
|
||||
background: 'var(--accent)', color: 'var(--accent-text)',
|
||||
flexShrink: 0, marginLeft: 'auto',
|
||||
flexShrink: 0, marginLeft: docSyncOffered ? undefined : 'auto',
|
||||
opacity: showTrash ? 1 : 0.88,
|
||||
transition: 'opacity 0.15s ease',
|
||||
}}
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
// FE-DOCSYNC-BIND-001 to FE-DOCSYNC-BIND-030
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import en from '@trek/shared/i18n/en'
|
||||
import { render, screen, fireEvent, waitFor, within } from '../../../../tests/helpers/render'
|
||||
import DocSyncBinding from './DocSyncBinding'
|
||||
import type { DocSyncLink, useDocSync } from './useDocSync'
|
||||
|
||||
type Sync = ReturnType<typeof useDocSync>
|
||||
|
||||
const syncNow = vi.fn(async (_linkId: number) => ({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 }))
|
||||
const updateLink = vi.fn(async (_linkId: number, _patch: Record<string, unknown>) => {})
|
||||
const removeLink = vi.fn(async (_linkId: number) => {})
|
||||
|
||||
const WEBHOOK = 'https://trek.example/api/trips/3/docsync/hooks/abc123'
|
||||
|
||||
function makeLink(overrides: Partial<DocSyncLink> = {}): DocSyncLink {
|
||||
return {
|
||||
id: 4,
|
||||
connectionId: 1,
|
||||
providerId: 'paperless',
|
||||
scopeKey: 'trek-trip-3',
|
||||
remoteLabel: 'Lisbon papers',
|
||||
remoteRootPath: '/TREK/Lisbon',
|
||||
direction: 'both',
|
||||
deletePolicy: 'unlink',
|
||||
conflictPolicy: 'manual',
|
||||
syncEnabled: true,
|
||||
lastSyncAt: null,
|
||||
lastSyncState: 'ok',
|
||||
lastSyncError: null,
|
||||
webhookUrl: null,
|
||||
holdings: { inTrek: 3, atProvider: 2, paired: 2, missing: 1 },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeSync(overrides: Partial<Sync> = {}): Sync {
|
||||
return {
|
||||
providers: [],
|
||||
connections: [],
|
||||
links: [],
|
||||
itemCounts: {},
|
||||
loading: false,
|
||||
busy: null,
|
||||
error: null,
|
||||
connectionFor: () => null,
|
||||
load: vi.fn(),
|
||||
saveConnection: vi.fn(),
|
||||
testConnection: vi.fn(),
|
||||
loadScopes: vi.fn(),
|
||||
createScope: vi.fn(),
|
||||
createLink: vi.fn(),
|
||||
updateLink,
|
||||
removeLink,
|
||||
syncNow,
|
||||
resolveConflict: vi.fn(),
|
||||
lastRunFor: () => ({ pulled: 0, pushed: 0 }),
|
||||
...overrides,
|
||||
} as unknown as Sync
|
||||
}
|
||||
|
||||
function renderCard(
|
||||
opts: {
|
||||
link?: Partial<DocSyncLink>
|
||||
sync?: Partial<Sync>
|
||||
canManage?: boolean
|
||||
providerName?: string
|
||||
onReconnect?: () => void
|
||||
} = {},
|
||||
) {
|
||||
const utils = render(
|
||||
<DocSyncBinding
|
||||
link={makeLink(opts.link)}
|
||||
providerName={opts.providerName ?? 'Paperless'}
|
||||
sync={makeSync(opts.sync)}
|
||||
canManage={opts.canManage ?? true}
|
||||
onReconnect={opts.onReconnect}
|
||||
/>,
|
||||
)
|
||||
const header = utils.container.querySelector('header') as HTMLElement
|
||||
return { ...utils, header }
|
||||
}
|
||||
|
||||
const openSettings = () => fireEvent.click(screen.getByRole('button', { name: 'Settings' }))
|
||||
|
||||
const rowFor = (label: string) => screen.getByText(label).closest('div') as HTMLElement
|
||||
|
||||
const UNLINK_QUESTION = 'Documents stay in TREK and at the store. Only the pairing between them goes.'
|
||||
|
||||
/** The confirmation the disconnect button opens; it renders in a portal. */
|
||||
const unlinkDialog = () => within(screen.getByText(UNLINK_QUESTION).closest('.trek-modal-enter') as HTMLElement)
|
||||
|
||||
/** Named through the same fallback chain `t()` uses, so the label can land in the locales later. */
|
||||
const reconnectButton = () =>
|
||||
screen.queryByRole('button', { name: (en as unknown as Record<string, string>)['docsync.binding.reconnect'] ?? 'docsync.binding.reconnect' })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('DocSyncBinding: running a sync', () => {
|
||||
it('FE-DOCSYNC-BIND-001: "Sync now" asks the hook to run this binding', () => {
|
||||
renderCard()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Sync now' }))
|
||||
|
||||
expect(syncNow).toHaveBeenCalledWith(4)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-002: while this binding runs the button reads "Syncing" and refuses another click', () => {
|
||||
renderCard({ sync: { busy: 'sync-4' } })
|
||||
|
||||
const button = screen.getByRole('button', { name: 'Syncing' })
|
||||
expect(button).toBeDisabled()
|
||||
expect(screen.queryByRole('button', { name: 'Sync now' })).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(button)
|
||||
expect(syncNow).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-003: a run on another binding leaves this card ready', () => {
|
||||
renderCard({ sync: { busy: 'sync-9' } })
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Sync now' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-004: the disconnect button asks first and unlinks once that is confirmed', () => {
|
||||
// As the phone does. The button sits beside "Sync now", and a binding
|
||||
// cannot be put back: rebinding the same folder starts from nothing.
|
||||
renderCard()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }))
|
||||
|
||||
expect(removeLink).not.toHaveBeenCalled()
|
||||
expect(screen.getByText(UNLINK_QUESTION)).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(unlinkDialog().getByRole('button', { name: 'Disconnect' }))
|
||||
|
||||
expect(removeLink).toHaveBeenCalledWith(4)
|
||||
expect(screen.queryByText(UNLINK_QUESTION)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-027: cancelling the question leaves the binding as it was', () => {
|
||||
renderCard()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }))
|
||||
fireEvent.click(unlinkDialog().getByRole('button', { name: 'Cancel' }))
|
||||
|
||||
expect(removeLink).not.toHaveBeenCalled()
|
||||
expect(screen.queryByText(UNLINK_QUESTION)).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncBinding: a refused credential', () => {
|
||||
it('FE-DOCSYNC-BIND-028: offers to sign in again beside the notice, and hands the click to the panel', () => {
|
||||
// The sidebar opens the credential form only for a store with no
|
||||
// connection yet, so a rotated token had no way back in from the app.
|
||||
const onReconnect = vi.fn()
|
||||
renderCard({ link: { lastSyncState: 'needs_reauth', lastSyncError: 'unauthorized' }, onReconnect })
|
||||
|
||||
expect(screen.getByText('Sign in again · The credentials were refused.')).toBeInTheDocument()
|
||||
fireEvent.click(reconnectButton() as HTMLElement)
|
||||
|
||||
expect(onReconnect).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-029: a refusal recorded as a failed run offers it too', () => {
|
||||
const onReconnect = vi.fn()
|
||||
renderCard({ link: { lastSyncState: 'failed', lastSyncError: 'unauthorized' }, onReconnect })
|
||||
|
||||
expect(reconnectButton()).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-030: is not offered to a member, for another failure, or while the provider is switched off', () => {
|
||||
const onReconnect = vi.fn()
|
||||
const refused = { lastSyncState: 'needs_reauth', lastSyncError: 'unauthorized' } as const
|
||||
|
||||
const member = renderCard({ link: refused, onReconnect, canManage: false })
|
||||
expect(reconnectButton()).not.toBeInTheDocument()
|
||||
member.unmount()
|
||||
|
||||
const other = renderCard({ link: { lastSyncState: 'failed', lastSyncError: 'unreachable' }, onReconnect })
|
||||
expect(reconnectButton()).not.toBeInTheDocument()
|
||||
other.unmount()
|
||||
|
||||
// An admin has switched the store off: the paused notice stands in front,
|
||||
// and a new credential would change nothing until it is back on.
|
||||
const paused = renderCard({ link: { ...refused, providerOff: true }, onReconnect })
|
||||
expect(reconnectButton()).not.toBeInTheDocument()
|
||||
paused.unmount()
|
||||
|
||||
// The panel could not find the provider's form: nothing to open.
|
||||
renderCard({ link: refused })
|
||||
expect(reconnectButton()).not.toBeInTheDocument()
|
||||
expect(onReconnect).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncBinding: what it says about itself', () => {
|
||||
it('FE-DOCSYNC-BIND-005: a healthy binding shows its state as a dot, not as a word', () => {
|
||||
renderCard()
|
||||
|
||||
expect(screen.queryByText('In sync')).not.toBeInTheDocument()
|
||||
const dot = screen.getByTitle('In sync')
|
||||
expect(dot).toBeInTheDocument()
|
||||
expect(dot).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-006: a failing binding spells the state out and appends the reason', () => {
|
||||
renderCard({ link: { lastSyncState: 'failed', lastSyncError: 'unauthorized' } })
|
||||
|
||||
expect(screen.getByText('Failed')).toBeInTheDocument()
|
||||
expect(screen.getByText('Failed · The credentials were refused.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-007: a failing binding without a reason code shows the state alone', () => {
|
||||
renderCard({ link: { lastSyncState: 'failed', lastSyncError: null } })
|
||||
|
||||
// once as the header badge, once as the banner underneath it
|
||||
expect(screen.getAllByText('Failed')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-008: a partly synced binding also gets the banner', () => {
|
||||
renderCard({ link: { lastSyncState: 'partial', lastSyncError: 'too_large' } })
|
||||
|
||||
expect(screen.getByText('Partly synced · The file is larger than the provider accepts.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-009: a binding that never ran names its state but raises no alarm', () => {
|
||||
renderCard({ link: { lastSyncState: 'never', lastSyncAt: null } })
|
||||
|
||||
expect(screen.getAllByText('Not synced yet')).toHaveLength(1)
|
||||
expect(screen.getByText('not run yet')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-026: a binding whose provider an admin switched off says it is paused, not what the last run said', () => {
|
||||
// The server leaves the binding's own state as the last run wrote it, so
|
||||
// without this the card went on reporting an old failure, or nothing.
|
||||
renderCard({ link: { providerOff: true, lastSyncState: 'failed', lastSyncError: 'unauthorized' } })
|
||||
|
||||
expect(screen.getByText('Paused: an administrator has switched this provider off. Syncing resumes once it is back on.')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Failed · The credentials were refused.')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-010: a paused binding is badged, an active one is not', () => {
|
||||
const { unmount } = renderCard({ link: { syncEnabled: false } })
|
||||
expect(screen.getByText('Paused')).toBeInTheDocument()
|
||||
unmount()
|
||||
|
||||
renderCard({ link: { syncEnabled: true } })
|
||||
expect(screen.queryByText('Paused')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-011: the last run is shown as elapsed time once there is one', () => {
|
||||
renderCard({ link: { lastSyncAt: new Date(Date.now() - 2 * 3600_000).toISOString() } })
|
||||
|
||||
expect(screen.getByText(/hours ago/)).toBeInTheDocument()
|
||||
expect(screen.queryByText('not run yet')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-012: the folder falls back to the path, then to the scope key', () => {
|
||||
const { unmount } = renderCard({ link: { remoteLabel: '' } })
|
||||
expect(screen.getByText('/TREK/Lisbon')).toBeInTheDocument()
|
||||
unmount()
|
||||
|
||||
renderCard({ link: { remoteLabel: '', remoteRootPath: null } })
|
||||
expect(screen.getByText('trek-trip-3')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-013: names the store it is handed in the header and at the far end of the flow', () => {
|
||||
const { header } = renderCard({ providerName: 'Paperless-ngx' })
|
||||
|
||||
expect(within(header).getByText('Paperless-ngx')).toBeInTheDocument()
|
||||
expect(screen.getAllByText('Paperless-ngx')).toHaveLength(2)
|
||||
expect(screen.queryByText('paperless')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-014: the flow bar gets the holdings, and zeros when there are none', () => {
|
||||
const { unmount } = renderCard()
|
||||
expect(screen.getByText('3')).toBeInTheDocument()
|
||||
expect(screen.getByText('2')).toBeInTheDocument()
|
||||
unmount()
|
||||
|
||||
renderCard({ link: { holdings: undefined } })
|
||||
expect(screen.getAllByText('0')).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncBinding: the settings section', () => {
|
||||
it('FE-DOCSYNC-BIND-015: the settings stay folded away until they are opened', () => {
|
||||
renderCard()
|
||||
|
||||
const toggle = screen.getByRole('button', { name: 'Settings' })
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(screen.queryByText('Sync automatically')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('When a document is deleted')).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(toggle)
|
||||
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(screen.getByText('Sync automatically')).toBeInTheDocument()
|
||||
expect(screen.getByText('When a document is deleted')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(toggle)
|
||||
expect(screen.queryByText('Sync automatically')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-016: a member gets no settings section and no disconnect button', () => {
|
||||
renderCard({ canManage: false })
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Settings' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Sync automatically')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('When a document is deleted')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Disconnect' })).not.toBeInTheDocument()
|
||||
// a member may still trigger a run
|
||||
expect(screen.getByRole('button', { name: 'Sync now' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-017: turning "sync automatically" off patches the link', () => {
|
||||
renderCard()
|
||||
openSettings()
|
||||
|
||||
fireEvent.click(within(rowFor('Sync automatically')).getByRole('button'))
|
||||
|
||||
expect(updateLink).toHaveBeenCalledWith(4, { syncEnabled: false })
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-018: turning it back on patches the other way', () => {
|
||||
renderCard({ link: { syncEnabled: false } })
|
||||
openSettings()
|
||||
|
||||
const toggle = within(rowFor('Sync automatically')).getByRole('button')
|
||||
expect(toggle).toHaveAttribute('aria-pressed', 'false')
|
||||
fireEvent.click(toggle)
|
||||
|
||||
expect(updateLink).toHaveBeenCalledWith(4, { syncEnabled: true })
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-019: choosing another delete policy patches the link', () => {
|
||||
renderCard()
|
||||
openSettings()
|
||||
|
||||
const trigger = within(rowFor('When a document is deleted')).getByRole('button')
|
||||
expect(trigger).toHaveTextContent('Keep both copies')
|
||||
|
||||
fireEvent.click(trigger)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Move to recycle bin' }))
|
||||
|
||||
expect(updateLink).toHaveBeenCalledWith(4, { deletePolicy: 'trash' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncBinding: the webhook URL', () => {
|
||||
const realClipboard = navigator.clipboard
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(navigator, 'clipboard', { value: realClipboard, configurable: true, writable: true })
|
||||
})
|
||||
|
||||
const stubClipboard = (writeText: (text: string) => Promise<void>) => {
|
||||
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true, writable: true })
|
||||
}
|
||||
|
||||
it('FE-DOCSYNC-BIND-020: a binding without a webhook shows no webhook section', () => {
|
||||
renderCard({ link: { webhookUrl: null } })
|
||||
openSettings()
|
||||
|
||||
expect(screen.queryByText('Instant updates')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Copy' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-021: a binding with a webhook shows the URL for pasting', () => {
|
||||
renderCard({ link: { webhookUrl: WEBHOOK } })
|
||||
openSettings()
|
||||
|
||||
expect(screen.getByText('Instant updates')).toBeInTheDocument()
|
||||
expect(screen.getByText(WEBHOOK)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-022: copying the webhook puts it on the clipboard and confirms', async () => {
|
||||
const writeText = vi.fn(async (_text: string) => {})
|
||||
stubClipboard(writeText)
|
||||
renderCard({ link: { webhookUrl: WEBHOOK } })
|
||||
openSettings()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Copy' }))
|
||||
|
||||
await waitFor(() => expect(writeText).toHaveBeenCalledWith(WEBHOOK))
|
||||
expect(await screen.findByRole('button', { name: 'Copied' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-023: a blocked clipboard leaves the URL on screen and the button unchanged', async () => {
|
||||
const writeText = vi.fn(async (_text: string) => { throw new Error('not allowed') })
|
||||
stubClipboard(writeText)
|
||||
renderCard({ link: { webhookUrl: WEBHOOK } })
|
||||
openSettings()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Copy' }))
|
||||
|
||||
await waitFor(() => expect(writeText).toHaveBeenCalled())
|
||||
expect(screen.queryByRole('button', { name: 'Copied' })).not.toBeInTheDocument()
|
||||
expect(screen.getByText(WEBHOOK)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncBinding: the direction lanes', () => {
|
||||
it('FE-DOCSYNC-BIND-024: switching a lane off patches the direction', () => {
|
||||
renderCard()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Out to the store' }))
|
||||
|
||||
expect(updateLink).toHaveBeenCalledWith(4, { direction: 'pull' })
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-BIND-025: a member cannot change the direction', () => {
|
||||
renderCard({ canManage: false })
|
||||
|
||||
const lane = screen.getByRole('button', { name: 'Out to the store' })
|
||||
expect(lane).toBeDisabled()
|
||||
fireEvent.click(lane)
|
||||
expect(updateLink).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,258 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
AlertTriangle, Check, ChevronDown, Clock, Copy, FolderOpen, Link2Off, RefreshCw,
|
||||
} from 'lucide-react'
|
||||
import ConfirmDialog from '../../shared/ConfirmDialog'
|
||||
import CustomSelect from '../../shared/CustomSelect'
|
||||
import ToggleSwitch from '../../Settings/ToggleSwitch'
|
||||
import Tooltip from '../../shared/Tooltip'
|
||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/DocumentProviderIcons'
|
||||
import DocSyncFlow, { type SyncDirection } from './DocSyncFlow'
|
||||
import { Badge, CONFLICT_POLICIES, conflictPolicyKey, LastRun, StateBadge } from './DocSyncBits'
|
||||
import { bindingNotice, needsReauth, type DocSyncLink, type useDocSync } from './useDocSync'
|
||||
|
||||
/**
|
||||
* One binding: where this trip's documents live, which way they move, and what
|
||||
* happened last time.
|
||||
*
|
||||
* The flow bar carries the direction because that is the one thing this feature
|
||||
* is about. Everything a person sets once and forgets (the delete rule, the
|
||||
* webhook URL) is folded away behind "Settings" so the card stays a status
|
||||
* card rather than a form.
|
||||
*/
|
||||
export default function DocSyncBinding({
|
||||
link,
|
||||
providerName,
|
||||
sync,
|
||||
canManage,
|
||||
onReconnect,
|
||||
}: {
|
||||
link: DocSyncLink
|
||||
providerName: string
|
||||
sync: ReturnType<typeof useDocSync>
|
||||
canManage: boolean
|
||||
/**
|
||||
* Opens the credential form for this binding's store. Only the panel can,
|
||||
* because the form needs the provider's field list, which the card does
|
||||
* not carry; left out, a refused credential is reported but not curable.
|
||||
*/
|
||||
onReconnect?: () => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const [confirmUnlink, setConfirmUnlink] = useState(false)
|
||||
const Icon = DOCUMENT_PROVIDER_ICONS[link.providerId]
|
||||
const busy = sync.busy === `sync-${link.id}`
|
||||
const notice = bindingNotice(link, t)
|
||||
// Not while the provider is switched off: the paused notice stands in front
|
||||
// of the refusal then, and a new credential would change nothing until an
|
||||
// admin turns the provider back on.
|
||||
const reconnect = canManage && onReconnect && !link.providerOff && needsReauth(link) ? onReconnect : null
|
||||
|
||||
const copyWebhook = async () => {
|
||||
if (!link.webhookUrl) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(link.webhookUrl)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 1600)
|
||||
} catch {
|
||||
// Clipboard is blocked outside a secure context; the URL is selectable.
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<article className="overflow-hidden rounded-2xl border border-edge bg-surface shadow-card">
|
||||
<header className="flex flex-wrap items-start gap-x-3 gap-y-3 px-4 py-3.5">
|
||||
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-xl border border-edge bg-surface-secondary">
|
||||
{Icon ? <Icon className="h-5 w-5 text-content" /> : null}
|
||||
</span>
|
||||
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span className="truncate text-subtitle font-semibold text-content">
|
||||
{providerName}
|
||||
</span>
|
||||
{/* A healthy binding needs no word for it: the dot is the whole
|
||||
message, and the states that do need words get them below. */}
|
||||
<StateBadge state={link.lastSyncState} compact={link.lastSyncState === 'ok'} />
|
||||
{!link.syncEnabled && <Badge tone="neutral">{t('docsync.binding.autoOff')}</Badge>}
|
||||
</span>
|
||||
|
||||
{/* Where and when, as two facts rather than a sentence. They are what
|
||||
a member checks before asking why a file has not turned up. */}
|
||||
<span className="mt-1.5 flex flex-wrap items-center gap-1.5">
|
||||
<Badge tone="neutral" icon={<FolderOpen size={12} />} title={link.remoteRootPath || undefined}>
|
||||
<span className="max-w-[12rem] truncate">
|
||||
{link.remoteLabel || link.remoteRootPath || link.scopeKey}
|
||||
</span>
|
||||
</Badge>
|
||||
<Badge tone="neutral" icon={<Clock size={12} />}>
|
||||
<LastRun at={link.lastSyncAt} />
|
||||
</Badge>
|
||||
</span>
|
||||
</span>
|
||||
|
||||
{/* Both controls are h-9 so the square one cannot sit a pixel off the
|
||||
other: the two together read as one segmented control. */}
|
||||
<span className="flex shrink-0 items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void sync.syncNow(link.id)}
|
||||
disabled={busy}
|
||||
className="flex h-9 items-center gap-2 rounded-lg border border-edge bg-surface px-3 text-caption font-medium text-content-secondary transition-colors hover:bg-surface-hover disabled:opacity-60"
|
||||
>
|
||||
<RefreshCw size={14} className={busy ? 'animate-spin' : ''} />
|
||||
{/* Taken out of the layout below sm rather than out of the document:
|
||||
`hidden` left a screen reader announcing a bare "button" there,
|
||||
and an aria-label would have frozen the name while the visible
|
||||
text still changes to "Syncing". */}
|
||||
<span className="sr-only sm:not-sr-only">{busy ? t('docsync.syncing') : t('docsync.syncNow')}</span>
|
||||
</button>
|
||||
{/* Asked first, as the phone does: the button sits a hand's width
|
||||
from "Sync now", and a binding cannot be put back. Rebinding the
|
||||
same folder starts from nothing and copies both sides over
|
||||
again. */}
|
||||
{canManage && (
|
||||
<Tooltip label={t('docsync.unlink')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setConfirmUnlink(true)}
|
||||
className="grid h-9 w-9 place-items-center rounded-lg border border-edge bg-surface text-content-muted transition-colors hover:bg-danger-soft hover:text-danger"
|
||||
aria-label={t('docsync.unlink')}
|
||||
>
|
||||
<Link2Off size={14} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
{notice && (
|
||||
<p className="mx-4 mb-3 flex items-start gap-2 rounded-lg bg-warning-soft px-3 py-2 text-caption text-warning">
|
||||
<AlertTriangle size={13} className="mt-px shrink-0" />
|
||||
<span className="min-w-0 flex-1">{notice}</span>
|
||||
{/* The one state a person can act on from here. Without this the
|
||||
only way past a rotated token was the API: the sidebar opens the
|
||||
form for a store that has no connection yet, and this one has. */}
|
||||
{reconnect && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={reconnect}
|
||||
className="shrink-0 rounded-lg border border-edge bg-surface px-2.5 py-1 text-caption font-medium text-content transition-colors hover:bg-surface-hover"
|
||||
>
|
||||
{t('docsync.binding.reconnect')}
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={confirmUnlink}
|
||||
onClose={() => setConfirmUnlink(false)}
|
||||
onConfirm={() => void sync.removeLink(link.id)}
|
||||
title={t('docsync.unlink')}
|
||||
message={t('docsync.confirmUnlink')}
|
||||
confirmLabel={t('docsync.unlink')}
|
||||
/>
|
||||
|
||||
<div className="px-4 pb-3">
|
||||
<DocSyncFlow
|
||||
direction={link.direction}
|
||||
providerId={link.providerId}
|
||||
providerName={providerName}
|
||||
running={busy}
|
||||
holdings={link.holdings ?? { inTrek: 0, atProvider: 0, paired: 0, missing: 0 }}
|
||||
disabled={!canManage}
|
||||
onChange={(next: SyncDirection) => void sync.updateLink(link.id, { direction: next })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{canManage && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(!open)}
|
||||
aria-expanded={open}
|
||||
className="flex w-full items-center gap-1.5 border-t border-edge-faint px-4 py-2.5 text-left text-caption text-content-muted transition-colors hover:bg-surface-hover"
|
||||
>
|
||||
<ChevronDown size={13} className={`transition-transform ${open ? 'rotate-180' : ''}`} />
|
||||
{t('docsync.binding.settings')}
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="space-y-3 border-t border-edge-faint bg-surface-secondary px-4 py-3">
|
||||
<Row label={t('docsync.deletePolicy')} hint={t('docsync.binding.deleteHint')}>
|
||||
<CustomSelect
|
||||
size="sm"
|
||||
value={link.deletePolicy}
|
||||
onChange={v => void sync.updateLink(link.id, { deletePolicy: String(v) })}
|
||||
options={[
|
||||
{ value: 'unlink', label: t('docsync.deleteUnlink') },
|
||||
{ value: 'trash', label: t('docsync.deleteTrash') },
|
||||
]}
|
||||
/>
|
||||
</Row>
|
||||
|
||||
<Row label={t('docsync.conflictPolicy')} hint={t('docsync.binding.conflictHint')}>
|
||||
<CustomSelect
|
||||
size="sm"
|
||||
value={link.conflictPolicy}
|
||||
onChange={v => void sync.updateLink(link.id, { conflictPolicy: String(v) })}
|
||||
options={CONFLICT_POLICIES.map(p => ({ value: p, label: t(conflictPolicyKey(p)) }))}
|
||||
/>
|
||||
</Row>
|
||||
|
||||
<Row label={t('docsync.syncEnabled')} hint={t('docsync.binding.autoHint')}>
|
||||
<span className="flex justify-end">
|
||||
<ToggleSwitch
|
||||
on={link.syncEnabled}
|
||||
onToggle={() => void sync.updateLink(link.id, { syncEnabled: !link.syncEnabled })}
|
||||
/>
|
||||
</span>
|
||||
</Row>
|
||||
|
||||
{/* Only where TREK could not subscribe itself. Papra's webhook CRUD
|
||||
is closed to API keys and Nextcloud's needs admin rights, so the
|
||||
person pastes this in by hand; polling carries it either way. */}
|
||||
{link.webhookUrl && (
|
||||
<div>
|
||||
{/* Same tier as the two rows above it: this is the third
|
||||
setting, not a footnote to the second. */}
|
||||
<span className="block text-body text-content">{t('docsync.binding.webhookTitle')}</span>
|
||||
<p className="mt-1 text-caption text-content-muted">{t('docsync.webhookHint')}</p>
|
||||
<div className="mt-1.5 flex items-stretch gap-1.5">
|
||||
<code className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap rounded-lg border border-edge bg-surface px-2.5 py-1.5 text-caption text-content-secondary">
|
||||
{link.webhookUrl}
|
||||
</code>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void copyWebhook()}
|
||||
className="flex shrink-0 items-center gap-1.5 rounded-lg border border-edge px-2.5 text-caption text-content-secondary transition-colors hover:bg-surface-hover"
|
||||
>
|
||||
{copied ? <Check size={13} className="text-success" /> : <Copy size={13} />}
|
||||
{copied ? t('docsync.binding.copied') : t('docsync.binding.copy')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<span className="min-w-0">
|
||||
<span className="block text-body text-content">{label}</span>
|
||||
{hint && <span className="mt-0.5 block text-caption text-content-muted">{hint}</span>}
|
||||
</span>
|
||||
<span className="w-56 shrink-0">{children}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||
import { relativeTime } from '../../../utils/relativeTime'
|
||||
|
||||
/**
|
||||
* The small shared pieces of the document-sync dialog.
|
||||
*
|
||||
* They live together because the panel, the store list and the binding card all
|
||||
* label the same five sync states, and three hand-written copies of that mapping
|
||||
* is how one of them ends up saying something different from the other two.
|
||||
*/
|
||||
|
||||
export type Tone = 'neutral' | 'accent' | 'success' | 'warning' | 'danger'
|
||||
|
||||
const TONES: Record<Tone, string> = {
|
||||
neutral: 'bg-surface-secondary text-content-secondary',
|
||||
accent: 'bg-accent-subtle text-accent-on',
|
||||
success: 'bg-success-soft text-success',
|
||||
warning: 'bg-warning-soft text-warning',
|
||||
danger: 'bg-danger-soft text-danger',
|
||||
}
|
||||
|
||||
/** A count or a short label, on a tinted pill. */
|
||||
export function Badge({
|
||||
tone = 'neutral',
|
||||
icon,
|
||||
children,
|
||||
title,
|
||||
}: {
|
||||
tone?: Tone
|
||||
icon?: ReactNode
|
||||
children: ReactNode
|
||||
title?: string
|
||||
}) {
|
||||
return (
|
||||
<span
|
||||
title={title}
|
||||
className={`inline-flex items-center gap-1.5 whitespace-nowrap rounded-full px-2 py-0.5 text-caption font-medium ${TONES[tone]}`}
|
||||
>
|
||||
{icon}
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The tone each sync state carries, in one place. */
|
||||
function toneForState(state: string): Tone {
|
||||
if (state === 'ok') return 'success'
|
||||
if (state === 'partial') return 'warning'
|
||||
if (state === 'never') return 'neutral'
|
||||
return 'danger'
|
||||
}
|
||||
|
||||
/**
|
||||
* A binding's state as a dot plus its word.
|
||||
*
|
||||
* A dot alone is a colour puzzle and a word alone is easy to skim past; the two
|
||||
* together survive both colour blindness and a glance.
|
||||
*/
|
||||
export function StateBadge({ state, compact }: { state: string; compact?: boolean }) {
|
||||
const { t } = useTranslation()
|
||||
const tone = toneForState(state)
|
||||
const dot =
|
||||
tone === 'success' ? 'bg-success'
|
||||
: tone === 'warning' ? 'bg-warning'
|
||||
: tone === 'danger' ? 'bg-danger'
|
||||
: 'bg-content-faint'
|
||||
|
||||
if (compact) return <span className={`h-2 w-2 shrink-0 rounded-full ${dot}`} title={t(`docsync.linkState.${state}`)} />
|
||||
|
||||
return (
|
||||
<Badge tone={tone} icon={<span className={`h-1.5 w-1.5 rounded-full ${dot}`} />}>
|
||||
{t(`docsync.linkState.${state}`)}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
/** "2h ago", or "never" when a binding has not run yet. */
|
||||
export function LastRun({ at }: { at: string | null }) {
|
||||
const { t, language, locale } = useTranslation()
|
||||
if (!at) return <span className="text-content-faint">{t('docsync.binding.neverRun')}</span>
|
||||
const ms = Date.parse(at)
|
||||
if (Number.isNaN(ms)) return null
|
||||
return <span title={new Date(ms).toLocaleString(locale)}>{relativeTime(ms, language)}</span>
|
||||
}
|
||||
|
||||
/**
|
||||
* The three answers to "both sides changed", in the order they are offered.
|
||||
*
|
||||
* Shared because the phone offers them as one cycling button and the desktop as
|
||||
* a dropdown: two lists would drift, and a binding would then say one thing on
|
||||
* a laptop and another on a phone.
|
||||
*/
|
||||
export const CONFLICT_POLICIES = ['manual', 'trek_wins', 'provider_wins'] as const
|
||||
|
||||
export type ConflictPolicy = (typeof CONFLICT_POLICIES)[number]
|
||||
|
||||
/** The next answer in that ring, for the phone's single button. */
|
||||
export function nextConflictPolicy(current: string): ConflictPolicy {
|
||||
const at = (CONFLICT_POLICIES as readonly string[]).indexOf(current)
|
||||
return CONFLICT_POLICIES[(at + 1) % CONFLICT_POLICIES.length]
|
||||
}
|
||||
|
||||
/** The label key for one answer. */
|
||||
export function conflictPolicyKey(policy: string): string {
|
||||
return `docsync.onConflict.${(CONFLICT_POLICIES as readonly string[]).includes(policy) ? policy : 'manual'}`
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
// FE-DOCSYNC-CONNECT-001 to FE-DOCSYNC-CONNECT-027
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import en from '@trek/shared/i18n/en'
|
||||
import { render, screen, fireEvent, waitFor, act, within } from '../../../../tests/helpers/render'
|
||||
import type { DocSyncConnection, DocSyncProvider } from './useDocSync'
|
||||
|
||||
/** What the app really shows: `en` is bundled, so `t()` resolves for real here. */
|
||||
const tx = (key: string): string => (en as unknown as Record<string, string>)[key] ?? key
|
||||
|
||||
const providers = vi.fn(async (_tripId: number | string): Promise<unknown> => [])
|
||||
const listConnections = vi.fn(async (_tripId: number | string): Promise<unknown> => [])
|
||||
const listLinks = vi.fn(async (_tripId: number | string): Promise<unknown> => [])
|
||||
const status = vi.fn(async (_tripId: number | string): Promise<unknown> => ({ items: {}, links: [] }))
|
||||
const saveConnection = vi.fn(async (_tripId: number | string, _data: unknown): Promise<unknown> => ({ id: 1 }))
|
||||
const testConnection = vi.fn(async (_tripId: number | string, _data: unknown): Promise<unknown> => ({ connected: true }))
|
||||
|
||||
vi.mock('../../../api/client', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../../api/client')>()
|
||||
return {
|
||||
...actual,
|
||||
docsyncApi: {
|
||||
...actual.docsyncApi,
|
||||
providers: (tripId: number | string) => providers(tripId),
|
||||
status: (tripId: number | string) => status(tripId),
|
||||
listConnections: (tripId: number | string) => listConnections(tripId),
|
||||
listLinks: (tripId: number | string) => listLinks(tripId),
|
||||
saveConnection: (tripId: number | string, data: unknown) => saveConnection(tripId, data),
|
||||
testConnection: (tripId: number | string, data: unknown) => testConnection(tripId, data),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
import DocSyncConnectModal from './DocSyncConnectModal'
|
||||
import { useDocSync } from './useDocSync'
|
||||
|
||||
const TRIP_ID = 42
|
||||
|
||||
const nextcloud: DocSyncProvider = {
|
||||
id: 'nextcloud',
|
||||
name: 'Nextcloud',
|
||||
description: 'Two-way document sync with a Nextcloud folder over WebDAV',
|
||||
icon: 'Cloud',
|
||||
available: true,
|
||||
fields: [
|
||||
{ field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://cloud.example.com', hint: null, required: true, secret: false },
|
||||
{ field_key: 'login_name', label: 'providerUsername', input_type: 'text', placeholder: 'username', hint: 'hintNextcloudLogin', required: true, secret: false },
|
||||
{ field_key: 'app_password', label: 'providerAppPassword', input_type: 'password', placeholder: 'app password', hint: 'hintNextcloudAppPassword', required: true, secret: true },
|
||||
{ field_key: 'base_path', label: 'providerBasePath', input_type: 'text', placeholder: '/TREK', hint: 'hintBasePath', required: false, secret: false },
|
||||
{ field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: false, secret: false },
|
||||
],
|
||||
}
|
||||
|
||||
/** Synology is the one provider with a secret that is NOT a password box (the OTP). */
|
||||
const synology: DocSyncProvider = {
|
||||
id: 'synologydrive',
|
||||
name: 'Synology Drive',
|
||||
description: 'Two-way document sync with a folder on a Synology NAS',
|
||||
icon: 'HardDrive',
|
||||
available: true,
|
||||
fields: [
|
||||
{ field_key: 'base_url', label: 'providerUrl', input_type: 'url', placeholder: 'https://nas.example.com:5001', hint: 'hintSynologyUrl', required: true, secret: false },
|
||||
{ field_key: 'password', label: 'providerPassword', input_type: 'password', placeholder: 'password', hint: null, required: true, secret: true },
|
||||
{ field_key: 'otp_code', label: 'providerOTP', input_type: 'text', placeholder: '123456', hint: 'hintSynologyOtp', required: false, secret: true },
|
||||
{ field_key: 'allow_insecure_tls', label: 'allowInsecureTls', input_type: 'checkbox', placeholder: null, hint: null, required: false, secret: false },
|
||||
],
|
||||
}
|
||||
|
||||
const connection = (overrides: Partial<DocSyncConnection> = {}): DocSyncConnection => ({
|
||||
id: 9,
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
settings: { login_name: 'maurice', base_path: '/Archive/TREK' },
|
||||
secrets: { app_password: 'stored' },
|
||||
allowInsecureTls: false,
|
||||
lastProbeState: 'ok',
|
||||
lastProbeError: null,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
function Harness({
|
||||
provider,
|
||||
onClose,
|
||||
onConnected,
|
||||
waitForConnection,
|
||||
}: {
|
||||
provider: DocSyncProvider
|
||||
onClose: () => void
|
||||
onConnected: (providerId: string) => void
|
||||
/**
|
||||
* Hold the dialog back until the stored connection is in hand, the way the
|
||||
* panel does: it only offers "connect" once it knows what is already there.
|
||||
*/
|
||||
waitForConnection?: boolean
|
||||
}) {
|
||||
const sync = useDocSync(TRIP_ID, true)
|
||||
if (waitForConnection && !sync.connectionFor(provider.id)) return null
|
||||
return <DocSyncConnectModal provider={provider} sync={sync} onClose={onClose} onConnected={onConnected} />
|
||||
}
|
||||
|
||||
/** Let the hook's initial load land before anything is asserted. */
|
||||
async function flush() {
|
||||
await act(async () => {
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
})
|
||||
}
|
||||
|
||||
async function open(provider: DocSyncProvider = nextcloud, waitForConnection = false) {
|
||||
const onClose = vi.fn()
|
||||
const onConnected = vi.fn()
|
||||
const utils = render(
|
||||
<Harness provider={provider} onClose={onClose} onConnected={onConnected} waitForConnection={waitForConnection} />,
|
||||
)
|
||||
await flush()
|
||||
return { ...utils, onClose, onConnected }
|
||||
}
|
||||
|
||||
const testButton = () => screen.getByRole('button', { name: tx('docsync.test') })
|
||||
const connectButton = () => screen.getByRole('button', { name: tx('docsync.connect.submit') })
|
||||
|
||||
function fillNextcloud() {
|
||||
fireEvent.change(screen.getByPlaceholderText('https://cloud.example.com'), { target: { value: 'https://cloud.example.com' } })
|
||||
fireEvent.change(screen.getByPlaceholderText('username'), { target: { value: 'maurice' } })
|
||||
fireEvent.change(screen.getByPlaceholderText('app password'), { target: { value: 'app-pw' } })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
providers.mockResolvedValue([])
|
||||
listConnections.mockResolvedValue([])
|
||||
listLinks.mockResolvedValue([])
|
||||
status.mockResolvedValue({ items: {}, links: [] })
|
||||
saveConnection.mockResolvedValue({ id: 1 })
|
||||
testConnection.mockResolvedValue({ connected: true })
|
||||
})
|
||||
|
||||
describe('DocSyncConnectModal form', () => {
|
||||
it('FE-DOCSYNC-CONNECT-001: renders one labelled box per provider field and leaves the TLS field to the switch', async () => {
|
||||
const { baseElement } = await open()
|
||||
|
||||
expect(screen.getByText(tx('docsync.providerUrl'))).toBeInTheDocument()
|
||||
expect(screen.getByText(tx('docsync.providerUsername'))).toBeInTheDocument()
|
||||
expect(screen.getByText(tx('docsync.providerAppPassword'))).toBeInTheDocument()
|
||||
expect(screen.getByText(tx('docsync.providerBasePath'))).toBeInTheDocument()
|
||||
// allow_insecure_tls is a switch, not a fifth text box
|
||||
expect(baseElement.querySelectorAll('input')).toHaveLength(4)
|
||||
expect(screen.getByText(tx('docsync.allowInsecureTls'))).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { pressed: false })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-002: a password field is masked and the other boxes are not', async () => {
|
||||
await open()
|
||||
|
||||
expect(screen.getByPlaceholderText('app password')).toHaveAttribute('type', 'password')
|
||||
expect(screen.getByPlaceholderText('https://cloud.example.com')).toHaveAttribute('type', 'text')
|
||||
expect(screen.getByPlaceholderText('username')).toHaveAttribute('type', 'text')
|
||||
expect(screen.getByPlaceholderText('/TREK')).toHaveAttribute('type', 'text')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-003: a secret the provider declares as plain text stays readable', async () => {
|
||||
await open(synology)
|
||||
|
||||
expect(screen.getByPlaceholderText('password')).toHaveAttribute('type', 'password')
|
||||
expect(screen.getByPlaceholderText('123456')).toHaveAttribute('type', 'text')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-004: only the optional fields carry the optional mark', async () => {
|
||||
await open()
|
||||
const optional = tx('docsync.connect.optional')
|
||||
|
||||
const basePath = screen.getByPlaceholderText('/TREK').closest('label') as HTMLElement
|
||||
expect(within(basePath).getByText(optional)).toBeInTheDocument()
|
||||
|
||||
for (const placeholder of ['https://cloud.example.com', 'username', 'app password']) {
|
||||
const field = screen.getByPlaceholderText(placeholder).closest('label') as HTMLElement
|
||||
expect(within(field).queryByText(optional)).not.toBeInTheDocument()
|
||||
}
|
||||
expect(screen.getAllByText(optional)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-005: a field hint is translated, and a field without one gets no line', async () => {
|
||||
await open()
|
||||
|
||||
const username = screen.getByPlaceholderText('username').closest('label') as HTMLElement
|
||||
expect(within(username).getByText(tx('docsync.hintNextcloudLogin'))).toBeInTheDocument()
|
||||
|
||||
const baseUrl = screen.getByPlaceholderText('https://cloud.example.com').closest('label') as HTMLElement
|
||||
expect(baseUrl.textContent?.trim()).toBe(tx('docsync.providerUrl'))
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-006: the dialog is headed by the provider and explains what it will do', async () => {
|
||||
await open()
|
||||
|
||||
expect(screen.getByRole('heading', { name: nextcloud.name })).toBeInTheDocument()
|
||||
expect(screen.getByText(tx('docsync.connect.about.nextcloud'))).toBeInTheDocument()
|
||||
expect(screen.getByText(tx('docsync.connect.insecureHint'))).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-007: escape closes the dialog without saving', async () => {
|
||||
const { onClose, onConnected } = await open()
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
expect(onConnected).not.toHaveBeenCalled()
|
||||
expect(saveConnection).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncConnectModal required fields', () => {
|
||||
it('FE-DOCSYNC-CONNECT-008: nothing can be saved or probed while a required field is empty', async () => {
|
||||
await open()
|
||||
|
||||
expect(connectButton()).toBeDisabled()
|
||||
expect(testButton()).toBeDisabled()
|
||||
|
||||
fireEvent.click(connectButton())
|
||||
fireEvent.click(testButton())
|
||||
|
||||
expect(saveConnection).not.toHaveBeenCalled()
|
||||
expect(testConnection).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-009: a missing password alone is enough to refuse the save', async () => {
|
||||
await open()
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('https://cloud.example.com'), { target: { value: 'https://cloud.example.com' } })
|
||||
fireEvent.change(screen.getByPlaceholderText('username'), { target: { value: 'maurice' } })
|
||||
|
||||
expect(connectButton()).toBeDisabled()
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('app password'), { target: { value: 'app-pw' } })
|
||||
|
||||
expect(connectButton()).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-010: an address of nothing but spaces does not count as filled', async () => {
|
||||
await open()
|
||||
|
||||
fillNextcloud()
|
||||
expect(connectButton()).toBeEnabled()
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('https://cloud.example.com'), { target: { value: ' ' } })
|
||||
|
||||
expect(connectButton()).toBeDisabled()
|
||||
expect(testButton()).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-011: an empty optional field does not hold the save back', async () => {
|
||||
const { onConnected } = await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(connectButton())
|
||||
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalled())
|
||||
expect(saveConnection).toHaveBeenCalledWith(TRIP_ID, {
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: { base_url: 'https://cloud.example.com', login_name: 'maurice', app_password: 'app-pw' },
|
||||
allowInsecureTls: false,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncConnectModal probe verdict', () => {
|
||||
it('FE-DOCSYNC-CONNECT-012: the probe carries the typed address, credentials and TLS choice', async () => {
|
||||
await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.change(screen.getByPlaceholderText('/TREK'), { target: { value: '/Archive' } })
|
||||
fireEvent.click(testButton())
|
||||
|
||||
await waitFor(() => expect(testConnection).toHaveBeenCalledWith(TRIP_ID, {
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: {
|
||||
base_url: 'https://cloud.example.com',
|
||||
login_name: 'maurice',
|
||||
app_password: 'app-pw',
|
||||
base_path: '/Archive',
|
||||
},
|
||||
allowInsecureTls: false,
|
||||
}))
|
||||
expect(saveConnection).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-013: a reachable provider names the account it signed in as', async () => {
|
||||
testConnection.mockResolvedValueOnce({ connected: true, account: 'maurice' })
|
||||
await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(testButton())
|
||||
|
||||
const line = tx('docsync.connect.okAs').replace('{account}', 'maurice')
|
||||
expect(await screen.findByText(line)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-014: a reachable provider without an account just reports the connection', async () => {
|
||||
testConnection.mockResolvedValueOnce({ connected: true })
|
||||
await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(testButton())
|
||||
|
||||
expect(await screen.findByText(tx('docsync.connected'))).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-015: a refused credential shows the translated reason', async () => {
|
||||
testConnection.mockResolvedValueOnce({ connected: false, error: 'unauthorized' })
|
||||
await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(testButton())
|
||||
|
||||
const line = await screen.findByText(tx('docsync.error.unauthorized'))
|
||||
expect(line).toBeInTheDocument()
|
||||
expect(screen.queryByText(tx('docsync.connected'))).not.toBeInTheDocument()
|
||||
expect(line.parentElement?.querySelector('svg')?.getAttribute('class')).not.toMatch(/shield/)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-016: an address TREK itself blocked is marked with the shield, not the warning', async () => {
|
||||
testConnection.mockResolvedValueOnce({ connected: false, error: 'ssrf_blocked' })
|
||||
await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(testButton())
|
||||
|
||||
const line = await screen.findByText(tx('docsync.error.ssrf_blocked'))
|
||||
expect(line.parentElement?.querySelector('svg')?.getAttribute('class')).toMatch(/shield/)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-017: a failure with no reason falls back to the unknown message', async () => {
|
||||
testConnection.mockResolvedValueOnce({ connected: false })
|
||||
await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(testButton())
|
||||
|
||||
expect(await screen.findByText(tx('docsync.error.unknown'))).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-018: a request that throws still lands as a verdict rather than an empty footer', async () => {
|
||||
testConnection.mockRejectedValueOnce({ response: { data: { error: 'timeout' } } })
|
||||
await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(testButton())
|
||||
|
||||
expect(await screen.findByText(tx('docsync.error.timeout'))).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-019: while the probe runs the dialog says so and the probe button is locked', async () => {
|
||||
let settle: (value: unknown) => void = () => {}
|
||||
testConnection.mockImplementationOnce(() => new Promise(resolve => { settle = resolve }))
|
||||
await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(testButton())
|
||||
|
||||
expect(screen.getByText(tx('docsync.connect.testing'))).toBeInTheDocument()
|
||||
expect(testButton()).toBeDisabled()
|
||||
|
||||
await act(async () => {
|
||||
settle({ connected: true })
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
})
|
||||
|
||||
expect(screen.queryByText(tx('docsync.connect.testing'))).not.toBeInTheDocument()
|
||||
expect(screen.getByText(tx('docsync.connected'))).toBeInTheDocument()
|
||||
expect(testButton()).toBeEnabled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncConnectModal saving', () => {
|
||||
it('FE-DOCSYNC-CONNECT-020: a successful save reports the connected provider upward', async () => {
|
||||
const { onConnected, onClose } = await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(connectButton())
|
||||
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalledWith('nextcloud'))
|
||||
expect(onConnected).toHaveBeenCalledTimes(1)
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
// the freshly stored connection is read back, not assumed
|
||||
expect(listConnections).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-021: a rejected save reports nothing upward and leaves the form standing', async () => {
|
||||
saveConnection.mockRejectedValueOnce({ response: { data: { error: 'unauthorized' } } })
|
||||
const { onConnected, onClose } = await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(connectButton())
|
||||
|
||||
await waitFor(() => expect(saveConnection).toHaveBeenCalled())
|
||||
expect(onConnected).not.toHaveBeenCalled()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
expect(screen.getByPlaceholderText('app password')).toHaveValue('app-pw')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-022: the save button is locked while the write is in flight', async () => {
|
||||
let settle: (value: unknown) => void = () => {}
|
||||
saveConnection.mockImplementationOnce(() => new Promise(resolve => { settle = resolve }))
|
||||
const { onConnected } = await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(connectButton())
|
||||
|
||||
expect(connectButton()).toBeDisabled()
|
||||
|
||||
await act(async () => {
|
||||
settle({ id: 1 })
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
})
|
||||
|
||||
expect(onConnected).toHaveBeenCalledWith('nextcloud')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-023: the self-signed switch starts off and travels with the request', async () => {
|
||||
await open()
|
||||
|
||||
fillNextcloud()
|
||||
fireEvent.click(screen.getByRole('button', { pressed: false }))
|
||||
|
||||
expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(connectButton())
|
||||
|
||||
await waitFor(() => expect(saveConnection).toHaveBeenCalledWith(TRIP_ID, expect.objectContaining({ allowInsecureTls: true })))
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncConnectModal with a connection already stored', () => {
|
||||
it('FE-DOCSYNC-CONNECT-024: the stored settings come back, the saved secret is only hinted at, and it saves untouched', async () => {
|
||||
listConnections.mockResolvedValue([connection({ settings: { login_name: 'maurice', base_path: '/Archive/TREK', app_password: 'never-echo-me' } })])
|
||||
const { onConnected } = await open(nextcloud, true)
|
||||
|
||||
expect(await screen.findByPlaceholderText('••••••••')).toBeInTheDocument()
|
||||
expect(screen.getByPlaceholderText('username')).toHaveValue('maurice')
|
||||
expect(screen.getByPlaceholderText('/TREK')).toHaveValue('/Archive/TREK')
|
||||
// a secret is never echoed back into the box, whatever the settings blob holds
|
||||
expect(screen.getByPlaceholderText('••••••••')).toHaveValue('')
|
||||
|
||||
// the stored secret counts as filled, so nothing has to be retyped
|
||||
expect(connectButton()).toBeEnabled()
|
||||
fireEvent.click(connectButton())
|
||||
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalledWith('nextcloud'))
|
||||
expect(saveConnection).toHaveBeenCalledWith(TRIP_ID, {
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example.com',
|
||||
credentials: {},
|
||||
allowInsecureTls: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-025: the stored self-signed choice is the one the switch starts on', async () => {
|
||||
listConnections.mockResolvedValue([connection({ allowInsecureTls: true })])
|
||||
await open(nextcloud, true)
|
||||
|
||||
expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-026: a connection that lands after the dialog is open still sets the switch', async () => {
|
||||
// The switch used to be seeded by a useState initialiser, so it only ever
|
||||
// read the connection that existed at the moment the dialog mounted: a
|
||||
// stored "allow self-signed" showed as off, and the next save wrote that
|
||||
// back. A security switch turning itself off unasked is the bad version of
|
||||
// a stale field, so it now reads through until somebody touches it.
|
||||
listConnections.mockResolvedValue([connection({ allowInsecureTls: true })])
|
||||
await open(nextcloud, false)
|
||||
|
||||
await screen.findByPlaceholderText('••••••••')
|
||||
await waitFor(() => expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-CONNECT-027: the stored address is shown as well as submitted', async () => {
|
||||
listConnections.mockResolvedValue([connection()])
|
||||
const { onConnected } = await open(nextcloud, true)
|
||||
|
||||
await screen.findByPlaceholderText('••••••••')
|
||||
// The address is a column of its own rather than a settings entry. Reading
|
||||
// it out of settings left the box empty over its placeholder while the form
|
||||
// went on submitting the stored value, the field and the request quietly
|
||||
// disagreeing about what the connection is.
|
||||
await waitFor(() =>
|
||||
expect(screen.getByPlaceholderText('https://cloud.example.com')).toHaveValue('https://cloud.example.com'),
|
||||
)
|
||||
|
||||
fireEvent.click(connectButton())
|
||||
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalled())
|
||||
expect(saveConnection).toHaveBeenCalledWith(TRIP_ID, expect.objectContaining({ baseUrl: 'https://cloud.example.com' }))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,189 @@
|
||||
import { useState } from 'react'
|
||||
import { AlertTriangle, Check, Loader2, ShieldAlert } from 'lucide-react'
|
||||
import Modal from '../../shared/Modal'
|
||||
import ToggleSwitch from '../../Settings/ToggleSwitch'
|
||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||
import { useConnectForm } from './useConnectForm'
|
||||
import { Badge } from './DocSyncBits'
|
||||
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/DocumentProviderIcons'
|
||||
import type { DocSyncProvider, useDocSync } from './useDocSync'
|
||||
|
||||
/**
|
||||
* Connecting a store, as a dialog rather than a panel that unfolds in place.
|
||||
*
|
||||
* Entering a URL and a token is a task with a beginning and an end, and doing it
|
||||
* inside the list meant the list jumped around while someone typed. The dialog
|
||||
* also gives the probe result somewhere to live that is not a line of text
|
||||
* squeezed between two fields.
|
||||
*/
|
||||
export default function DocSyncConnectModal({
|
||||
provider,
|
||||
sync,
|
||||
onClose,
|
||||
onConnected,
|
||||
}: {
|
||||
provider: DocSyncProvider
|
||||
sync: ReturnType<typeof useDocSync>
|
||||
onClose: () => void
|
||||
onConnected: (providerId: string) => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const existing = sync.connectionFor(provider.id)
|
||||
const Icon = DOCUMENT_PROVIDER_ICONS[provider.id]
|
||||
|
||||
const form = useConnectForm(provider, existing, sync)
|
||||
const [verdict, setVerdict] = useState<{ connected: boolean; account?: string; error?: string } | null>(null)
|
||||
|
||||
const test = async () => setVerdict(await form.probe())
|
||||
|
||||
const save = async () => {
|
||||
if (await form.save()) onConnected(provider.id)
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
size="md"
|
||||
title={
|
||||
<span className="flex items-center gap-2.5">
|
||||
{Icon && <Icon className="h-5 w-5 text-content" />}
|
||||
<span>{provider.name}</span>
|
||||
</span>
|
||||
}
|
||||
footer={
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<Verdict verdict={verdict} busy={sync.busy === 'test'} failure={sync.error} />
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void test()}
|
||||
disabled={!form.complete || sync.busy === 'test'}
|
||||
className="rounded-lg border border-edge px-3.5 py-2 text-body text-content-secondary transition-colors hover:bg-surface-hover disabled:opacity-50"
|
||||
>
|
||||
{t('docsync.test')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void save()}
|
||||
disabled={!form.complete || sync.busy === 'save'}
|
||||
className="flex items-center gap-2 rounded-lg bg-accent px-3.5 py-2 text-body font-medium text-accent-text transition-opacity hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{sync.busy === 'save' && <Loader2 size={14} className="animate-spin" />}
|
||||
{t('docsync.connect.submit')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-caption text-content-muted">{t(`docsync.connect.about.${provider.id}`)}</p>
|
||||
|
||||
{form.fields.map(f => (
|
||||
<Field
|
||||
key={f.field_key}
|
||||
label={t(form.labelKey(f))}
|
||||
hint={form.hintKey(f) ? t(form.hintKey(f) as string) : undefined}
|
||||
required={f.required}
|
||||
>
|
||||
<input
|
||||
type={f.input_type === 'password' ? 'password' : 'text'}
|
||||
value={form.valueOf(f.field_key)}
|
||||
placeholder={form.placeholderOf(f)}
|
||||
onChange={e => form.setValue(f.field_key, e.target.value)}
|
||||
className="w-full rounded-lg border border-edge bg-surface-input px-3 py-2.5 text-body text-content ring-accent transition-shadow placeholder:text-content-faint focus:outline-none focus:ring-2"
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
|
||||
<label className="flex items-start justify-between gap-4 rounded-lg border border-edge bg-surface-secondary px-3 py-2.5">
|
||||
<span className="min-w-0">
|
||||
<span className="block text-body text-content">{t('docsync.allowInsecureTls')}</span>
|
||||
<span className="mt-0.5 block text-caption text-content-muted">
|
||||
{t('docsync.connect.insecureHint')}
|
||||
</span>
|
||||
</span>
|
||||
<span className="shrink-0 pt-0.5">
|
||||
<ToggleSwitch on={form.insecureTls} onToggle={() => form.setInsecureTls(!form.insecureTls)} />
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
function Field({
|
||||
label,
|
||||
hint,
|
||||
required,
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
hint?: string
|
||||
required?: boolean
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<label className="block">
|
||||
<span className="mb-1.5 flex items-center gap-2">
|
||||
<span className="text-body font-medium text-content">{label}</span>
|
||||
{!required && <Badge tone="neutral">{t('docsync.connect.optional')}</Badge>}
|
||||
</span>
|
||||
{children}
|
||||
{hint && <span className="mt-1.5 block text-caption text-content-muted">{hint}</span>}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
/** The probe result, in the footer where it stays put while the form scrolls. */
|
||||
function Verdict({
|
||||
verdict,
|
||||
busy,
|
||||
failure,
|
||||
}: {
|
||||
verdict: { connected: boolean; account?: string; error?: string } | null
|
||||
busy: boolean
|
||||
/** A call that failed outside the connection test (saving, most of all). */
|
||||
failure: string | null
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
if (busy) {
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-2 text-caption text-content-muted">
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
{t('docsync.connect.testing')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
// A save that the server refused left the dialog open with the button back to
|
||||
// normal and nothing else said, which reads as nothing having happened. The
|
||||
// test verdict wins the space when there is one: it is the more specific
|
||||
// answer and the one the person just asked for.
|
||||
if (!verdict && failure) {
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-2 text-caption text-danger">
|
||||
<AlertTriangle size={14} />
|
||||
<span className="truncate">{t(`docsync.error.${failure}`)}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
if (!verdict) return <span />
|
||||
if (verdict.connected) {
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-2 text-caption text-success">
|
||||
<Check size={14} strokeWidth={2.5} />
|
||||
<span className="truncate">
|
||||
{verdict.account ? t('docsync.connect.okAs', { account: verdict.account }) : t('docsync.connected')}
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
const blocked = verdict.error === 'ssrf_blocked' || verdict.error === 'tls_untrusted'
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-2 text-caption text-danger">
|
||||
{blocked ? <ShieldAlert size={14} /> : <AlertTriangle size={14} />}
|
||||
<span className="truncate">{t(`docsync.error.${verdict.error || 'unknown'}`)}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// FE-DOCSYNC-FLOW-001 to FE-DOCSYNC-FLOW-013
|
||||
|
||||
/**
|
||||
* The direction control of the document-sync dialog.
|
||||
*
|
||||
* Two lanes, each one a direction that is either carrying or idle. The rules
|
||||
* that matter to somebody using it: what each side is holding is readable
|
||||
* before a word is, switching direction means switching a lane off, and the
|
||||
* last lane cannot be switched off, a binding with no direction syncs
|
||||
* nothing, and a dialog that lets you build one has lied about what it does.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import en from '@trek/shared/i18n/en'
|
||||
import { render, screen, fireEvent } from '../../../../tests/helpers/render'
|
||||
import DocSyncFlow, { type FlowHoldings, type SyncDirection } from './DocSyncFlow'
|
||||
|
||||
// The captions come from the locale rather than from English typed out here:
|
||||
// the assertion is "the lane labelled as the outbound one", not the wording.
|
||||
const S = en as unknown as Record<string, string>
|
||||
const OUT = S['docsync.flow.toProvider']
|
||||
const IN = S['docsync.flow.toTrek']
|
||||
|
||||
const onChange = vi.fn()
|
||||
|
||||
const holdings: FlowHoldings = { inTrek: 12, atProvider: 7, paired: 5, missing: 2 }
|
||||
|
||||
function renderFlow(
|
||||
props: Partial<{
|
||||
direction: SyncDirection
|
||||
providerId: string
|
||||
providerName: string
|
||||
holdings: FlowHoldings
|
||||
running: boolean
|
||||
disabled: boolean
|
||||
}> = {},
|
||||
) {
|
||||
return render(
|
||||
<DocSyncFlow
|
||||
direction="both"
|
||||
providerId="paperless"
|
||||
providerName="Paperless"
|
||||
holdings={holdings}
|
||||
onChange={onChange}
|
||||
{...props}
|
||||
/>,
|
||||
)
|
||||
}
|
||||
|
||||
const laneOut = () => screen.getByRole('button', { name: OUT })
|
||||
const laneIn = () => screen.getByRole('button', { name: IN })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('DocSyncFlow ends', () => {
|
||||
it('FE-DOCSYNC-FLOW-001: shows what each side is holding, next to the name of that side', () => {
|
||||
renderFlow()
|
||||
|
||||
expect(screen.getByText('12')).toBeInTheDocument()
|
||||
expect(screen.getByText('7')).toBeInTheDocument()
|
||||
expect(screen.getByText(S['docsync.flow.trek'])).toBeInTheDocument()
|
||||
expect(screen.getByText('Paperless')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-FLOW-002: an empty side reads as zero rather than as nothing', () => {
|
||||
// A healthy binding transfers nothing; the panel must still answer the
|
||||
// question somebody opened it for.
|
||||
renderFlow({ holdings: { inTrek: 0, atProvider: 0, paired: 0, missing: 0 } })
|
||||
|
||||
expect(screen.getAllByText('0')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-FLOW-003: an unrecognised store still names itself', () => {
|
||||
renderFlow({ providerId: 'not-a-provider', providerName: 'Some Store' })
|
||||
|
||||
expect(screen.getByText('Some Store')).toBeInTheDocument()
|
||||
expect(laneOut()).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncFlow direction switching', () => {
|
||||
it('FE-DOCSYNC-FLOW-004: switching the outbound lane off from both leaves inbound only', () => {
|
||||
renderFlow({ direction: 'both' })
|
||||
|
||||
fireEvent.click(laneOut())
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('pull')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-FLOW-005: switching the inbound lane off from both leaves outbound only', () => {
|
||||
renderFlow({ direction: 'both' })
|
||||
|
||||
fireEvent.click(laneIn())
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('push')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-FLOW-006: switching the idle inbound lane on from push gives both ways', () => {
|
||||
renderFlow({ direction: 'push' })
|
||||
|
||||
fireEvent.click(laneIn())
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('both')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-FLOW-007: switching the idle outbound lane on from pull gives both ways', () => {
|
||||
renderFlow({ direction: 'pull' })
|
||||
|
||||
fireEvent.click(laneOut())
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('both')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-FLOW-008: the last carrying lane refuses to switch off (push)', () => {
|
||||
renderFlow({ direction: 'push' })
|
||||
|
||||
fireEvent.click(laneOut())
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
expect(laneOut()).toHaveAttribute('aria-pressed', 'true')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-FLOW-009: the last carrying lane refuses to switch off (pull)', () => {
|
||||
renderFlow({ direction: 'pull' })
|
||||
|
||||
fireEvent.click(laneIn())
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
expect(laneIn()).toHaveAttribute('aria-pressed', 'true')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-FLOW-010: a member who may not edit the binding cannot move the lanes', () => {
|
||||
renderFlow({ direction: 'both', disabled: true })
|
||||
|
||||
expect(laneOut()).toBeDisabled()
|
||||
expect(laneIn()).toBeDisabled()
|
||||
|
||||
fireEvent.click(laneOut())
|
||||
fireEvent.click(laneIn())
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncFlow lane state', () => {
|
||||
it('FE-DOCSYNC-FLOW-011: aria-pressed mirrors each lane in every direction', () => {
|
||||
const { rerender } = renderFlow({ direction: 'both' })
|
||||
expect(laneOut()).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(laneIn()).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
rerender(
|
||||
<DocSyncFlow
|
||||
direction="push"
|
||||
providerId="paperless"
|
||||
providerName="Paperless"
|
||||
holdings={holdings}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
expect(laneOut()).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(laneIn()).toHaveAttribute('aria-pressed', 'false')
|
||||
|
||||
rerender(
|
||||
<DocSyncFlow
|
||||
direction="pull"
|
||||
providerId="paperless"
|
||||
providerName="Paperless"
|
||||
holdings={holdings}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
expect(laneOut()).toHaveAttribute('aria-pressed', 'false')
|
||||
expect(laneIn()).toHaveAttribute('aria-pressed', 'true')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-FLOW-012: only the switched-off lane is hatched', () => {
|
||||
// The hatch is the whole of "this road is not driven on", there is no
|
||||
// other handle for it, so the class is the behaviour here.
|
||||
const { rerender } = renderFlow({ direction: 'both' })
|
||||
expect(laneOut()).not.toHaveClass('trek-docsync-lane-off')
|
||||
expect(laneIn()).not.toHaveClass('trek-docsync-lane-off')
|
||||
|
||||
rerender(
|
||||
<DocSyncFlow
|
||||
direction="push"
|
||||
providerId="paperless"
|
||||
providerName="Paperless"
|
||||
holdings={holdings}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
expect(laneOut()).not.toHaveClass('trek-docsync-lane-off')
|
||||
expect(laneIn()).toHaveClass('trek-docsync-lane-off')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-FLOW-013: the hint tells an editor the lanes are tappable, a reader only what happens', () => {
|
||||
const { rerender } = renderFlow({ direction: 'both' })
|
||||
expect(screen.getByText(S['docsync.flow.summaryEditable.both'])).toBeInTheDocument()
|
||||
|
||||
rerender(
|
||||
<DocSyncFlow
|
||||
direction="both"
|
||||
providerId="paperless"
|
||||
providerName="Paperless"
|
||||
holdings={holdings}
|
||||
disabled
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText(S['docsync.flow.summary.both'])).toBeInTheDocument()
|
||||
expect(screen.queryByText(S['docsync.flow.summaryEditable.both'])).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,213 @@
|
||||
import { ArrowLeft, ArrowRight } from 'lucide-react'
|
||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/DocumentProviderIcons'
|
||||
import TrekIcon from '../../shared/TrekIcon'
|
||||
import { Badge } from './DocSyncBits'
|
||||
|
||||
export type SyncDirection = 'both' | 'pull' | 'push'
|
||||
|
||||
export interface FlowHoldings {
|
||||
/** Documents this trip has in TREK. */
|
||||
inTrek: number
|
||||
/** How many of them the store is holding. */
|
||||
atProvider: number
|
||||
paired: number
|
||||
missing: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The direction control, drawn as what it actually is.
|
||||
*
|
||||
* A document sync has one characteristic picture (two places and things moving
|
||||
* between them), and a dropdown reading "Both ways" hides it behind a word.
|
||||
* Here the two ends carry what each side is holding, the lanes between them
|
||||
* carry the direction, and switching direction means switching a lane off. It
|
||||
* is the one loud element in the dialog; everything around it stays quiet.
|
||||
*
|
||||
* The numbers are standing counts, not the last run's transfers: a binding that
|
||||
* is already in step transferred nothing, and a panel answering "0" on a
|
||||
* healthy connection says nothing at the moment somebody looks at it.
|
||||
*/
|
||||
export default function DocSyncFlow({
|
||||
direction,
|
||||
providerId,
|
||||
providerName,
|
||||
holdings,
|
||||
running,
|
||||
disabled,
|
||||
onChange,
|
||||
}: {
|
||||
direction: SyncDirection
|
||||
providerId: string
|
||||
providerName: string
|
||||
holdings: FlowHoldings
|
||||
/** A run is in flight: the active lanes move while it is. */
|
||||
running?: boolean
|
||||
disabled?: boolean
|
||||
onChange: (next: SyncDirection) => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const Icon = DOCUMENT_PROVIDER_ICONS[providerId]
|
||||
const pushOn = direction === 'both' || direction === 'push'
|
||||
const pullOn = direction === 'both' || direction === 'pull'
|
||||
|
||||
const hint = disabled
|
||||
? t(`docsync.flow.summary.${direction}`, { provider: providerName })
|
||||
: t(`docsync.flow.summaryEditable.${direction}`, { provider: providerName })
|
||||
|
||||
/** Turning a lane off leaves the other one; turning the last one off is refused. */
|
||||
const toggle = (lane: 'push' | 'pull') => {
|
||||
if (disabled) return
|
||||
const nextPush = lane === 'push' ? !pushOn : pushOn
|
||||
const nextPull = lane === 'pull' ? !pullOn : pullOn
|
||||
if (!nextPush && !nextPull) return
|
||||
onChange(nextPush && nextPull ? 'both' : nextPush ? 'push' : 'pull')
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="rounded-2xl border border-edge bg-surface-secondary p-4 sm:p-6">
|
||||
<div className="flex items-center gap-3 sm:gap-5">
|
||||
<End
|
||||
name={t('docsync.flow.trek')}
|
||||
count={holdings.inTrek}
|
||||
glyph={<TrekIcon className="h-6 w-6 text-content" />}
|
||||
/>
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-2.5">
|
||||
<Lane
|
||||
active={pushOn}
|
||||
running={running}
|
||||
disabled={disabled}
|
||||
caption={t('docsync.flow.toProvider')}
|
||||
onClick={() => toggle('push')}
|
||||
>
|
||||
<ArrowRight size={13} strokeWidth={2.75} />
|
||||
</Lane>
|
||||
<Lane
|
||||
active={pullOn}
|
||||
running={running}
|
||||
reverse
|
||||
disabled={disabled}
|
||||
caption={t('docsync.flow.toTrek')}
|
||||
onClick={() => toggle('pull')}
|
||||
>
|
||||
<ArrowLeft size={13} strokeWidth={2.75} />
|
||||
</Lane>
|
||||
|
||||
{/* Under the lanes rather than under the whole bar: it explains what
|
||||
the two buttons above it are doing, and sitting anywhere else
|
||||
makes the reader look for what it refers to. */}
|
||||
<p className="truncate px-1 text-center text-caption text-content-muted">{hint}</p>
|
||||
</div>
|
||||
|
||||
<End
|
||||
name={providerName}
|
||||
count={holdings.atProvider}
|
||||
glyph={Icon ? <Icon className="h-6 w-6 text-content" /> : null}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One end of the flow: the mark, the count, the name.
|
||||
*
|
||||
* The count is the largest thing in the box on purpose: "is my stuff over
|
||||
* there" is the question that makes somebody open this dialog, and it should be
|
||||
* answered before they read a word.
|
||||
*/
|
||||
function End({ name, count, glyph }: { name: string; count: number; glyph: React.ReactNode }) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<div
|
||||
className="flex w-24 shrink-0 flex-col items-center gap-2 rounded-2xl border border-edge bg-surface px-3 py-4 shadow-card sm:w-32"
|
||||
>
|
||||
<span className="grid h-10 w-10 place-items-center rounded-xl bg-surface-secondary">{glyph}</span>
|
||||
|
||||
<span className="flex flex-col items-center gap-1">
|
||||
<span className="text-title font-semibold tabular-nums leading-none text-content">{count}</span>
|
||||
<span className="text-caption uppercase leading-none tracking-wide text-content-faint">
|
||||
{t('docsync.flow.documents')}
|
||||
</span>
|
||||
</span>
|
||||
|
||||
<Badge tone="neutral" title={name}>
|
||||
<span className="max-w-[6.5rem] truncate">{name}</span>
|
||||
</Badge>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One direction, as a track that is either carrying or idle.
|
||||
*
|
||||
* An idle track stays visible as a dashed line, so switching a direction off
|
||||
* reads as a road nobody drives on rather than as something that disappeared.
|
||||
*/
|
||||
function Lane({
|
||||
active,
|
||||
running,
|
||||
disabled,
|
||||
caption,
|
||||
reverse,
|
||||
onClick,
|
||||
children,
|
||||
}: {
|
||||
active: boolean
|
||||
running?: boolean
|
||||
disabled?: boolean
|
||||
caption: string
|
||||
reverse?: boolean
|
||||
onClick: () => void
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const moving = active && running
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
aria-pressed={active}
|
||||
className={[
|
||||
// No border at all, not a transparent one: a border box across the
|
||||
// diagonals still renders a hairline where it meets the corner radius,
|
||||
// and that line reads as a broken frame rather than as a hatch.
|
||||
'group relative flex h-12 items-center gap-3 overflow-hidden rounded-xl px-3 text-caption transition-all duration-200',
|
||||
reverse ? 'flex-row-reverse' : '',
|
||||
active
|
||||
? 'bg-accent-subtle text-accent-on'
|
||||
: 'trek-docsync-lane-off bg-surface text-content-faint',
|
||||
disabled ? 'cursor-default' : active ? 'hover:brightness-[0.98]' : 'hover:text-content-muted',
|
||||
].join(' ')}
|
||||
>
|
||||
<span
|
||||
className={[
|
||||
'relative grid h-7 w-7 shrink-0 place-items-center rounded-lg transition-transform duration-200',
|
||||
active ? 'bg-surface shadow-sm' : 'bg-surface-secondary',
|
||||
disabled ? '' : reverse ? 'group-hover:-translate-x-0.5' : 'group-hover:translate-x-0.5',
|
||||
].join(' ')}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
|
||||
{/* Explicitly aligned to the arrow's side: the dialog inherits a centred
|
||||
text-align, which would otherwise float the label away from it. */}
|
||||
<span className={`relative min-w-0 flex-1 truncate font-medium ${reverse ? 'text-right' : 'text-left'}`}>
|
||||
{caption}
|
||||
</span>
|
||||
|
||||
{/* Only while a run is in flight. An idle lane needs no track (that it is
|
||||
on or off is already in its fill), and a permanent line just asks the
|
||||
reader what it means. */}
|
||||
{moving && (
|
||||
<span
|
||||
aria-hidden
|
||||
className={`trek-docsync-lane-run pointer-events-none absolute inset-x-3 bottom-1.5 h-0.5 rounded-full ${
|
||||
reverse ? 'trek-docsync-lane-run-rev' : ''
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
// FE-DOCSYNC-PANEL-001 to FE-DOCSYNC-PANEL-023
|
||||
|
||||
/**
|
||||
* The document-sync dialog shell (#2391).
|
||||
*
|
||||
* The panel itself owns three decisions: which store is open, which of them a
|
||||
* person is even offered, and whether the "needs a look" list is worth the
|
||||
* space. Everything below it (the binding card, the flow bar, the connect and
|
||||
* scope modals) is tested where it lives; what is exercised here is the shell
|
||||
* around them, driven through the real `useDocSync` against a mocked
|
||||
* `docsyncApi`, because the selection rules are a reaction to what the server
|
||||
* answers rather than to a prop.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import en from '@trek/shared/i18n/en'
|
||||
import { act, render, screen, within, fireEvent, waitFor } from '../../../../tests/helpers/render'
|
||||
|
||||
/** What the dialog actually renders for a key, via the same fallback chain `t()` uses. */
|
||||
const t = (key: string): string => (en as unknown as Record<string, string>)[key] ?? key
|
||||
|
||||
const providers = vi.fn()
|
||||
const listConnections = vi.fn()
|
||||
const listLinks = vi.fn()
|
||||
const status = vi.fn()
|
||||
const deleteLink = vi.fn()
|
||||
const updateLink = vi.fn()
|
||||
const syncNow = vi.fn()
|
||||
const items = vi.fn()
|
||||
const resolve = vi.fn()
|
||||
const saveConnection = vi.fn()
|
||||
|
||||
vi.mock('../../../api/client', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../../api/client')>()
|
||||
return {
|
||||
...actual,
|
||||
docsyncApi: {
|
||||
...actual.docsyncApi,
|
||||
providers: (tripId: number | string) => providers(tripId),
|
||||
listConnections: (tripId: number | string) => listConnections(tripId),
|
||||
listLinks: (tripId: number | string) => listLinks(tripId),
|
||||
status: (tripId: number | string) => status(tripId),
|
||||
deleteLink: (tripId: number | string, linkId: number) => deleteLink(tripId, linkId),
|
||||
updateLink: (tripId: number | string, linkId: number, patch: unknown) => updateLink(tripId, linkId, patch),
|
||||
syncNow: (tripId: number | string, linkId: number, full: boolean) => syncNow(tripId, linkId, full),
|
||||
items: (tripId: number | string, state?: string) => items(tripId, state),
|
||||
resolve: (tripId: number | string, itemId: number, keep: string) => resolve(tripId, itemId, keep),
|
||||
saveConnection: (tripId: number | string, data: unknown) => saveConnection(tripId, data),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
/** Set by the one test that needs a render slower than React's time slice. */
|
||||
let slowCard = false
|
||||
|
||||
vi.mock('./DocSyncBinding', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('./DocSyncBinding')>()
|
||||
const Card = actual.default
|
||||
return {
|
||||
...actual,
|
||||
default: function SlowableBinding(props: Parameters<typeof Card>[0]) {
|
||||
// Busy for longer than the scheduler's 5 ms slice, so the commit that
|
||||
// shows the card leaves its effects for a later task, as a loaded CI
|
||||
// runner does.
|
||||
if (slowCard) {
|
||||
const end = performance.now() + 20
|
||||
while (performance.now() < end) { /* busy */ }
|
||||
}
|
||||
return <Card {...props} />
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
import DocSyncPanel from './DocSyncPanel'
|
||||
import type { DocSyncLink, DocSyncProvider } from './useDocSync'
|
||||
|
||||
const provider = (id: string, name: string, available = true): DocSyncProvider => ({
|
||||
id,
|
||||
name,
|
||||
description: null,
|
||||
icon: id,
|
||||
available,
|
||||
fields: [],
|
||||
})
|
||||
|
||||
const link = (id: number, providerId: string, overrides: Partial<DocSyncLink> = {}): DocSyncLink => ({
|
||||
id,
|
||||
connectionId: id,
|
||||
providerId,
|
||||
scopeKey: `scope-${id}`,
|
||||
remoteLabel: `Folder ${id}`,
|
||||
remoteRootPath: `/TREK/folder-${id}`,
|
||||
direction: 'both',
|
||||
deletePolicy: 'unlink',
|
||||
conflictPolicy: 'manual',
|
||||
syncEnabled: true,
|
||||
lastSyncAt: null,
|
||||
lastSyncState: 'ok',
|
||||
lastSyncError: null,
|
||||
webhookUrl: null,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
/** What the server answers, as one object the tests reshape per case. */
|
||||
function serverHas({
|
||||
providers: p = [],
|
||||
connections = [],
|
||||
links = [],
|
||||
items = {},
|
||||
}: {
|
||||
providers?: DocSyncProvider[]
|
||||
connections?: Array<Record<string, unknown>>
|
||||
links?: DocSyncLink[]
|
||||
items?: Record<string, number>
|
||||
}): void {
|
||||
providers.mockResolvedValue(p)
|
||||
listConnections.mockResolvedValue(connections)
|
||||
listLinks.mockResolvedValue(links)
|
||||
status.mockResolvedValue({
|
||||
items,
|
||||
links: links.map(l => ({ id: l.id, holdings: { inTrek: 3, atProvider: 3, paired: 3, missing: 0 } })),
|
||||
})
|
||||
}
|
||||
|
||||
/** The stored connection a binding runs under. */
|
||||
const connection = (id: number, providerId: string) => ({
|
||||
id,
|
||||
providerId,
|
||||
baseUrl: 'https://docs.example.org',
|
||||
settings: {},
|
||||
secrets: { token: '***' },
|
||||
allowInsecureTls: false,
|
||||
lastProbeState: 'ok',
|
||||
lastProbeError: null,
|
||||
})
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>(r => { resolve = r })
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
const onClose = vi.fn()
|
||||
|
||||
/** The detail column's binding card. */
|
||||
const binding = () => screen.getByRole('article')
|
||||
|
||||
/** The store list beside it. */
|
||||
const sidebar = () => screen.getByRole('navigation')
|
||||
|
||||
/** The stores filed under one sidebar heading. */
|
||||
const group = (heading: string) =>
|
||||
within(screen.getByRole('heading', { name: heading }).parentElement as HTMLElement)
|
||||
|
||||
/** The "needs a look" section under the binding card. */
|
||||
const issues = () =>
|
||||
within(screen.getByRole('heading', { name: t('docsync.issues.title') }).closest('section') as HTMLElement)
|
||||
|
||||
/** Disconnect asks first; this answers yes. The question renders in a portal. */
|
||||
const confirmUnlink = () => {
|
||||
const dialog = screen.getByText(t('docsync.confirmUnlink')).closest('.trek-modal-enter') as HTMLElement
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: t('docsync.unlink') }))
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
slowCard = false
|
||||
serverHas({})
|
||||
deleteLink.mockResolvedValue({})
|
||||
updateLink.mockResolvedValue({})
|
||||
syncNow.mockResolvedValue({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 })
|
||||
items.mockResolvedValue([])
|
||||
resolve.mockResolvedValue({ success: true })
|
||||
saveConnection.mockResolvedValue({ id: 1 })
|
||||
})
|
||||
|
||||
describe('DocSyncPanel: first load', () => {
|
||||
it('FE-DOCSYNC-PANEL-001: shows a spinner while the first load is in flight and nothing else', async () => {
|
||||
const gate = deferred<DocSyncProvider[]>()
|
||||
providers.mockReturnValue(gate.promise)
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
|
||||
// The spinner carries no text of its own; the spin is the whole affordance.
|
||||
expect(document.querySelector('.animate-spin')).not.toBeNull()
|
||||
expect(screen.queryByRole('navigation')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(t('docsync.noProviders'))).not.toBeInTheDocument()
|
||||
|
||||
await act(async () => { gate.resolve([]) })
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-002: replaces the spinner with the store list once the load lands', async () => {
|
||||
serverHas({ providers: [provider('paperless', 'Paperless-ngx')] })
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
|
||||
expect(await screen.findByRole('navigation')).toBeInTheDocument()
|
||||
expect(document.querySelector('.animate-spin')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-003: says there is nothing to configure when the instance offers no provider', async () => {
|
||||
serverHas({ providers: [] })
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
|
||||
expect(await screen.findByText(t('docsync.noProviders'))).toBeInTheDocument()
|
||||
expect(screen.getByText(t('docsync.noProvidersHint'))).toBeInTheDocument()
|
||||
expect(screen.queryByRole('navigation')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-017: a bound trip keeps showing its binding after every provider was switched off', async () => {
|
||||
serverHas({ providers: [], links: [link(1, 'paperless', { providerName: 'Paperless-ngx' })] })
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage={false} onClose={onClose} />)
|
||||
|
||||
expect(await screen.findByRole('article')).toBeInTheDocument()
|
||||
expect(within(sidebar()).getByText('Folder 1')).toBeInTheDocument()
|
||||
expect(screen.queryByText(t('docsync.noProviders'))).not.toBeInTheDocument()
|
||||
// The providers route no longer names it, so the name comes off the link.
|
||||
expect(within(sidebar()).getByText('Paperless-ngx')).toBeInTheDocument()
|
||||
expect(within(binding()).getAllByText('Paperless-ngx').length).toBeGreaterThan(0)
|
||||
expect(screen.queryByText('paperless')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-018: a reload that finds the addon gone blanks the bindings too', async () => {
|
||||
serverHas({ providers: [provider('paperless', 'Paperless-ngx')], links: [link(1, 'paperless')] })
|
||||
// Documents is switched off while the dialog is open: the run is refused
|
||||
// and so is every route the reload after it asks.
|
||||
const gone = { response: { status: 404 } }
|
||||
syncNow.mockImplementation(async () => {
|
||||
providers.mockRejectedValue(gone)
|
||||
throw gone
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
|
||||
fireEvent.click(within(binding()).getByRole('button', { name: t('docsync.syncNow') }))
|
||||
|
||||
expect(await screen.findByText(t('docsync.noProviders'))).toBeInTheDocument()
|
||||
expect(screen.queryByRole('article')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('navigation')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-004: a provider switched on without a working adapter is not offered', async () => {
|
||||
serverHas({ providers: [provider('papra', 'Papra', false)] })
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
|
||||
expect(await screen.findByText(t('docsync.noProviders'))).toBeInTheDocument()
|
||||
expect(screen.queryByText('Papra')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncPanel: the store list', () => {
|
||||
it('FE-DOCSYNC-PANEL-005: files the bound stores under one heading and the rest under another', async () => {
|
||||
serverHas({
|
||||
providers: [
|
||||
provider('paperless', 'Paperless-ngx'),
|
||||
provider('nextcloud', 'Nextcloud'),
|
||||
provider('opencloud', 'OpenCloud'),
|
||||
],
|
||||
links: [link(1, 'paperless')],
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('navigation')
|
||||
|
||||
const connected = group(t('docsync.sidebar.connected'))
|
||||
expect(connected.getByRole('button', { name: /Paperless-ngx/ })).toBeInTheDocument()
|
||||
expect(connected.queryByRole('button', { name: /Nextcloud/ })).not.toBeInTheDocument()
|
||||
|
||||
const addable = group(t('docsync.addAnother'))
|
||||
expect(addable.getByRole('button', { name: /Nextcloud/ })).toBeInTheDocument()
|
||||
expect(addable.getByRole('button', { name: /OpenCloud/ })).toBeInTheDocument()
|
||||
expect(addable.queryByRole('button', { name: /Paperless-ngx/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-006: with nothing bound the list invites a first connection instead of another one', async () => {
|
||||
serverHas({ providers: [provider('paperless', 'Paperless-ngx')], links: [] })
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('navigation')
|
||||
|
||||
expect(screen.getByRole('heading', { name: t('docsync.addProvider') })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('heading', { name: t('docsync.addAnother') })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('heading', { name: t('docsync.sidebar.connected') })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-007: opens the first bound store without being asked', async () => {
|
||||
serverHas({
|
||||
providers: [provider('paperless', 'Paperless-ngx'), provider('nextcloud', 'Nextcloud')],
|
||||
links: [link(1, 'paperless'), link(2, 'nextcloud')],
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
|
||||
const card = await screen.findByRole('article')
|
||||
// The card names its provider twice (header and flow bar), so the folder is
|
||||
// what says which of the two bindings is open.
|
||||
expect(within(card).getByText('Folder 1')).toBeInTheDocument()
|
||||
expect(within(card).queryByText('Folder 2')).not.toBeInTheDocument()
|
||||
expect(within(card).getAllByText('Paperless-ngx').length).toBeGreaterThan(0)
|
||||
expect(within(card).queryByText('Nextcloud')).not.toBeInTheDocument()
|
||||
expect(within(sidebar()).getByRole('button', { name: /Paperless-ngx/ })).toHaveAttribute('aria-current', 'true')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-008: picking a store swaps the detail column and moves the marker with it', async () => {
|
||||
serverHas({
|
||||
providers: [provider('paperless', 'Paperless-ngx'), provider('nextcloud', 'Nextcloud')],
|
||||
links: [link(1, 'paperless'), link(2, 'nextcloud')],
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
|
||||
const second = within(sidebar()).getByRole('button', { name: /Nextcloud/ })
|
||||
fireEvent.click(second)
|
||||
|
||||
expect(within(binding()).getByText('Folder 2')).toBeInTheDocument()
|
||||
expect(within(binding()).queryByText('Folder 1')).not.toBeInTheDocument()
|
||||
expect(within(binding()).getAllByText('Nextcloud').length).toBeGreaterThan(0)
|
||||
expect(within(binding()).queryByText('Paperless-ngx')).not.toBeInTheDocument()
|
||||
expect(second).toHaveAttribute('aria-current', 'true')
|
||||
expect(within(sidebar()).getByRole('button', { name: /Paperless-ngx/ })).not.toHaveAttribute('aria-current')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-023: a store picked before the list-following effect has run stays picked', async () => {
|
||||
serverHas({
|
||||
providers: [provider('paperless', 'Paperless-ngx'), provider('nextcloud', 'Nextcloud')],
|
||||
links: [link(1, 'paperless'), link(2, 'nextcloud')],
|
||||
})
|
||||
slowCard = true
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
|
||||
// Outside act, as during the wait inside findBy*: React commits the card on
|
||||
// its own scheduler, and the click lands the moment the card is in the DOM,
|
||||
// before the effect that follows the list has had its turn.
|
||||
const env = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
const previous = env.IS_REACT_ACT_ENVIRONMENT
|
||||
env.IS_REACT_ACT_ENVIRONMENT = false
|
||||
try {
|
||||
await new Promise<void>(resolve => {
|
||||
const observer = new MutationObserver(() => {
|
||||
if (!document.querySelector('article')) return
|
||||
observer.disconnect()
|
||||
fireEvent.click(within(sidebar()).getByRole('button', { name: /Nextcloud/ }))
|
||||
resolve()
|
||||
})
|
||||
observer.observe(document.body, { childList: true, subtree: true })
|
||||
})
|
||||
} finally {
|
||||
env.IS_REACT_ACT_ENVIRONMENT = previous
|
||||
}
|
||||
|
||||
expect(within(binding()).getByText('Folder 2')).toBeInTheDocument()
|
||||
expect(within(binding()).queryByText('Folder 1')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncPanel: a member rather than the owner', () => {
|
||||
it('FE-DOCSYNC-PANEL-009: is shown where the documents go but is offered no store to add', async () => {
|
||||
serverHas({
|
||||
providers: [provider('paperless', 'Paperless-ngx'), provider('nextcloud', 'Nextcloud')],
|
||||
links: [link(1, 'paperless')],
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage={false} onClose={onClose} />)
|
||||
await screen.findByRole('navigation')
|
||||
|
||||
expect(within(sidebar()).getByRole('button', { name: /Paperless-ngx/ })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('heading', { name: t('docsync.addAnother') })).not.toBeInTheDocument()
|
||||
expect(within(sidebar()).queryByRole('button', { name: /Nextcloud/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-010: with nothing bound is told the owner sets this up, not to pick a store', async () => {
|
||||
serverHas({ providers: [provider('paperless', 'Paperless-ngx')], links: [] })
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage={false} onClose={onClose} />)
|
||||
|
||||
expect(await screen.findByText(t('docsync.empty.hintMember'))).toBeInTheDocument()
|
||||
expect(screen.queryByText(t('docsync.empty.hintOwner'))).not.toBeInTheDocument()
|
||||
expect(within(sidebar()).queryAllByRole('button')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncPanel: removing a binding', () => {
|
||||
it('FE-DOCSYNC-PANEL-011: moves the selection to the binding that is left instead of emptying the column', async () => {
|
||||
const paperless = link(1, 'paperless')
|
||||
const nextcloud = link(2, 'nextcloud')
|
||||
const both = [provider('paperless', 'Paperless-ngx'), provider('nextcloud', 'Nextcloud')]
|
||||
serverHas({ providers: both, links: [paperless, nextcloud] })
|
||||
// The unlink lands on the server, and the reload after it is what the panel
|
||||
// reacts to, so that is where the row disappears.
|
||||
deleteLink.mockImplementation(async () => {
|
||||
serverHas({ providers: both, links: [paperless] })
|
||||
return {}
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
|
||||
fireEvent.click(within(sidebar()).getByRole('button', { name: /Nextcloud/ }))
|
||||
expect(within(binding()).getByText('Folder 2')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(within(binding()).getByRole('button', { name: t('docsync.unlink') }))
|
||||
confirmUnlink()
|
||||
|
||||
await waitFor(() => expect(deleteLink).toHaveBeenCalledWith(7, 2))
|
||||
await waitFor(() => expect(within(binding()).getByText('Folder 1')).toBeInTheDocument())
|
||||
expect(screen.queryByText(t('docsync.empty.title'))).not.toBeInTheDocument()
|
||||
expect(within(sidebar()).getByRole('button', { name: /Paperless-ngx/ })).toHaveAttribute('aria-current', 'true')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-012: removing the last binding leaves the invitation, not a blank column', async () => {
|
||||
serverHas({ providers: [provider('paperless', 'Paperless-ngx')], links: [link(1, 'paperless')] })
|
||||
deleteLink.mockImplementation(async () => {
|
||||
serverHas({ providers: [provider('paperless', 'Paperless-ngx')], links: [] })
|
||||
return {}
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
|
||||
fireEvent.click(within(binding()).getByRole('button', { name: t('docsync.unlink') }))
|
||||
confirmUnlink()
|
||||
|
||||
expect(await screen.findByText(t('docsync.empty.title'))).toBeInTheDocument()
|
||||
expect(screen.getByText(t('docsync.empty.hintOwner'))).toBeInTheDocument()
|
||||
expect(screen.queryByRole('article')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncPanel: what needs a look', () => {
|
||||
it('FE-DOCSYNC-PANEL-013: stays quiet when nothing needs attention', async () => {
|
||||
serverHas({ providers: [provider('paperless', 'Paperless-ngx')], links: [link(1, 'paperless')], items: {} })
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
|
||||
expect(screen.queryByRole('heading', { name: t('docsync.issues.title') })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-014: counts that need no decision do not open the issues panel', async () => {
|
||||
serverHas({
|
||||
providers: [provider('paperless', 'Paperless-ngx')],
|
||||
links: [link(1, 'paperless')],
|
||||
items: { pending: 9, synced: 41, local_deleted: 2 },
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
|
||||
expect(screen.queryByRole('heading', { name: t('docsync.issues.title') })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-015: names only the states needing attention, with their counts', async () => {
|
||||
serverHas({
|
||||
providers: [provider('paperless', 'Paperless-ngx')],
|
||||
links: [link(1, 'paperless')],
|
||||
items: { conflict: 2, too_large: 1, pending: 9, synced: 41 },
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
|
||||
const panel = within(
|
||||
screen.getByRole('heading', { name: t('docsync.issues.title') }).closest('section') as HTMLElement,
|
||||
)
|
||||
const rows = panel.getAllByRole('listitem')
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(within(rows[0]).getByText(t('docsync.state.conflict'))).toBeInTheDocument()
|
||||
expect(within(rows[0]).getByText(t('docsync.issues.conflict'))).toBeInTheDocument()
|
||||
// The conflict row carries a button rather than a bare count: it is the one
|
||||
// of these a person can act on.
|
||||
expect(within(rows[0]).getByRole('button', { name: /Resolve/ })).toBeInTheDocument()
|
||||
expect(within(rows[1]).getByText(t('docsync.state.too_large'))).toBeInTheDocument()
|
||||
expect(within(rows[1]).getByText('1')).toBeInTheDocument()
|
||||
expect(panel.queryByText(t('docsync.state.pending'))).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-019: a member is shown the conflict count but offered no choice', async () => {
|
||||
// The server refuses a member's choice with 403, so the three buttons
|
||||
// would only ever fail for them. The count is what they are owed.
|
||||
serverHas({
|
||||
providers: [provider('paperless', 'Paperless-ngx')],
|
||||
links: [link(1, 'paperless')],
|
||||
items: { conflict: 2 },
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage={false} onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
|
||||
const row = issues().getAllByRole('listitem')[0]
|
||||
expect(within(row).getByText(t('docsync.state.conflict'))).toBeInTheDocument()
|
||||
expect(within(row).getByText('2')).toBeInTheDocument()
|
||||
expect(within(row).queryByRole('button')).not.toBeInTheDocument()
|
||||
expect(items).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-020: a choice the server refuses is said in the column, and the row stays', async () => {
|
||||
serverHas({
|
||||
providers: [provider('paperless', 'Paperless-ngx')],
|
||||
links: [link(1, 'paperless')],
|
||||
items: { conflict: 1 },
|
||||
})
|
||||
items.mockResolvedValue([{ id: 40, file_name: 'boarding-pass.pdf', remote_name: 'boarding-pass.pdf' }])
|
||||
// Settled by the owner in another tab a moment ago.
|
||||
resolve.mockRejectedValue({ response: { status: 400, data: { error: 'conflict' } } })
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
|
||||
fireEvent.click(issues().getByRole('button', { name: /Resolve/ }))
|
||||
fireEvent.click(await issues().findByRole('button', { name: t('docsync.conflict.keepTrek') }))
|
||||
|
||||
await waitFor(() => expect(resolve).toHaveBeenCalledWith(7, 40, 'trek'))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(t('docsync.error.conflict'))
|
||||
// The list is read back rather than trimmed by hand, so the row is still
|
||||
// there, ready for another try.
|
||||
await waitFor(() => expect(issues().getByRole('button', { name: t('docsync.conflict.keepTrek') })).toBeEnabled())
|
||||
expect(issues().getByText('boarding-pass.pdf')).toBeInTheDocument()
|
||||
expect(items).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncPanel: what a click on the card reports', () => {
|
||||
it('FE-DOCSYNC-PANEL-021: a refused run is said under the card rather than swallowed', async () => {
|
||||
serverHas({ providers: [provider('paperless', 'Paperless-ngx')], links: [link(1, 'paperless')] })
|
||||
syncNow.mockRejectedValue({ response: { status: 409, data: { error: 'provider_disabled' } } })
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(within(binding()).getByRole('button', { name: t('docsync.syncNow') }))
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(t('docsync.error.provider_disabled'))
|
||||
expect(screen.getByRole('article')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-PANEL-022: a refused credential opens the form for the bound store, and saving runs the binding', async () => {
|
||||
// The sidebar only ever opened the form for a store with no connection
|
||||
// yet, and a bound store is not listed there, so a rotated token could
|
||||
// only be entered through the API.
|
||||
serverHas({
|
||||
providers: [provider('paperless', 'Paperless-ngx')],
|
||||
connections: [connection(5, 'paperless')],
|
||||
links: [link(1, 'paperless', { lastSyncState: 'needs_reauth', lastSyncError: 'unauthorized' })],
|
||||
})
|
||||
|
||||
render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)
|
||||
await screen.findByRole('article')
|
||||
|
||||
fireEvent.click(within(binding()).getByRole('button', { name: t('docsync.binding.reconnect') }))
|
||||
|
||||
// The credential form, for this store, not the folder picker.
|
||||
expect(screen.getByRole('button', { name: t('docsync.connect.submit') })).toBeInTheDocument()
|
||||
expect(screen.queryByText(t('docsync.scope.pickTitle'))).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: t('docsync.connect.submit') }))
|
||||
|
||||
await waitFor(() => expect(saveConnection).toHaveBeenCalledWith(7, expect.objectContaining({ providerId: 'paperless' })))
|
||||
await waitFor(() => expect(syncNow).toHaveBeenCalledWith(7, 1, false))
|
||||
await waitFor(() => expect(screen.queryByRole('button', { name: t('docsync.connect.submit') })).not.toBeInTheDocument())
|
||||
expect(screen.queryByText(t('docsync.scope.pickTitle'))).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncPanel: the dialog itself', () => {
|
||||
it('FE-DOCSYNC-PANEL-016: names the trip under the title and closes from the header', async () => {
|
||||
serverHas({ providers: [] })
|
||||
|
||||
render(<DocSyncPanel tripId={7} tripTitle="Iceland 2026" canManage onClose={onClose} />)
|
||||
await screen.findByText(t('docsync.noProviders'))
|
||||
|
||||
expect(screen.getByText(t('docsync.title'))).toBeInTheDocument()
|
||||
expect(screen.getByText('Iceland 2026')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button'))
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,429 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { AlertCircle, ArrowRight, Check, Loader2, Plus } from 'lucide-react'
|
||||
import Modal from '../../shared/Modal'
|
||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/DocumentProviderIcons'
|
||||
import { StateBadge } from './DocSyncBits'
|
||||
import { useConflicts } from './useConflicts'
|
||||
import { storeName, useDocSync, type DocSyncLink, type DocSyncProvider } from './useDocSync'
|
||||
import DocSyncBinding from './DocSyncBinding'
|
||||
import DocSyncConnectModal from './DocSyncConnectModal'
|
||||
import DocSyncScopeModal from './DocSyncScopeModal'
|
||||
|
||||
/**
|
||||
* Document sync for one trip, as a dialog with the stores down one side and the
|
||||
* selected one open beside it.
|
||||
*
|
||||
* Two columns rather than a stack, because the two questions are different
|
||||
* shapes: "which store" is a short list somebody scans, and "how does this one
|
||||
* behave" is a screenful. Stacked, the second answer pushed the first one off
|
||||
* the top every time a binding was added.
|
||||
*
|
||||
* It opens from the file manager rather than from settings: this is the one
|
||||
* screen where a person has the context that makes the folder choice obvious.
|
||||
* Only the trip owner can change a binding (the credential usually reaches
|
||||
* their whole archive), but every member sees where their documents go, which
|
||||
* is the minimum a shared folder owes the people sharing it.
|
||||
*/
|
||||
export default function DocSyncPanel({
|
||||
tripId,
|
||||
tripTitle,
|
||||
canManage,
|
||||
onClose,
|
||||
}: {
|
||||
tripId: number | string
|
||||
tripTitle?: string
|
||||
canManage: boolean
|
||||
onClose: () => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const sync = useDocSync(tripId, true)
|
||||
const [selected, setSelected] = useState<number | null>(null)
|
||||
const [connecting, setConnecting] = useState<DocSyncProvider | null>(null)
|
||||
const [scopeFor, setScopeFor] = useState<string | null>(null)
|
||||
// The credential form again, for a store this trip is already bound to. Kept
|
||||
// apart from `connecting`, whose next step is the folder picker: here the
|
||||
// folder is known and the next step is the run that the refusal stopped.
|
||||
const [reconnecting, setReconnecting] = useState<DocSyncProvider | null>(null)
|
||||
|
||||
const bound = useMemo(() => new Set(sync.links.map(l => l.providerId)), [sync.links])
|
||||
const available = sync.providers.filter(p => !bound.has(p.id))
|
||||
const active = sync.links.find(l => l.id === selected) ?? sync.links[0] ?? null
|
||||
// Undefined once an admin has switched the store off: the form needs the
|
||||
// provider's field list, and the providers route no longer carries it.
|
||||
const activeProvider = active ? sync.providers.find(p => p.id === active.providerId) : undefined
|
||||
|
||||
// Follow the list: a freshly bound store should be the one on screen, and a
|
||||
// removed one must not leave the detail column pointing at nothing. The pick
|
||||
// is read when the update runs, not from this render: a store clicked before
|
||||
// the effect got its turn was otherwise switched straight back.
|
||||
useEffect(() => {
|
||||
setSelected(prev => (sync.links.some(l => l.id === prev) ? prev : (sync.links[0]?.id ?? null)))
|
||||
}, [sync.links])
|
||||
|
||||
const attention = ATTENTION_STATES.reduce((n, k) => n + (sync.itemCounts[k] ?? 0), 0)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
size="4xl"
|
||||
title={
|
||||
<span className="flex flex-col">
|
||||
<span>{t('docsync.title')}</span>
|
||||
{tripTitle && (
|
||||
<span className="mt-0.5 truncate text-caption font-normal text-content-muted">{tripTitle}</span>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{sync.loading ? (
|
||||
<div className="grid place-items-center py-20">
|
||||
<Loader2 size={22} className="animate-spin text-content-faint" />
|
||||
</div>
|
||||
) : sync.providers.length === 0 && sync.links.length === 0 ? (
|
||||
// Only with nothing bound: a binding outlives the admin switching its
|
||||
// provider off, and the people sharing it still need to see it.
|
||||
<Empty />
|
||||
) : (
|
||||
<div className="grid gap-5 md:grid-cols-[17rem_minmax(0,1fr)] md:gap-6">
|
||||
<Sidebar
|
||||
links={sync.links}
|
||||
providers={sync.providers}
|
||||
available={available}
|
||||
activeId={active?.id ?? null}
|
||||
canManage={canManage}
|
||||
onSelect={setSelected}
|
||||
onAdd={p => (sync.connectionFor(p.id) ? setScopeFor(p.id) : setConnecting(p))}
|
||||
/>
|
||||
|
||||
<div className="min-w-0 md:border-l md:border-edge-faint md:pl-6">
|
||||
{active ? (
|
||||
<div className="space-y-5">
|
||||
<DocSyncBinding
|
||||
link={active}
|
||||
providerName={storeName(active, sync.providers)}
|
||||
sync={sync}
|
||||
canManage={canManage}
|
||||
onReconnect={activeProvider ? () => setReconnecting(activeProvider) : undefined}
|
||||
/>
|
||||
{/* Every action in this column reports here: a refused run, a
|
||||
switch that flipped back, a conflict the server would not
|
||||
settle. The two dialogs say their own, but nothing said
|
||||
what happened to a click on the card itself. */}
|
||||
{sync.error && (
|
||||
<p role="alert" className="rounded-xl border border-edge bg-danger-soft px-3 py-2.5 text-caption text-danger">
|
||||
{t(`docsync.error.${sync.error}`)}
|
||||
</p>
|
||||
)}
|
||||
{attention > 0 && (
|
||||
<Attention counts={sync.itemCounts} tripId={tripId} sync={sync} canManage={canManage} />
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<NothingBound canManage={canManage} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{connecting && (
|
||||
<DocSyncConnectModal
|
||||
provider={connecting}
|
||||
sync={sync}
|
||||
onClose={() => setConnecting(null)}
|
||||
onConnected={id => { setConnecting(null); setScopeFor(id) }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{reconnecting && (
|
||||
<DocSyncConnectModal
|
||||
provider={reconnecting}
|
||||
sync={sync}
|
||||
onClose={() => setReconnecting(null)}
|
||||
onConnected={id => {
|
||||
setReconnecting(null)
|
||||
// Run straight away, as binding does: the card still reports the
|
||||
// refusal until a run says otherwise, and the person has just
|
||||
// done the one thing that could change the answer.
|
||||
const rebound = sync.links.find(l => l.providerId === id)
|
||||
if (rebound) void sync.syncNow(rebound.id)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{scopeFor && sync.connectionFor(scopeFor) && (
|
||||
<DocSyncScopeModal
|
||||
connection={sync.connectionFor(scopeFor)!}
|
||||
providerName={sync.providers.find(p => p.id === scopeFor)?.name ?? scopeFor}
|
||||
suggestedName={slugFor(tripTitle, tripId)}
|
||||
sync={sync}
|
||||
onClose={() => setScopeFor(null)}
|
||||
onBound={() => setScopeFor(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const ATTENTION_STATES = ['conflict', 'remote_missing', 'rejected_type', 'too_large', 'error'] as const
|
||||
|
||||
/** The stores: the ones this trip uses, then the ones it could. */
|
||||
function Sidebar({
|
||||
links,
|
||||
providers,
|
||||
available,
|
||||
activeId,
|
||||
canManage,
|
||||
onSelect,
|
||||
onAdd,
|
||||
}: {
|
||||
links: DocSyncLink[]
|
||||
providers: DocSyncProvider[]
|
||||
available: DocSyncProvider[]
|
||||
activeId: number | null
|
||||
canManage: boolean
|
||||
onSelect: (id: number) => void
|
||||
onAdd: (p: DocSyncProvider) => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<nav className="space-y-5">
|
||||
{links.length > 0 && (
|
||||
<div>
|
||||
<h4 className="mb-2 px-1 text-caption font-medium text-content-muted">
|
||||
{t('docsync.sidebar.connected')}
|
||||
</h4>
|
||||
<ul className="space-y-1.5">
|
||||
{links.map(link => (
|
||||
<li key={link.id}>
|
||||
<StoreButton
|
||||
providerId={link.providerId}
|
||||
title={storeName(link, providers)}
|
||||
subtitle={link.remoteLabel || link.remoteRootPath || link.scopeKey}
|
||||
state={link.lastSyncState}
|
||||
active={link.id === activeId}
|
||||
onClick={() => onSelect(link.id)}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canManage && available.length > 0 && (
|
||||
<div>
|
||||
<h4 className="mb-2 px-1 text-caption font-medium text-content-muted">
|
||||
{links.length === 0 ? t('docsync.addProvider') : t('docsync.addAnother')}
|
||||
</h4>
|
||||
<ul className="space-y-1.5">
|
||||
{available.map(p => (
|
||||
<li key={p.id}>
|
||||
<StoreButton
|
||||
providerId={p.id}
|
||||
title={p.name}
|
||||
subtitle={t(`docsync.model.${p.id}`)}
|
||||
onClick={() => onAdd(p)}
|
||||
addable
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One row in the store list.
|
||||
*
|
||||
* The selected row is marked with the accent on a subtle fill rather than a
|
||||
* heavy border, so a list of five does not turn into five competing boxes.
|
||||
*/
|
||||
function StoreButton({
|
||||
providerId,
|
||||
title,
|
||||
subtitle,
|
||||
state,
|
||||
active,
|
||||
addable,
|
||||
onClick,
|
||||
}: {
|
||||
providerId: string
|
||||
title: string
|
||||
subtitle: string
|
||||
state?: string
|
||||
active?: boolean
|
||||
addable?: boolean
|
||||
onClick: () => void
|
||||
}) {
|
||||
const Icon = DOCUMENT_PROVIDER_ICONS[providerId]
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-current={active ? 'true' : undefined}
|
||||
className={[
|
||||
'group flex w-full items-center gap-3 rounded-xl border px-3 py-2.5 text-left transition-colors',
|
||||
active
|
||||
? 'border-transparent bg-accent-subtle'
|
||||
: 'border-edge bg-surface hover:bg-surface-hover',
|
||||
].join(' ')}
|
||||
>
|
||||
<span
|
||||
className={[
|
||||
'grid h-8 w-8 shrink-0 place-items-center rounded-lg',
|
||||
active ? 'bg-surface' : 'bg-surface-secondary',
|
||||
].join(' ')}
|
||||
>
|
||||
{Icon ? <Icon className={`h-4 w-4 ${active ? 'text-accent-on' : 'text-content'}`} /> : null}
|
||||
</span>
|
||||
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className={`block truncate text-body ${active ? 'font-medium text-accent-on' : 'text-content'}`}>
|
||||
{title}
|
||||
</span>
|
||||
<span className="mt-0.5 block truncate text-caption text-content-muted">{subtitle}</span>
|
||||
</span>
|
||||
|
||||
{addable ? (
|
||||
<Plus size={14} className="shrink-0 text-content-faint transition-transform group-hover:scale-110" />
|
||||
) : state ? (
|
||||
<StateBadge state={state} compact />
|
||||
) : null}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** What a person still has to decide about, named rather than counted in a chip. */
|
||||
function Attention({
|
||||
counts,
|
||||
tripId,
|
||||
sync,
|
||||
canManage,
|
||||
}: {
|
||||
counts: Record<string, number>
|
||||
tripId: number | string
|
||||
sync: ReturnType<typeof useDocSync>
|
||||
canManage: boolean
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const rows = ATTENTION_STATES.filter(k => (counts[k] ?? 0) > 0)
|
||||
const [showConflicts, setShowConflicts] = useState(false)
|
||||
const conflicts = useConflicts(tripId, sync, showConflicts)
|
||||
|
||||
return (
|
||||
<section className="rounded-xl border border-edge bg-surface">
|
||||
<h4 className="flex items-center gap-2 border-b border-edge-faint px-4 py-2.5 text-body font-medium text-content">
|
||||
<AlertCircle size={14} className="text-warning" />
|
||||
{t('docsync.issues.title')}
|
||||
</h4>
|
||||
<ul className="divide-y divide-edge-faint">
|
||||
{rows.map(k => (
|
||||
<li key={k} className="px-4 py-2.5">
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<span className="min-w-0">
|
||||
<span className="block text-body text-content">{t(`docsync.state.${k}`)}</span>
|
||||
<span className="mt-0.5 block text-caption text-content-muted">{t(`docsync.issues.${k}`)}</span>
|
||||
</span>
|
||||
{/* A conflict is the one of these a person can act on, so it is
|
||||
the one that opens. The rest are a state to read. Only for
|
||||
the owner: the server refuses a member's choice, so a member
|
||||
gets the count, like every other row. */}
|
||||
{k === 'conflict' && canManage ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowConflicts(v => !v)}
|
||||
className="shrink-0 rounded-lg border border-edge px-2.5 py-1 text-caption font-medium text-content transition-colors hover:bg-surface-hover"
|
||||
>
|
||||
{showConflicts ? t('common.close') : t('docsync.conflict.resolve', { count: counts[k] })}
|
||||
</button>
|
||||
) : (
|
||||
<span className="shrink-0 text-body font-medium tabular-nums text-content">{counts[k]}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{k === 'conflict' && canManage && showConflicts && (
|
||||
<ul className="mt-3 space-y-2">
|
||||
{conflicts.items === null && (
|
||||
<li className="flex justify-center py-2">
|
||||
<Loader2 size={14} className="animate-spin text-content-muted" />
|
||||
</li>
|
||||
)}
|
||||
{conflicts.items?.map(item => (
|
||||
<li key={item.id} className="rounded-lg bg-surface-secondary px-3 py-2.5">
|
||||
<p className="truncate text-body text-content" title={item.name}>{item.name}</p>
|
||||
<p className="mt-0.5 text-caption text-content-muted">{t('docsync.conflict.title')}</p>
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{(['trek', 'provider', 'both'] as const).map(keep => (
|
||||
<button
|
||||
key={keep}
|
||||
type="button"
|
||||
disabled={conflicts.working === item.id}
|
||||
onClick={() => void conflicts.resolve(item.id, keep)}
|
||||
className="rounded-lg border border-edge px-2.5 py-1 text-caption text-content-secondary transition-colors hover:bg-surface-hover disabled:opacity-50"
|
||||
>
|
||||
{t(`docsync.conflict.${keep === 'trek' ? 'keepTrek' : keep === 'provider' ? 'keepProvider' : 'keepBoth'}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** The detail column before anything is bound: an invitation, not a blank. */
|
||||
function NothingBound({ canManage }: { canManage: boolean }) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<div className="grid h-full min-h-[16rem] place-items-center rounded-xl border border-dashed border-edge px-6 py-12 text-center">
|
||||
<div>
|
||||
<span className="mx-auto grid h-11 w-11 place-items-center rounded-xl border border-edge bg-surface-secondary">
|
||||
<ArrowRight size={18} className="text-content-faint" />
|
||||
</span>
|
||||
<p className="mt-3 text-body text-content">{t('docsync.empty.title')}</p>
|
||||
<p className="mx-auto mt-1 max-w-xs text-caption text-content-muted">
|
||||
{canManage ? t('docsync.empty.hintOwner') : t('docsync.empty.hintMember')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Empty() {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<div className="rounded-xl border border-dashed border-edge px-6 py-12 text-center">
|
||||
<span className="mx-auto grid h-11 w-11 place-items-center rounded-xl border border-edge bg-surface-secondary">
|
||||
<Check size={18} className="text-content-faint" />
|
||||
</span>
|
||||
<p className="mt-3 text-body text-content">{t('docsync.noProviders')}</p>
|
||||
<p className="mx-auto mt-1 max-w-sm text-caption text-content-muted">{t('docsync.noProvidersHint')}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A folder name from the trip's own title, so nobody has to invent one.
|
||||
*
|
||||
* The id is appended because two trips can share a title and a folder cannot.
|
||||
*/
|
||||
function slugFor(title: string | undefined, tripId: number | string): string {
|
||||
const base = (title || 'trek')
|
||||
.toLowerCase()
|
||||
.normalize('NFD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 40)
|
||||
return `${base || 'trek'}-${tripId}`
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
// FE-DOCSYNC-SCOPE-001 to FE-DOCSYNC-SCOPE-023
|
||||
|
||||
/**
|
||||
* The folder picker of the document-sync dialog.
|
||||
*
|
||||
* What matters to somebody opening it: the folders of their own store show up,
|
||||
* the one they pick is the one that gets bound, making a new folder is one
|
||||
* action rather than two, and a store that refuses to answer says so instead of
|
||||
* pretending the archive is empty.
|
||||
*
|
||||
* The component takes the `useDocSync` hook as a prop, so the double here is the
|
||||
* real hook with `api/client` mocked underneath, so the assertions are about
|
||||
* the requests that actually leave, not about a hand-written stand-in. The hook
|
||||
* is created with `enabled: false` because the panel-level lists it would fetch
|
||||
* belong to the dialog around this modal, not to the picker.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import en from '@trek/shared/i18n/en'
|
||||
import { render, screen, fireEvent, waitFor } from '../../../../tests/helpers/render'
|
||||
import type { DocSyncConnection, DocSyncScope } from './useDocSync'
|
||||
|
||||
const S = en as unknown as Record<string, string>
|
||||
|
||||
const listScopes = vi.fn()
|
||||
const createScope = vi.fn()
|
||||
const createLink = vi.fn()
|
||||
|
||||
vi.mock('../../../api/client', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../../api/client')>()
|
||||
return {
|
||||
...actual,
|
||||
docsyncApi: {
|
||||
...actual.docsyncApi,
|
||||
providers: () => Promise.resolve([]),
|
||||
status: () => Promise.resolve({ items: {}, links: [] }),
|
||||
listConnections: () => Promise.resolve([]),
|
||||
listLinks: () => Promise.resolve([]),
|
||||
listScopes: (tripId: number | string, connectionId: number, q?: string) => listScopes(tripId, connectionId, q),
|
||||
createScope: (tripId: number | string, connectionId: number, name: string) => createScope(tripId, connectionId, name),
|
||||
createLink: (tripId: number | string, data: unknown) => createLink(tripId, data),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
import DocSyncScopeModal from './DocSyncScopeModal'
|
||||
import { useDocSync } from './useDocSync'
|
||||
|
||||
const TRIP_ID = 42
|
||||
|
||||
const connection: DocSyncConnection = {
|
||||
id: 5,
|
||||
providerId: 'paperless',
|
||||
baseUrl: 'https://docs.example.org',
|
||||
settings: {},
|
||||
secrets: {},
|
||||
allowInsecureTls: false,
|
||||
lastProbeState: 'ok',
|
||||
lastProbeError: null,
|
||||
}
|
||||
|
||||
const folder = (n: number, label: string, remoteRootPath: string | null = `/Documents/${label}`): DocSyncScope =>
|
||||
({ scopeKey: `folder-${n}`, label, remoteRootId: String(n), remoteRootPath })
|
||||
|
||||
/** Seven, so the list is one over the threshold that earns a search box. */
|
||||
const SEVEN = [
|
||||
folder(1, 'Trips'),
|
||||
folder(2, 'Archive'),
|
||||
folder(3, 'Receipts'),
|
||||
folder(4, 'Invoices'),
|
||||
folder(5, 'Photos'),
|
||||
folder(6, 'Manuals'),
|
||||
folder(7, 'Warranty'),
|
||||
]
|
||||
const SIX = SEVEN.slice(0, 6)
|
||||
const THREE = SEVEN.slice(0, 3)
|
||||
|
||||
const onClose = vi.fn()
|
||||
const onBound = vi.fn()
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason?: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej })
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
function Harness({ suggestedName = 'trek-paris-42', providerName = 'Paperless' }: {
|
||||
suggestedName?: string
|
||||
providerName?: string
|
||||
}) {
|
||||
const sync = useDocSync(TRIP_ID, false)
|
||||
return (
|
||||
<DocSyncScopeModal
|
||||
connection={connection}
|
||||
providerName={providerName}
|
||||
suggestedName={suggestedName}
|
||||
sync={sync}
|
||||
onClose={onClose}
|
||||
onBound={onBound}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const nameField = () => screen.getByPlaceholderText(S['docsync.newFolderPlaceholder'])
|
||||
const createButton = () => screen.getByRole('button', { name: S['docsync.scope.createAction'] })
|
||||
const searchField = () => screen.queryByPlaceholderText(S['docsync.scope.search'])
|
||||
const rowFor = (label: string) => screen.getByText(label).closest('button') as HTMLButtonElement
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
listScopes.mockResolvedValue({ scopes: THREE })
|
||||
createScope.mockResolvedValue(folder(9, 'Paris 2026'))
|
||||
createLink.mockResolvedValue({ id: 1 })
|
||||
})
|
||||
|
||||
describe('DocSyncScopeModal list', () => {
|
||||
it('FE-DOCSYNC-SCOPE-001: asks the store for its folders as soon as it opens', async () => {
|
||||
render(<Harness />)
|
||||
|
||||
await waitFor(() => expect(listScopes).toHaveBeenCalledWith(TRIP_ID, 5, undefined))
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-002: shows every folder the store answered with, and where each one sits', async () => {
|
||||
listScopes.mockResolvedValue({ scopes: THREE })
|
||||
render(<Harness />)
|
||||
|
||||
expect(await screen.findByText('Trips')).toBeInTheDocument()
|
||||
expect(screen.getByText('Archive')).toBeInTheDocument()
|
||||
expect(screen.getByText('Receipts')).toBeInTheDocument()
|
||||
expect(screen.getByText('/Documents/Archive')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-003: says nothing about an empty archive while the list is still in flight', async () => {
|
||||
const pending = deferred<{ scopes: DocSyncScope[] }>()
|
||||
listScopes.mockReturnValue(pending.promise)
|
||||
render(<Harness />)
|
||||
|
||||
// The dangerous middle state: "no folders" is a claim about the store, and
|
||||
// it must not be made before the store has answered.
|
||||
expect(screen.queryByText(S['docsync.noFolders'])).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Trips')).not.toBeInTheDocument()
|
||||
|
||||
pending.resolve({ scopes: THREE })
|
||||
expect(await screen.findByText('Trips')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-004: a store with no folders at all says so', async () => {
|
||||
listScopes.mockResolvedValue({ scopes: [] })
|
||||
render(<Harness />)
|
||||
|
||||
expect(await screen.findByText(S['docsync.noFolders'])).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-005: names the store in the question it asks', async () => {
|
||||
render(<Harness providerName="Paperless" />)
|
||||
|
||||
expect(await screen.findByText(S['docsync.scope.title'].replace('{provider}', 'Paperless'))).toBeInTheDocument()
|
||||
expect(screen.getByText(S['docsync.scope.intro'])).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-006: the header close button leaves without binding anything', async () => {
|
||||
render(<Harness />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
fireEvent.click(screen.getAllByRole('button')[0])
|
||||
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
expect(createLink).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncScopeModal search', () => {
|
||||
it('FE-DOCSYNC-SCOPE-007: a list short enough to read gets no search box', async () => {
|
||||
listScopes.mockResolvedValue({ scopes: SIX })
|
||||
render(<Harness />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
expect(searchField()).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-008: one folder past the threshold the search box appears', async () => {
|
||||
listScopes.mockResolvedValue({ scopes: SEVEN })
|
||||
render(<Harness />)
|
||||
await screen.findByText('Warranty')
|
||||
|
||||
expect(searchField()).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-009: typing narrows the list without going back to the store', async () => {
|
||||
listScopes.mockResolvedValue({ scopes: SEVEN })
|
||||
render(<Harness />)
|
||||
await screen.findByText('Warranty')
|
||||
const before = listScopes.mock.calls.length
|
||||
|
||||
fireEvent.change(searchField()!, { target: { value: ' ARCH ' } })
|
||||
|
||||
expect(screen.getByText('Archive')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Trips')).not.toBeInTheDocument()
|
||||
// Matching is case- and whitespace-insensitive and costs no round trip.
|
||||
expect(listScopes.mock.calls.length).toBe(before)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-010: a query nothing matches says so, and does not claim the store is empty', async () => {
|
||||
listScopes.mockResolvedValue({ scopes: SEVEN })
|
||||
render(<Harness />)
|
||||
await screen.findByText('Warranty')
|
||||
|
||||
fireEvent.change(searchField()!, { target: { value: 'zzz' } })
|
||||
|
||||
expect(screen.getByText(S['docsync.scope.noMatch'])).toBeInTheDocument()
|
||||
expect(screen.queryByText(S['docsync.noFolders'])).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncScopeModal picking an existing folder', () => {
|
||||
it('FE-DOCSYNC-SCOPE-011: binds the folder that was clicked, with the defaults a new binding gets', async () => {
|
||||
render(<Harness />)
|
||||
await screen.findByText('Archive')
|
||||
|
||||
fireEvent.click(rowFor('Archive'))
|
||||
|
||||
await waitFor(() => expect(createLink).toHaveBeenCalledWith(TRIP_ID, {
|
||||
connectionId: 5,
|
||||
scopeKey: 'folder-2',
|
||||
remoteRootId: '2',
|
||||
remoteRootPath: '/Documents/Archive',
|
||||
remoteLabel: 'Archive',
|
||||
direction: 'both',
|
||||
deletePolicy: 'unlink',
|
||||
conflictPolicy: 'manual',
|
||||
syncEnabled: true,
|
||||
}))
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-012: a bound folder closes the picker', async () => {
|
||||
render(<Harness />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
fireEvent.click(rowFor('Trips'))
|
||||
|
||||
await waitFor(() => expect(onBound).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-013: a refused binding leaves the picker open so another folder can be tried', async () => {
|
||||
createLink.mockRejectedValueOnce(Object.assign(new Error('nope'), {
|
||||
response: { data: { error: 'forbidden' } },
|
||||
}))
|
||||
render(<Harness />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
fireEvent.click(rowFor('Trips'))
|
||||
|
||||
await waitFor(() => expect(createLink).toHaveBeenCalled())
|
||||
expect(onBound).not.toHaveBeenCalled()
|
||||
expect(screen.getByText('Trips')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-014: while one folder is being bound nothing else can be started', async () => {
|
||||
const pending = deferred<{ id: number }>()
|
||||
createLink.mockReturnValueOnce(pending.promise)
|
||||
render(<Harness />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
fireEvent.click(rowFor('Trips'))
|
||||
|
||||
expect(rowFor('Archive')).toBeDisabled()
|
||||
expect(createButton()).toBeDisabled()
|
||||
|
||||
pending.resolve({ id: 1 })
|
||||
await waitFor(() => expect(onBound).toHaveBeenCalled())
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncScopeModal creating a folder', () => {
|
||||
it('FE-DOCSYNC-SCOPE-015: the trip name is already in the field, so creating is one click', async () => {
|
||||
render(<Harness suggestedName="trek-paris-42" />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
expect(nameField()).toHaveValue('trek-paris-42')
|
||||
expect(createButton()).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-016: creating makes the folder and binds it in one go', async () => {
|
||||
createScope.mockResolvedValue(folder(9, 'Paris 2026', '/Documents/Paris 2026'))
|
||||
render(<Harness suggestedName="Paris 2026" />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
fireEvent.click(createButton())
|
||||
|
||||
await waitFor(() => expect(createScope).toHaveBeenCalledWith(TRIP_ID, 5, 'Paris 2026'))
|
||||
await waitFor(() => expect(createLink).toHaveBeenCalledWith(TRIP_ID, expect.objectContaining({
|
||||
connectionId: 5,
|
||||
scopeKey: 'folder-9',
|
||||
remoteRootId: '9',
|
||||
remoteLabel: 'Paris 2026',
|
||||
})))
|
||||
await waitFor(() => expect(onBound).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-021: a refused create says why instead of doing nothing', async () => {
|
||||
// The create had no failure path at all: the rejection escaped the click
|
||||
// handler unhandled, nothing was bound, and the dialog said nothing: the
|
||||
// button blinked and the person was left guessing. Every other write in the
|
||||
// hook reports, and so does this one now.
|
||||
createScope.mockRejectedValue({ response: { data: { error: 'quota_exceeded' } } })
|
||||
render(<Harness suggestedName="Paris 2026" />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
fireEvent.click(createButton())
|
||||
|
||||
await waitFor(() => expect(screen.getByText(S['docsync.error.quota_exceeded'])).toBeInTheDocument())
|
||||
expect(createLink).not.toHaveBeenCalled()
|
||||
expect(onBound).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-022: the create button comes back after a refusal', async () => {
|
||||
createScope.mockRejectedValue({ response: { data: { error: 'quota_exceeded' } } })
|
||||
render(<Harness suggestedName="Paris 2026" />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
fireEvent.click(createButton())
|
||||
|
||||
await waitFor(() => expect(createButton()).toBeEnabled())
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-017: a blank or whitespace-only name creates nothing', async () => {
|
||||
render(<Harness suggestedName="" />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
expect(createButton()).toBeDisabled()
|
||||
|
||||
fireEvent.change(nameField(), { target: { value: ' ' } })
|
||||
expect(createButton()).toBeDisabled()
|
||||
|
||||
fireEvent.keyDown(nameField(), { key: 'Enter' })
|
||||
expect(createScope).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-018: Enter in the name field creates the typed name, not the suggested one', async () => {
|
||||
createScope.mockResolvedValue(folder(9, 'Belege'))
|
||||
render(<Harness suggestedName="trek-paris-42" />)
|
||||
await screen.findByText('Trips')
|
||||
|
||||
fireEvent.change(nameField(), { target: { value: ' Belege ' } })
|
||||
fireEvent.keyDown(nameField(), { key: 'Enter' })
|
||||
|
||||
await waitFor(() => expect(createScope).toHaveBeenCalledWith(TRIP_ID, 5, 'Belege'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('DocSyncScopeModal errors', () => {
|
||||
it('FE-DOCSYNC-SCOPE-019: a store that refuses the credentials says so instead of showing an empty archive', async () => {
|
||||
listScopes.mockResolvedValue({ scopes: [], error: 'unauthorized' })
|
||||
render(<Harness />)
|
||||
|
||||
expect(await screen.findByText(S['docsync.error.unauthorized'])).toBeInTheDocument()
|
||||
expect(screen.queryByText(S['docsync.noFolders'])).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-020: an error wins over folders the store still managed to list', async () => {
|
||||
listScopes.mockResolvedValue({ scopes: THREE, error: 'scope_missing' })
|
||||
render(<Harness />)
|
||||
|
||||
expect(await screen.findByText(S['docsync.error.scope_missing'])).toBeInTheDocument()
|
||||
expect(screen.queryByText('Trips')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-SCOPE-023: a listing request that fell over says so instead of spinning forever', async () => {
|
||||
// The store answers 200 with a code when it refuses, but a request that
|
||||
// never got an answer (a store behind a VPN that is down, a connection an
|
||||
// admin deleted meanwhile) rejected instead, nothing caught it, and the
|
||||
// spinner was all the picker ever showed.
|
||||
listScopes.mockRejectedValue({ code: 'ECONNABORTED', message: 'timeout of 60000ms exceeded' })
|
||||
render(<Harness />)
|
||||
|
||||
expect(await screen.findByText(S['docsync.error.unknown'])).toBeInTheDocument()
|
||||
expect(document.querySelector('.animate-spin')).toBeNull()
|
||||
expect(screen.queryByText(S['docsync.noFolders'])).not.toBeInTheDocument()
|
||||
// Making a new folder is still on offer: the store may well be reachable
|
||||
// for that, and it is the way out when the listing is what failed.
|
||||
expect(createButton()).toBeEnabled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { FolderPlus, Loader2, Search } from 'lucide-react'
|
||||
import Modal from '../../shared/Modal'
|
||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||
import type { DocSyncConnection, DocSyncScope, useDocSync } from './useDocSync'
|
||||
|
||||
/**
|
||||
* Picking the container a trip lives in.
|
||||
*
|
||||
* The list is filtered client-side: these are a person's own folders or tags,
|
||||
* so there are tens of them, not thousands, and a round trip per keystroke
|
||||
* would be slower than the filter it replaces.
|
||||
*
|
||||
* "Create" is a first-class action rather than a fallback at the bottom,
|
||||
* because for a new trip it is the common case: there is no folder yet.
|
||||
*/
|
||||
export default function DocSyncScopeModal({
|
||||
connection,
|
||||
providerName,
|
||||
suggestedName,
|
||||
sync,
|
||||
onClose,
|
||||
onBound,
|
||||
}: {
|
||||
connection: DocSyncConnection
|
||||
providerName: string
|
||||
/** Pre-filled name for a new container, from the trip's title. */
|
||||
suggestedName: string
|
||||
sync: ReturnType<typeof useDocSync>
|
||||
onClose: () => void
|
||||
onBound: () => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const [scopes, setScopes] = useState<DocSyncScope[] | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [query, setQuery] = useState('')
|
||||
const [newName, setNewName] = useState(suggestedName)
|
||||
const [working, setWorking] = useState<string | null>(null)
|
||||
|
||||
// `loadScopes`, not `sync`: the hook hands back a fresh object on every
|
||||
// render of the panel above, so depending on it re-listed the provider's
|
||||
// folders each time anything up there changed. The callback itself is
|
||||
// stable. Taken out of `sync` first, because calling it as `sync.loadScopes`
|
||||
// inside the effect makes the whole object a dependency again.
|
||||
const { loadScopes } = sync
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void (async () => {
|
||||
const res = await loadScopes(connection.id)
|
||||
if (cancelled) return
|
||||
setScopes(res.scopes)
|
||||
setError(res.error ?? null)
|
||||
})()
|
||||
return () => { cancelled = true }
|
||||
}, [connection.id, loadScopes])
|
||||
|
||||
const shown = useMemo(() => {
|
||||
const needle = query.trim().toLowerCase()
|
||||
if (!needle || !scopes) return scopes ?? []
|
||||
return scopes.filter(s => s.label.toLowerCase().includes(needle))
|
||||
}, [scopes, query])
|
||||
|
||||
const bind = async (scope: DocSyncScope) => {
|
||||
setWorking(scope.scopeKey)
|
||||
const ok = await sync.createLink({
|
||||
connectionId: connection.id,
|
||||
scopeKey: scope.scopeKey,
|
||||
remoteRootId: scope.remoteRootId,
|
||||
remoteRootPath: scope.remoteRootPath,
|
||||
remoteLabel: scope.label,
|
||||
direction: 'both',
|
||||
deletePolicy: 'unlink',
|
||||
conflictPolicy: 'manual',
|
||||
syncEnabled: true,
|
||||
})
|
||||
setWorking(null)
|
||||
if (ok) onBound()
|
||||
}
|
||||
|
||||
const createAndBind = async () => {
|
||||
const name = newName.trim()
|
||||
if (!name) return
|
||||
setWorking('__new__')
|
||||
try {
|
||||
// A refused create leaves nothing to bind; the hook has already put the
|
||||
// reason where the dialog shows it.
|
||||
const scope = await sync.createScope(connection.id, name)
|
||||
if (scope) await bind(scope)
|
||||
} finally {
|
||||
setWorking(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal isOpen onClose={onClose} size="md" title={t('docsync.scope.title', { provider: providerName })}>
|
||||
<div className="space-y-4">
|
||||
<p className="text-caption text-content-muted">{t('docsync.scope.intro')}</p>
|
||||
|
||||
<div className="rounded-xl border border-edge bg-surface-secondary p-3">
|
||||
<span className="mb-2 block text-body font-medium text-content">{t('docsync.scope.createTitle')}</span>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={newName}
|
||||
onChange={e => setNewName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void createAndBind() }}
|
||||
placeholder={t('docsync.newFolderPlaceholder')}
|
||||
className="min-w-0 flex-1 rounded-lg border border-edge bg-surface-input px-3 py-2 text-body text-content ring-accent focus:outline-none focus:ring-2"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void createAndBind()}
|
||||
disabled={!newName.trim() || working !== null}
|
||||
className="flex shrink-0 items-center gap-2 rounded-lg bg-accent px-3.5 py-2 text-body font-medium text-accent-text transition-opacity hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{working === '__new__' ? <Loader2 size={14} className="animate-spin" /> : <FolderPlus size={14} />}
|
||||
{t('docsync.scope.createAction')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between gap-3">
|
||||
<span className="text-body font-medium text-content">{t('docsync.scope.pickTitle')}</span>
|
||||
{scopes && scopes.length > 6 && (
|
||||
<span className="relative">
|
||||
<Search size={13} className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-content-faint" />
|
||||
<input
|
||||
value={query}
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
placeholder={t('docsync.scope.search')}
|
||||
className="w-44 rounded-lg border border-edge bg-surface-input py-1.5 pl-8 pr-2.5 text-caption text-content ring-accent focus:outline-none focus:ring-2"
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{sync.error && (
|
||||
<p className="mb-2 rounded-xl border border-edge bg-danger-soft px-3 py-2.5 text-caption text-danger">
|
||||
{t(`docsync.error.${sync.error}`)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{scopes === null ? (
|
||||
<div className="grid place-items-center rounded-xl border border-edge py-8">
|
||||
<Loader2 size={18} className="animate-spin text-content-faint" />
|
||||
</div>
|
||||
) : error ? (
|
||||
<p className="rounded-xl border border-edge bg-danger-soft px-3 py-2.5 text-caption text-danger">
|
||||
{t(`docsync.error.${error}`)}
|
||||
</p>
|
||||
) : shown.length === 0 ? (
|
||||
<p className="rounded-xl border border-dashed border-edge px-3 py-6 text-center text-caption text-content-muted">
|
||||
{query ? t('docsync.scope.noMatch') : t('docsync.noFolders')}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="max-h-64 divide-y divide-edge-faint overflow-y-auto rounded-xl border border-edge">
|
||||
{shown.map(s => (
|
||||
<li key={s.scopeKey}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void bind(s)}
|
||||
disabled={working !== null}
|
||||
className="flex w-full items-center justify-between gap-3 px-3 py-2.5 text-left transition-colors hover:bg-surface-hover disabled:opacity-50"
|
||||
>
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-body text-content">{s.label}</span>
|
||||
{s.remoteRootPath && (
|
||||
<span className="block truncate text-caption text-content-faint">{s.remoteRootPath}</span>
|
||||
)}
|
||||
</span>
|
||||
{working === s.scopeKey && <Loader2 size={14} className="shrink-0 animate-spin text-content-faint" />}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { docsyncApi } from '../../../api/client'
|
||||
import type { useDocSync } from './useDocSync'
|
||||
|
||||
/**
|
||||
* The documents that changed in both places, and the way out of that.
|
||||
*
|
||||
* The server has resolved conflicts since the first version and the strings
|
||||
* have been in the locales just as long, but neither shell ever listed them: a
|
||||
* binding reported "1 conflict" and the only place to act on it was the MCP
|
||||
* tool. So a conflict was a dead end for anyone using the app.
|
||||
*
|
||||
* Shared between the panel and the phone sheet because both list the same rows
|
||||
* with the same three answers, and because the duplication gate counts a second
|
||||
* copy of it against the PR.
|
||||
*/
|
||||
|
||||
export interface ConflictItem {
|
||||
id: number
|
||||
/** The trip file's name, or the provider's when TREK never got a copy. */
|
||||
name: string
|
||||
remoteName: string | null
|
||||
}
|
||||
|
||||
interface ItemRow {
|
||||
id: number
|
||||
file_name?: string | null
|
||||
remote_name?: string | null
|
||||
}
|
||||
|
||||
export function useConflicts(tripId: number | string, sync: ReturnType<typeof useDocSync>, open: boolean) {
|
||||
const [items, setItems] = useState<ConflictItem[] | null>(null)
|
||||
const [working, setWorking] = useState<number | null>(null)
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
const rows = (await docsyncApi.items(tripId, 'conflict')) as ItemRow[]
|
||||
setItems(
|
||||
rows.map(r => ({
|
||||
id: r.id,
|
||||
name: r.file_name || r.remote_name || '',
|
||||
remoteName: r.remote_name ?? null,
|
||||
})),
|
||||
)
|
||||
}, [tripId])
|
||||
|
||||
// Only once the list is on screen: a trip with no conflicts should not pay
|
||||
// for a request to find that out, and the count above it already says so.
|
||||
useEffect(() => {
|
||||
if (open) void reload()
|
||||
}, [open, reload])
|
||||
|
||||
const resolve = useCallback(
|
||||
async (itemId: number, keep: 'trek' | 'provider' | 'both') => {
|
||||
setWorking(itemId)
|
||||
try {
|
||||
await sync.resolveConflict(itemId, keep)
|
||||
// The row is gone from this list either way: it was resolved, or the
|
||||
// call failed and `sync.error` says so. Re-reading is what tells the
|
||||
// difference, rather than removing it here and hoping.
|
||||
await reload()
|
||||
} finally {
|
||||
setWorking(null)
|
||||
}
|
||||
},
|
||||
[sync, reload],
|
||||
)
|
||||
|
||||
return { items, working, resolve, reload }
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useState } from 'react'
|
||||
import type { DocSyncConnection, DocSyncProvider, useDocSync } from './useDocSync'
|
||||
|
||||
/**
|
||||
* The credential form's rules, for both shells.
|
||||
*
|
||||
* Which field carries the address, which one must not be drawn as a text box,
|
||||
* how a label becomes a translation key, what counts as filled in when a secret
|
||||
* is already stored: every one of those is a rule, and every one of them was
|
||||
* wrong in the phone sheet while being right on the desktop. The phone read the
|
||||
* address under `baseUrl` while the server names the field `base_url`, so every
|
||||
* connection it saved carried an empty address; it drew `allow_insecure_tls` as
|
||||
* a text input and always sent false; and it built label keys a different way,
|
||||
* so the labels rendered as raw keys.
|
||||
*
|
||||
* None of that is markup, so none of it belongs in a component.
|
||||
*/
|
||||
|
||||
/** The field that holds the address rather than a credential. */
|
||||
export const BASE_URL_FIELD = 'base_url'
|
||||
|
||||
/** Rendered as a switch beside the fields, never as one of them. */
|
||||
export const INSECURE_TLS_FIELD = 'allow_insecure_tls'
|
||||
|
||||
export interface ConnectForm {
|
||||
/** The fields to draw, in order, minus the ones with their own control. */
|
||||
fields: DocSyncProvider['fields']
|
||||
/** Translation key for a field's label, and for its hint where it has one. */
|
||||
labelKey: (field: DocSyncProvider['fields'][number]) => string
|
||||
hintKey: (field: DocSyncProvider['fields'][number]) => string | undefined
|
||||
/** What to show in a field: the typed value, else what is stored. */
|
||||
valueOf: (fieldKey: string) => string
|
||||
/** A stored secret never comes back, so its box shows dots instead. */
|
||||
placeholderOf: (field: DocSyncProvider['fields'][number]) => string
|
||||
setValue: (fieldKey: string, value: string) => void
|
||||
baseUrl: string
|
||||
credentials: Record<string, string>
|
||||
insecureTls: boolean
|
||||
setInsecureTls: (on: boolean) => void
|
||||
/** Every required field is either filled in or already stored. */
|
||||
complete: boolean
|
||||
probe: () => Promise<{ connected: boolean; account?: string; error?: string }>
|
||||
save: () => Promise<boolean>
|
||||
}
|
||||
|
||||
export function useConnectForm(
|
||||
provider: DocSyncProvider,
|
||||
existing: DocSyncConnection | null,
|
||||
sync: ReturnType<typeof useDocSync>,
|
||||
): ConnectForm {
|
||||
const [values, setValues] = useState<Record<string, string>>({})
|
||||
// Null until touched, so a connection that arrives after the form opened is
|
||||
// still reflected. Seeding from `existing` at mount showed a stored "allow
|
||||
// self-signed" as off and wrote that back on the next save.
|
||||
const [insecure, setInsecure] = useState<boolean | null>(null)
|
||||
|
||||
const insecureTls = insecure ?? existing?.allowInsecureTls ?? false
|
||||
|
||||
/**
|
||||
* What a box shows.
|
||||
*
|
||||
* A secret shows only what was typed into it this time, never what is stored:
|
||||
* a stored credential must not travel back to a browser, and a value that
|
||||
* ended up in `settings` by mistake must not become the one place it leaks.
|
||||
* The address lives in its own column rather than in settings, so it is read
|
||||
* from there; everything else comes out of settings.
|
||||
*/
|
||||
const secretKeys = new Set(provider.fields.filter(f => f.secret).map(f => f.field_key))
|
||||
const valueOf = (key: string) => {
|
||||
if (secretKeys.has(key)) return values[key] ?? ''
|
||||
return values[key] ?? (key === BASE_URL_FIELD ? existing?.baseUrl : existing?.settings?.[key]) ?? ''
|
||||
}
|
||||
|
||||
const baseUrl = valueOf(BASE_URL_FIELD)
|
||||
// The address stays in here as well as in its own argument: the server walks
|
||||
// the provider's fields over `credentials` and would otherwise store no
|
||||
// `base_url` setting. It special-cases the key when checking completeness, so
|
||||
// dropping it changes nothing it needs, but it is an established request
|
||||
// shape and this is not the change to alter it in.
|
||||
const credentials = Object.fromEntries(
|
||||
Object.entries(values).filter(([k]) => k !== INSECURE_TLS_FIELD),
|
||||
)
|
||||
|
||||
const fields = provider.fields.filter(f => f.field_key !== INSECURE_TLS_FIELD)
|
||||
|
||||
const complete = fields.every(f => {
|
||||
if (!f.required) return true
|
||||
if (f.secret) return (values[f.field_key] ?? '').length > 0 || !!existing?.secrets?.[f.field_key]
|
||||
return valueOf(f.field_key).trim().length > 0
|
||||
})
|
||||
|
||||
return {
|
||||
fields,
|
||||
// The label and hint columns store a key suffix, not text.
|
||||
labelKey: f => `docsync.${f.label}`,
|
||||
hintKey: f => (f.hint ? `docsync.${f.hint}` : undefined),
|
||||
valueOf,
|
||||
placeholderOf: f =>
|
||||
f.secret && existing?.secrets?.[f.field_key] ? '••••••••' : f.placeholder || '',
|
||||
setValue: (key, value) => setValues(v => ({ ...v, [key]: value })),
|
||||
baseUrl,
|
||||
credentials,
|
||||
insecureTls,
|
||||
setInsecureTls: setInsecure,
|
||||
complete,
|
||||
probe: () => sync.testConnection(provider.id, baseUrl, credentials, insecureTls),
|
||||
save: () => sync.saveConnection(provider.id, baseUrl, credentials, insecureTls),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
// FE-DOCSYNC-HOOK-001 to FE-DOCSYNC-HOOK-030
|
||||
|
||||
/**
|
||||
* The document-sync hook.
|
||||
*
|
||||
* Everything the panel and the phone sheet know about sync comes through here,
|
||||
* so the interesting behaviour is what a person sees: holdings that arrive on a
|
||||
* different route than the bindings they belong to, a dialog that must not flash
|
||||
* white every time a switch is flipped, a toggle that moves before the server
|
||||
* has answered, and a probe that has to produce a verdict even when the request
|
||||
* itself fell over.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook, act, waitFor } from '../../../../tests/helpers/render'
|
||||
|
||||
const providersApi = vi.fn(async (_tripId: number | string): Promise<unknown> => [])
|
||||
const statusApi = vi.fn(async (_tripId: number | string): Promise<unknown> => ({}))
|
||||
const listConnectionsApi = vi.fn(async (_tripId: number | string): Promise<unknown> => [])
|
||||
const listLinksApi = vi.fn(async (_tripId: number | string): Promise<unknown> => [])
|
||||
const saveConnectionApi = vi.fn(async (_tripId: number | string, _data: unknown): Promise<unknown> => ({}))
|
||||
const testConnectionApi = vi.fn(async (_tripId: number | string, _data: unknown): Promise<unknown> => ({ connected: true }))
|
||||
const updateLinkApi = vi.fn(async (_tripId: number | string, _linkId: number, _patch: unknown): Promise<unknown> => ({}))
|
||||
const syncNowApi = vi.fn(async (_tripId: number | string, _linkId: number, _full: boolean): Promise<unknown> => ({}))
|
||||
const listScopesApi = vi.fn(async (_tripId: number | string, _connectionId: number, _q?: string): Promise<unknown> => ({ scopes: [] }))
|
||||
const resolveApi = vi.fn(async (_tripId: number | string, _itemId: number, _keep: string): Promise<unknown> => ({ success: true }))
|
||||
|
||||
vi.mock('../../../api/client', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../../api/client')>()
|
||||
return {
|
||||
...actual,
|
||||
docsyncApi: {
|
||||
...actual.docsyncApi,
|
||||
providers: (tripId: number | string) => providersApi(tripId),
|
||||
status: (tripId: number | string) => statusApi(tripId),
|
||||
listConnections: (tripId: number | string) => listConnectionsApi(tripId),
|
||||
listLinks: (tripId: number | string) => listLinksApi(tripId),
|
||||
saveConnection: (tripId: number | string, data: unknown) => saveConnectionApi(tripId, data),
|
||||
testConnection: (tripId: number | string, data: unknown) => testConnectionApi(tripId, data),
|
||||
updateLink: (tripId: number | string, linkId: number, patch: unknown) => updateLinkApi(tripId, linkId, patch),
|
||||
syncNow: (tripId: number | string, linkId: number, full: boolean) => syncNowApi(tripId, linkId, full),
|
||||
listScopes: (tripId: number | string, connectionId: number, q?: string) => listScopesApi(tripId, connectionId, q),
|
||||
resolve: (tripId: number | string, itemId: number, keep: string) => resolveApi(tripId, itemId, keep),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
import { useDocSync, canManageDocSync, needsReauth, storeName, type DocSyncLink, type DocSyncProvider } from './useDocSync'
|
||||
|
||||
const TRIP = 3
|
||||
|
||||
const provider = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'nextcloud',
|
||||
name: 'Nextcloud',
|
||||
description: null,
|
||||
icon: 'cloud',
|
||||
available: true,
|
||||
fields: [],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const connection = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 9,
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example',
|
||||
settings: {},
|
||||
secrets: {},
|
||||
allowInsecureTls: false,
|
||||
lastProbeState: 'ok',
|
||||
lastProbeError: null,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const link = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 1,
|
||||
connectionId: 9,
|
||||
providerId: 'nextcloud',
|
||||
scopeKey: 'trip',
|
||||
remoteLabel: 'Trip documents',
|
||||
remoteRootPath: '/Trips/Rome',
|
||||
direction: 'both',
|
||||
deletePolicy: 'unlink',
|
||||
conflictPolicy: 'newer',
|
||||
syncEnabled: true,
|
||||
lastSyncAt: null,
|
||||
lastSyncState: 'idle',
|
||||
lastSyncError: null,
|
||||
webhookUrl: null,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
/** A promise this test settles by hand, to hold a request open. */
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason?: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej })
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
/** Mount the hook and record `loading` on every render it goes through. */
|
||||
function mount(tripId: number | string = TRIP, enabled = true) {
|
||||
const seenLoading: boolean[] = []
|
||||
const view = renderHook(() => {
|
||||
const hook = useDocSync(tripId, enabled)
|
||||
seenLoading.push(hook.loading)
|
||||
return hook
|
||||
})
|
||||
return { ...view, seenLoading }
|
||||
}
|
||||
|
||||
/** Mount and wait until the first load is through. */
|
||||
async function mountLoaded(tripId: number | string = TRIP) {
|
||||
const view = mount(tripId)
|
||||
await waitFor(() => expect(view.result.current.loading).toBe(false))
|
||||
return view
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
providersApi.mockResolvedValue([provider()])
|
||||
statusApi.mockResolvedValue({ items: {}, links: [] })
|
||||
listConnectionsApi.mockResolvedValue([connection()])
|
||||
listLinksApi.mockResolvedValue([link()])
|
||||
saveConnectionApi.mockResolvedValue({})
|
||||
testConnectionApi.mockResolvedValue({ connected: true })
|
||||
updateLinkApi.mockResolvedValue({})
|
||||
syncNowApi.mockResolvedValue({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 })
|
||||
listScopesApi.mockResolvedValue({ scopes: [] })
|
||||
resolveApi.mockResolvedValue({ success: true })
|
||||
})
|
||||
|
||||
describe('useDocSync initial load', () => {
|
||||
it('FE-DOCSYNC-HOOK-001: joins the status route holdings onto the binding they belong to', async () => {
|
||||
const holdings = { inTrek: 7, atProvider: 5, paired: 4, missing: 1 }
|
||||
listLinksApi.mockResolvedValue([link()])
|
||||
statusApi.mockResolvedValue({ items: { conflict: 2, pending: 1 }, links: [{ id: 1, holdings }] })
|
||||
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
expect(result.current.links).toHaveLength(1)
|
||||
expect(result.current.links[0].holdings).toEqual(holdings)
|
||||
expect(result.current.itemCounts).toEqual({ conflict: 2, pending: 1 })
|
||||
expect(result.current.connections).toEqual([connection()])
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-002: a binding the status route never mentions does not inherit another binding counts', async () => {
|
||||
const holdings = { inTrek: 7, atProvider: 5, paired: 4, missing: 1 }
|
||||
listLinksApi.mockResolvedValue([link(), link({ id: 2, remoteLabel: 'Receipts' })])
|
||||
statusApi.mockResolvedValue({ items: {}, links: [{ id: 1, holdings }] })
|
||||
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
expect(result.current.links[0].holdings).toEqual(holdings)
|
||||
expect(result.current.links[1].holdings).toBeUndefined()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-025: carries the provider switch from the status route onto its binding', async () => {
|
||||
listLinksApi.mockResolvedValue([link(), link({ id: 2 }), link({ id: 3 })])
|
||||
statusApi.mockResolvedValue({ items: {}, links: [{ id: 1, providerOff: true }, { id: 2, providerOff: false }] })
|
||||
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
// The third is one the status route never mentions: running, not paused.
|
||||
expect(result.current.links.map(l => l.providerOff)).toEqual([true, false, false])
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-003: a status body without an items map leaves the counts empty', async () => {
|
||||
statusApi.mockResolvedValue({})
|
||||
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
expect(result.current.itemCounts).toEqual({})
|
||||
expect(result.current.links[0].holdings).toBeUndefined()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-004: offers only the providers this instance can actually use', async () => {
|
||||
providersApi.mockResolvedValue([
|
||||
provider(),
|
||||
provider({ id: 'gdrive', name: 'Google Drive', available: false }),
|
||||
])
|
||||
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
expect(result.current.providers.map(p => p.id)).toEqual(['nextcloud'])
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-005: a failed load leaves nothing to configure instead of blowing up', async () => {
|
||||
// The addon was switched off, or this member lost access to the trip.
|
||||
providersApi.mockRejectedValue(Object.assign(new Error('forbidden'), { response: { status: 403 } }))
|
||||
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
expect(result.current.providers).toEqual([])
|
||||
expect(result.current.links).toEqual([])
|
||||
expect(result.current.error).toBeNull()
|
||||
expect(result.current.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-023: a reload that finds the addon gone drops the bindings it had loaded', async () => {
|
||||
statusApi.mockResolvedValue({ items: { conflict: 1 }, links: [] })
|
||||
const { result } = await mountLoaded()
|
||||
expect(result.current.links).toHaveLength(1)
|
||||
|
||||
providersApi.mockRejectedValue(Object.assign(new Error('not found'), { response: { status: 404 } }))
|
||||
await act(async () => { await result.current.load() })
|
||||
|
||||
expect(result.current.providers).toEqual([])
|
||||
expect(result.current.connections).toEqual([])
|
||||
expect(result.current.links).toEqual([])
|
||||
expect(result.current.itemCounts).toEqual({})
|
||||
expect(result.current.error).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-006: asks the server nothing while the panel is closed', async () => {
|
||||
const { result } = mount(TRIP, false)
|
||||
|
||||
await act(async () => { await Promise.resolve() })
|
||||
|
||||
expect(providersApi).not.toHaveBeenCalled()
|
||||
expect(listLinksApi).not.toHaveBeenCalled()
|
||||
expect(result.current.loading).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDocSync spinner', () => {
|
||||
it('FE-DOCSYNC-HOOK-007: shows the spinner for the first load, which has nothing to show yet', async () => {
|
||||
const gate = deferred<unknown>()
|
||||
listLinksApi.mockReturnValueOnce(gate.promise)
|
||||
|
||||
const { result, seenLoading } = mount()
|
||||
|
||||
expect(result.current.loading).toBe(true)
|
||||
expect(seenLoading[seenLoading.length - 1]).toBe(true)
|
||||
|
||||
await act(async () => { gate.resolve([link()]) })
|
||||
await waitFor(() => expect(result.current.loading).toBe(false))
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-008: never raises the spinner again while a mutation refetches', async () => {
|
||||
// Regression guard: a refetch that flips `loading` swaps the whole dialog
|
||||
// for a spinner and back, so flipping one switch flashes the panel white.
|
||||
const { result, seenLoading } = await mountLoaded()
|
||||
const gate = deferred<unknown>()
|
||||
listLinksApi.mockReturnValueOnce(gate.promise)
|
||||
seenLoading.length = 0
|
||||
|
||||
let pending!: Promise<boolean>
|
||||
await act(async () => { pending = result.current.updateLink(1, { syncEnabled: false }) })
|
||||
expect(result.current.loading).toBe(false)
|
||||
|
||||
await act(async () => {
|
||||
gate.resolve([link({ syncEnabled: false })])
|
||||
await pending
|
||||
})
|
||||
|
||||
// the refetch really happened...
|
||||
expect(listLinksApi).toHaveBeenCalledTimes(2)
|
||||
// ...and the panel never went blank for it
|
||||
expect(seenLoading).not.toContain(true)
|
||||
expect(result.current.loading).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDocSync updateLink', () => {
|
||||
it('FE-DOCSYNC-HOOK-009: moves the switch before the server has answered', async () => {
|
||||
const { result } = await mountLoaded()
|
||||
const gate = deferred<unknown>()
|
||||
updateLinkApi.mockReturnValueOnce(gate.promise)
|
||||
|
||||
let pending!: Promise<boolean>
|
||||
await act(async () => { pending = result.current.updateLink(1, { direction: 'pull' }) })
|
||||
|
||||
expect(result.current.links[0].direction).toBe('pull')
|
||||
expect(updateLinkApi).toHaveBeenCalledWith(TRIP, 1, { direction: 'pull' })
|
||||
|
||||
await act(async () => { gate.resolve({}); await pending })
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-010: reloads afterwards, so the server row is what stays on screen', async () => {
|
||||
const { result } = await mountLoaded()
|
||||
listLinksApi.mockResolvedValue([link({ direction: 'pull', lastSyncState: 'ok', remoteLabel: 'Trip documents (moved)' })])
|
||||
|
||||
await act(async () => { await result.current.updateLink(1, { direction: 'pull' }) })
|
||||
|
||||
expect(listLinksApi).toHaveBeenCalledTimes(2)
|
||||
expect(result.current.links[0].remoteLabel).toBe('Trip documents (moved)')
|
||||
expect(result.current.links[0].lastSyncState).toBe('ok')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-011: a rejected update does not leave the optimistic value standing', async () => {
|
||||
const { result } = await mountLoaded()
|
||||
updateLinkApi.mockRejectedValueOnce({ response: { data: { error: 'forbidden' } } })
|
||||
listLinksApi.mockResolvedValueOnce([link({ direction: 'both' })])
|
||||
|
||||
let ok: boolean | undefined
|
||||
await act(async () => { ok = await result.current.updateLink(1, { direction: 'pull' }) })
|
||||
|
||||
// Reported rather than thrown: both shells call this as `void`, so a
|
||||
// rejection reached nobody. The reload puts the server's answer back and
|
||||
// the reason stays on screen.
|
||||
expect(ok).toBe(false)
|
||||
expect(result.current.links[0].direction).toBe('both')
|
||||
expect(result.current.error).toBe('forbidden')
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDocSync testConnection', () => {
|
||||
it('FE-DOCSYNC-HOOK-012: hands the probe verdict back to the form', async () => {
|
||||
testConnectionApi.mockResolvedValue({ connected: true, account: 'owner@cloud.example' })
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
let verdict: { connected: boolean; account?: string; error?: string } | undefined
|
||||
await act(async () => {
|
||||
verdict = await result.current.testConnection('nextcloud', 'https://cloud.example', { token: 'abc' }, false)
|
||||
})
|
||||
|
||||
expect(verdict).toEqual({ connected: true, account: 'owner@cloud.example' })
|
||||
expect(testConnectionApi).toHaveBeenCalledWith(TRIP, {
|
||||
providerId: 'nextcloud',
|
||||
baseUrl: 'https://cloud.example',
|
||||
credentials: { token: 'abc' },
|
||||
allowInsecureTls: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-013: a request that throws still produces a verdict the form can render', async () => {
|
||||
testConnectionApi.mockRejectedValueOnce({ response: { data: { error: 'docsync.unreachable' } } })
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
let verdict: { connected: boolean; error?: string } | undefined
|
||||
await act(async () => {
|
||||
verdict = await result.current.testConnection('nextcloud', 'https://typo.example', {}, false)
|
||||
})
|
||||
|
||||
expect(verdict).toEqual({ connected: false, error: 'docsync.unreachable' })
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-014: an error with no message of its own falls back to a generic one', async () => {
|
||||
testConnectionApi.mockRejectedValueOnce(new Error('socket hang up'))
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
let verdict: { connected: boolean; error?: string } | undefined
|
||||
await act(async () => {
|
||||
verdict = await result.current.testConnection('nextcloud', 'https://cloud.example', {}, false)
|
||||
})
|
||||
|
||||
expect(verdict).toEqual({ connected: false, error: 'unknown' })
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-015: marks the probe busy while it runs and clears it when it lands', async () => {
|
||||
const { result } = await mountLoaded()
|
||||
const gate = deferred<unknown>()
|
||||
testConnectionApi.mockReturnValueOnce(gate.promise)
|
||||
|
||||
let pending!: Promise<unknown>
|
||||
await act(async () => { pending = result.current.testConnection('nextcloud', 'https://cloud.example', {}, false) })
|
||||
expect(result.current.busy).toBe('test')
|
||||
|
||||
await act(async () => { gate.resolve({ connected: true }); await pending })
|
||||
expect(result.current.busy).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDocSync run and save feedback', () => {
|
||||
it('FE-DOCSYNC-HOOK-016: remembers what the last run moved, per binding', async () => {
|
||||
syncNowApi.mockResolvedValue({ state: 'ok', pulled: 4, pushed: 2, conflicts: 0, missing: 0 })
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
await act(async () => { await result.current.syncNow(1) })
|
||||
|
||||
expect(syncNowApi).toHaveBeenCalledWith(TRIP, 1, false)
|
||||
// What a run moved is no longer kept: the flow bar shows standing holdings,
|
||||
// which is the question somebody opening the dialog actually has. The run's
|
||||
// own numbers were only ever on screen for the moment after pressing it.
|
||||
expect(result.current.links).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-017: a refused run says so instead of vanishing into a void call', async () => {
|
||||
// syncNow is called as `void sync.syncNow(...)` from both shells, so a
|
||||
// rejection that escaped the hook reached nobody. An orphaned binding
|
||||
// answers 409 here, and the person pressing the button deserves the reason.
|
||||
syncNowApi.mockRejectedValueOnce({ response: { data: { error: 'link_orphaned' } } })
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
let outcome: unknown
|
||||
await act(async () => { outcome = await result.current.syncNow(1) })
|
||||
|
||||
expect(outcome).toBeNull()
|
||||
expect(result.current.error).toBe('link_orphaned')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-026: a run refused because an admin switched the provider off keeps the code', async () => {
|
||||
// Both shells render the error as docsync.error.<code>, so the code has to
|
||||
// arrive untouched for the sentence to be the right one.
|
||||
syncNowApi.mockRejectedValueOnce({ response: { status: 409, data: { error: 'provider_disabled' } } })
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
await act(async () => { await result.current.syncNow(1) })
|
||||
|
||||
expect(result.current.error).toBe('provider_disabled')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-018: a refused save reports failure and surfaces the server reason', async () => {
|
||||
saveConnectionApi.mockRejectedValueOnce({ response: { data: { message: 'docsync.badCredentials' } } })
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
let ok: boolean | undefined
|
||||
await act(async () => {
|
||||
ok = await result.current.saveConnection('nextcloud', 'https://cloud.example', { token: 'nope' }, false)
|
||||
})
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(result.current.error).toBe('docsync.badCredentials')
|
||||
expect(result.current.busy).toBeNull()
|
||||
// nothing was refetched, because nothing changed server-side
|
||||
expect(listLinksApi).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDocSync loadScopes', () => {
|
||||
it('FE-DOCSYNC-HOOK-027: a request that fell over still produces a listing the picker can render', async () => {
|
||||
// The picker awaits this inside an effect with nothing to catch, so a
|
||||
// rejection never reached `setScopes` and the spinner ran forever. A store
|
||||
// behind a VPN that is down answers this way every time.
|
||||
listScopesApi.mockRejectedValueOnce({ code: 'ECONNABORTED', message: 'timeout of 60000ms exceeded' })
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
let listing: unknown
|
||||
await act(async () => { listing = await result.current.loadScopes(9) })
|
||||
|
||||
expect(listing).toEqual({ scopes: [], error: 'unknown' })
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-028: a refusal with a code keeps the code, a sentence does not become a key', async () => {
|
||||
const { result } = await mountLoaded()
|
||||
let listing: { scopes: unknown[]; error?: string } | undefined
|
||||
|
||||
listScopesApi.mockRejectedValueOnce({ response: { status: 400, data: { error: 'unknown_provider' } } })
|
||||
await act(async () => { listing = await result.current.loadScopes(9, 'tri') })
|
||||
expect(listing?.error).toBe('unknown_provider')
|
||||
expect(listScopesApi).toHaveBeenCalledWith(TRIP, 9, 'tri')
|
||||
|
||||
// The picker renders this as docsync.error.<value>, so prose must not
|
||||
// arrive there as a translation key.
|
||||
listScopesApi.mockRejectedValueOnce({ response: { status: 404, data: { message: 'Connection not found' } } })
|
||||
await act(async () => { listing = await result.current.loadScopes(9) })
|
||||
expect(listing?.error).toBe('unknown')
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDocSync resolveConflict', () => {
|
||||
it('FE-DOCSYNC-HOOK-029: a refused choice says why instead of vanishing into a void call', async () => {
|
||||
// Both shells call this as `void conflicts.resolve(...)`. A member's choice
|
||||
// answers 403 and a row settled elsewhere answers 400; either way the
|
||||
// button came back and nothing said what happened.
|
||||
resolveApi.mockRejectedValueOnce({ response: { status: 403, data: { error: 'forbidden' } } })
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
let outcome: boolean | undefined
|
||||
await act(async () => { outcome = await result.current.resolveConflict(4, 'trek') })
|
||||
|
||||
expect(outcome).toBe(false)
|
||||
expect(result.current.error).toBe('forbidden')
|
||||
// reloaded, so the counts are the server's, and the message survived it
|
||||
expect(listLinksApi).toHaveBeenCalledTimes(2)
|
||||
|
||||
await act(async () => { outcome = await result.current.resolveConflict(4, 'provider') })
|
||||
|
||||
expect(outcome).toBe(true)
|
||||
expect(result.current.error).toBeNull()
|
||||
expect(resolveApi).toHaveBeenLastCalledWith(TRIP, 4, 'provider')
|
||||
})
|
||||
})
|
||||
|
||||
describe('needsReauth', () => {
|
||||
it('FE-DOCSYNC-HOOK-030: reads a refused credential off either the state or the error code', () => {
|
||||
expect(needsReauth({ lastSyncState: 'needs_reauth', lastSyncError: null })).toBe(true)
|
||||
expect(needsReauth({ lastSyncState: 'failed', lastSyncError: 'unauthorized' })).toBe(true)
|
||||
expect(needsReauth({ lastSyncState: 'partial', lastSyncError: 'unauthorized' })).toBe(true)
|
||||
expect(needsReauth({ lastSyncState: 'failed', lastSyncError: 'unreachable' })).toBe(false)
|
||||
expect(needsReauth({ lastSyncState: 'ok', lastSyncError: null })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('storeName', () => {
|
||||
it('FE-DOCSYNC-HOOK-024: prefers the provider list, then the name on the link, then the raw id', () => {
|
||||
const bound = link() as DocSyncLink
|
||||
const listed = [provider({ name: 'Nextcloud Hub' }) as DocSyncProvider]
|
||||
|
||||
expect(storeName({ ...bound, providerName: 'Nextcloud' }, listed)).toBe('Nextcloud Hub')
|
||||
// Switched off by an admin, so the providers route no longer lists it.
|
||||
expect(storeName({ ...bound, providerName: 'Nextcloud' }, [])).toBe('Nextcloud')
|
||||
expect(storeName(bound, [])).toBe('nextcloud')
|
||||
})
|
||||
})
|
||||
|
||||
describe('canManageDocSync', () => {
|
||||
it('FE-DOCSYNC-HOOK-019: the trip owner may repoint a binding', () => {
|
||||
expect(canManageDocSync({ id: 4, role: 'user' }, { user_id: 4 })).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-020: an instance admin may, even on a trip that is not theirs', () => {
|
||||
expect(canManageDocSync({ id: 12, role: 'admin' }, { user_id: 4 })).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-021: an ordinary member may not point the owner archive somewhere else', () => {
|
||||
expect(canManageDocSync({ id: 12, role: 'user' }, { user_id: 4 })).toBe(false)
|
||||
expect(canManageDocSync({ id: 12, role: 'user' }, null)).toBe(false)
|
||||
expect(canManageDocSync({ id: 12, role: 'user' }, {})).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-022: nobody signed in, nobody may manage', () => {
|
||||
expect(canManageDocSync(null, { user_id: 4 })).toBe(false)
|
||||
expect(canManageDocSync(undefined, { user_id: 4 })).toBe(false)
|
||||
// ids arrive as strings on some routes and as numbers on others
|
||||
expect(canManageDocSync({ id: '4', role: 'user' }, { user_id: 4 })).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,449 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { docsyncApi } from '../../../api/client'
|
||||
import { useServerPing } from '../../../sync/useServerPing'
|
||||
|
||||
/**
|
||||
* All document-sync state and actions, in one hook.
|
||||
*
|
||||
* Deliberately a hook rather than logic inside the panel: the phone shell is a
|
||||
* separate component tree (client/src/mobile/screens/trip/...), and duplicating
|
||||
* this across both would land on SonarCloud's 3% duplication budget the way the
|
||||
* photo provider section already does. `useDawarichConnection` states the same
|
||||
* reason for the same problem.
|
||||
*/
|
||||
|
||||
export interface DocSyncField {
|
||||
field_key: string
|
||||
label: string
|
||||
input_type: string
|
||||
placeholder: string | null
|
||||
hint: string | null
|
||||
required: boolean
|
||||
secret: boolean
|
||||
}
|
||||
|
||||
export interface DocSyncProvider {
|
||||
id: string
|
||||
name: string
|
||||
description: string | null
|
||||
icon: string
|
||||
available: boolean
|
||||
fields: DocSyncField[]
|
||||
}
|
||||
|
||||
export interface DocSyncConnection {
|
||||
id: number
|
||||
providerId: string
|
||||
baseUrl: string
|
||||
settings: Record<string, string>
|
||||
secrets: Record<string, string>
|
||||
allowInsecureTls: boolean
|
||||
lastProbeState: string
|
||||
lastProbeError: string | null
|
||||
}
|
||||
|
||||
export interface DocSyncScope {
|
||||
scopeKey: string
|
||||
label: string
|
||||
remoteRootId: string | null
|
||||
remoteRootPath: string | null
|
||||
}
|
||||
|
||||
export interface DocSyncLink {
|
||||
id: number
|
||||
connectionId: number
|
||||
providerId: string
|
||||
scopeKey: string
|
||||
remoteLabel: string
|
||||
remoteRootPath: string | null
|
||||
direction: 'both' | 'pull' | 'push'
|
||||
deletePolicy: 'unlink' | 'trash'
|
||||
conflictPolicy: string
|
||||
syncEnabled: boolean
|
||||
lastSyncAt: string | null
|
||||
lastSyncState: string
|
||||
lastSyncError: string | null
|
||||
webhookUrl: string | null
|
||||
/**
|
||||
* The store's display name as the server knows it. Carried on the link
|
||||
* because the providers route only lists what an admin has switched on, and
|
||||
* a binding outlives its provider being switched off.
|
||||
*/
|
||||
providerName?: string
|
||||
/** Standing counts per side, from the status route. */
|
||||
holdings?: { inTrek: number; atProvider: number; paired: number; missing: number }
|
||||
/**
|
||||
* An admin has switched this binding's provider off. The server leaves the
|
||||
* binding as it was, so `lastSyncState` still describes the last run and
|
||||
* this is what says why nothing moves now. From the status route.
|
||||
*/
|
||||
providerOff?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* What to call the store a binding points at.
|
||||
*
|
||||
* One lookup for both shells, so the list row, the card header and the flow
|
||||
* summary cannot name the same store three different ways. The providers list
|
||||
* wins because the rest of the dialog uses its names; the link's own name
|
||||
* covers a provider that has since been switched off.
|
||||
*/
|
||||
export function storeName(link: DocSyncLink, providers: readonly DocSyncProvider[]): string {
|
||||
return providers.find(p => p.id === link.providerId)?.name || link.providerName || link.providerId
|
||||
}
|
||||
|
||||
/**
|
||||
* The line a binding card shows under its header, or null when there is
|
||||
* nothing to say.
|
||||
*
|
||||
* Both shells render it, so a phone and a laptop cannot disagree about why a
|
||||
* binding stands still. A provider an admin switched off comes first: the
|
||||
* server leaves the binding's state as the last run wrote it, which would
|
||||
* otherwise report an old failure, or nothing, for a binding that is paused.
|
||||
*/
|
||||
export function bindingNotice(
|
||||
link: Pick<DocSyncLink, 'providerOff' | 'lastSyncState' | 'lastSyncError'>,
|
||||
t: (key: string) => string,
|
||||
): string | null {
|
||||
if (link.providerOff) return t('docsync.error.provider_disabled')
|
||||
if (link.lastSyncState === 'ok' || link.lastSyncState === 'never') return null
|
||||
const state = t(`docsync.linkState.${link.lastSyncState}`)
|
||||
return link.lastSyncError ? `${state} · ${t(`docsync.error.${link.lastSyncError}`)}` : state
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the store has refused the stored credential.
|
||||
*
|
||||
* Two shapes say so. A refusal while listing is recorded as its own state; a
|
||||
* refusal anywhere else (resolving the folder, one transfer) leaves the state
|
||||
* at failed or partial and puts the reason in the error code. Either way the
|
||||
* cure is the same, a new credential, and both shells decide from here
|
||||
* whether to offer the form for it.
|
||||
*/
|
||||
export function needsReauth(link: Pick<DocSyncLink, 'lastSyncState' | 'lastSyncError'>): boolean {
|
||||
return link.lastSyncState === 'needs_reauth' || link.lastSyncError === 'unauthorized'
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this person may change a sync binding.
|
||||
*
|
||||
* Only the trip owner: the credential a binding stores usually reaches that
|
||||
* person's entire document archive, so letting any member repoint it would
|
||||
* share a folder the owner never chose to share. Instance admins are included
|
||||
* because they already override every other permission check in the client.
|
||||
*
|
||||
* Shared by both shells rather than written out twice: the desktop file
|
||||
* manager and the phone sheet must not be able to drift on who may do this.
|
||||
*/
|
||||
export function canManageDocSync(
|
||||
user: { id?: number | string; role?: string } | null | undefined,
|
||||
trip: { user_id?: number | string } | null | undefined,
|
||||
): boolean {
|
||||
if (!user) return false
|
||||
return user.role === 'admin' || Number(trip?.user_id) === Number(user.id)
|
||||
}
|
||||
|
||||
export function useDocSync(tripId: number | string, enabled: boolean) {
|
||||
const [providers, setProviders] = useState<DocSyncProvider[]>([])
|
||||
const [connections, setConnections] = useState<DocSyncConnection[]>([])
|
||||
const [links, setLinks] = useState<DocSyncLink[]>([])
|
||||
const [itemCounts, setItemCounts] = useState<Record<string, number>>({})
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [busy, setBusy] = useState<string | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
/**
|
||||
* Whether the first load is through.
|
||||
*
|
||||
* Every mutation refreshes, and a refresh that flips `loading` swaps the whole
|
||||
* dialog for a spinner and back: a white flash on something as small as
|
||||
* toggling a direction. Only the first load has nothing to show yet.
|
||||
*/
|
||||
const loadedOnce = useRef(false)
|
||||
|
||||
/**
|
||||
* Which load is the current one.
|
||||
*
|
||||
* Four requests go out per load and several loads overlap: every mutation
|
||||
* starts one, and so does every ping. Without a generation stamp the slowest
|
||||
* response wins, which on a binding somebody just changed means the screen
|
||||
* settles on the state from before the change.
|
||||
*/
|
||||
const generation = useRef(0)
|
||||
/** Whether the last failure came from loading rather than from a write. */
|
||||
const loadFailed = useRef(false)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!enabled) return
|
||||
const mine = ++generation.current
|
||||
if (!loadedOnce.current) setLoading(true)
|
||||
try {
|
||||
const [p, c, l, s] = await Promise.all([
|
||||
docsyncApi.providers(tripId),
|
||||
docsyncApi.listConnections(tripId),
|
||||
docsyncApi.listLinks(tripId),
|
||||
docsyncApi.status(tripId),
|
||||
])
|
||||
if (mine !== generation.current) return
|
||||
setProviders(p as DocSyncProvider[])
|
||||
setConnections(c as DocSyncConnection[])
|
||||
// The status route carries the holdings and the provider switch; the
|
||||
// links route does not, so the two are merged here rather than asking
|
||||
// every caller to join them.
|
||||
const status = s as { items?: Record<string, number>; links?: DocSyncLink[] }
|
||||
const statusById = new Map((status.links ?? []).map(x => [x.id, x]))
|
||||
setLinks((l as DocSyncLink[]).map(x => ({
|
||||
...x,
|
||||
holdings: statusById.get(x.id)?.holdings,
|
||||
providerOff: statusById.get(x.id)?.providerOff === true,
|
||||
})))
|
||||
setItemCounts(status.items || {})
|
||||
// Only a load failure is cleared here. A write that just failed reloads to
|
||||
// put the server's answer back on screen, and clearing unconditionally
|
||||
// wiped the reason it had set a moment earlier.
|
||||
setError(prev => (prev !== null && loadFailed.current ? null : prev))
|
||||
loadFailed.current = false
|
||||
loadedOnce.current = true
|
||||
} catch (e: unknown) {
|
||||
// A 403 or 404 really does mean "nothing to configure here" (the addon is
|
||||
// off or this person lost access), and blanking the panel is the honest
|
||||
// answer. Anything else is a failure to say so: blanking on a dropped
|
||||
// connection told the user their provider list was empty.
|
||||
if (mine !== generation.current) return
|
||||
const status = (e as { response?: { status?: number } })?.response?.status
|
||||
loadFailed.current = true
|
||||
if (status === 403 || status === 404) {
|
||||
// The bindings go too. Both shells keep a binding on screen with no
|
||||
// provider left, so emptying the providers alone blanked nothing.
|
||||
setProviders([])
|
||||
setConnections([])
|
||||
setLinks([])
|
||||
setItemCounts({})
|
||||
setError(null)
|
||||
} else {
|
||||
setError(readError(e))
|
||||
}
|
||||
} finally {
|
||||
if (mine === generation.current) setLoading(false)
|
||||
}
|
||||
}, [tripId, enabled])
|
||||
|
||||
useEffect(() => { void load() }, [load])
|
||||
|
||||
// A run started by another member moves the same documents and the same
|
||||
// counts. The event is a ping rather than a payload: the numbers it would
|
||||
// carry are per-binding server state, and reading them back is the only way
|
||||
// this panel and that member's panel end up saying the same thing.
|
||||
useServerPing('docsync:changed', enabled, load)
|
||||
|
||||
const connectionFor = useCallback(
|
||||
(providerId: string) => connections.find(c => c.providerId === providerId) || null,
|
||||
[connections],
|
||||
)
|
||||
|
||||
const saveConnection = useCallback(async (providerId: string, baseUrl: string, credentials: Record<string, string>, allowInsecureTls: boolean) => {
|
||||
setBusy('save')
|
||||
setError(null)
|
||||
try {
|
||||
await docsyncApi.saveConnection(tripId, { providerId, baseUrl, credentials, allowInsecureTls })
|
||||
await load()
|
||||
return true
|
||||
} catch (e: unknown) {
|
||||
setError(readError(e))
|
||||
return false
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}, [tripId, load])
|
||||
|
||||
/**
|
||||
* Probe without saving. Always resolves to a verdict object: the route
|
||||
* answers 200 even for an unreachable instance, because a form showing a typo
|
||||
* needs a field to render, not an exception.
|
||||
*/
|
||||
const testConnection = useCallback(async (providerId: string, baseUrl: string, credentials: Record<string, string>, allowInsecureTls: boolean) => {
|
||||
setBusy('test')
|
||||
try {
|
||||
return await docsyncApi.testConnection(tripId, { providerId, baseUrl, credentials, allowInsecureTls }) as {
|
||||
connected: boolean; account?: string; error?: string; detail?: string
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
return { connected: false, error: readError(e) }
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}, [tripId])
|
||||
|
||||
/**
|
||||
* The containers a connection can be bound to.
|
||||
*
|
||||
* Always resolves to a listing, the way `testConnection` always resolves to
|
||||
* a verdict: the route answers 200 with an error code when the store refuses,
|
||||
* and a request that fell over on the way (a store behind a VPN that is not
|
||||
* up, a connection an admin deleted meanwhile) has to reach the picker the
|
||||
* same way. Left to reject, it never reached `setScopes`, and the picker
|
||||
* spun forever with nothing said.
|
||||
*/
|
||||
const loadScopes = useCallback(async (connectionId: number, q?: string) => {
|
||||
try {
|
||||
return await docsyncApi.listScopes(tripId, connectionId, q) as { scopes: DocSyncScope[]; error?: string }
|
||||
} catch (e: unknown) {
|
||||
return { scopes: [] as DocSyncScope[], error: readError(e) }
|
||||
}
|
||||
}, [tripId])
|
||||
|
||||
/**
|
||||
* Make a container at the provider.
|
||||
*
|
||||
* Reports failure the same way every other write here does. A rejected
|
||||
* create used to escape as an unhandled rejection, so the button blinked and
|
||||
* nothing happened and nothing was said. Null rather than a throw, because
|
||||
* the caller's next step is to bind what came back, and there is nothing to
|
||||
* bind.
|
||||
*/
|
||||
const createScope = useCallback(async (connectionId: number, name: string): Promise<DocSyncScope | null> => {
|
||||
setBusy('scope')
|
||||
setError(null)
|
||||
try {
|
||||
return await docsyncApi.createScope(tripId, connectionId, name) as DocSyncScope
|
||||
} catch (e: unknown) {
|
||||
setError(readError(e))
|
||||
return null
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}, [tripId])
|
||||
|
||||
const createLink = useCallback(async (payload: Record<string, unknown>) => {
|
||||
setBusy('link')
|
||||
setError(null)
|
||||
try {
|
||||
await docsyncApi.createLink(tripId, payload)
|
||||
await load()
|
||||
return true
|
||||
} catch (e: unknown) {
|
||||
setError(readError(e))
|
||||
return false
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}, [tripId, load])
|
||||
|
||||
/**
|
||||
* Change one binding, optimistically.
|
||||
*
|
||||
* The reload in `finally` puts the server's answer back either way, so a
|
||||
* refused change corrects itself on screen, but it used to do that in
|
||||
* silence, with the rejection escaping into a `void` call site. The switch
|
||||
* simply flipped back and nobody said why.
|
||||
*/
|
||||
const updateLink = useCallback(async (linkId: number, patch: Record<string, unknown>) => {
|
||||
setLinks(prev => prev.map(l => (l.id === linkId ? { ...l, ...patch } as DocSyncLink : l)))
|
||||
setError(null)
|
||||
try {
|
||||
await docsyncApi.updateLink(tripId, linkId, patch)
|
||||
await load()
|
||||
return true
|
||||
} catch (e: unknown) {
|
||||
// Reload first, so the optimistic value is corrected, then say why.
|
||||
// The other way round the reload cleared the message again.
|
||||
await load()
|
||||
setError(readError(e))
|
||||
return false
|
||||
}
|
||||
}, [tripId, load])
|
||||
|
||||
const removeLink = useCallback(async (linkId: number) => {
|
||||
setBusy('link')
|
||||
setError(null)
|
||||
try {
|
||||
await docsyncApi.deleteLink(tripId, linkId)
|
||||
await load()
|
||||
return true
|
||||
} catch (e: unknown) {
|
||||
setError(readError(e))
|
||||
return false
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}, [tripId, load])
|
||||
|
||||
const syncNow = useCallback(async (linkId: number, full = false) => {
|
||||
setBusy(`sync-${linkId}`)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await docsyncApi.syncNow(tripId, linkId, full) as {
|
||||
state: string; pulled: number; pushed: number; conflicts: number; missing: number
|
||||
}
|
||||
await load()
|
||||
return res
|
||||
} catch (e: unknown) {
|
||||
// A refused run is a thing the person asked for and did not get (an
|
||||
// orphaned binding answers 409 here), so it has to be said out loud
|
||||
// rather than escaping into the `void` at the call site. After the
|
||||
// reload, which would otherwise clear the message.
|
||||
await load()
|
||||
setError(readError(e))
|
||||
return null
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}, [tripId, load])
|
||||
|
||||
/**
|
||||
* Settle one conflict.
|
||||
*
|
||||
* Reports failure the way the other writes do. The rejection used to escape
|
||||
* into the `void` at the call site, so a refused choice (the row was settled
|
||||
* elsewhere a moment ago, or the server answered 403) put the button back
|
||||
* and left the row standing with nothing said.
|
||||
*/
|
||||
const resolveConflict = useCallback(async (itemId: number, keep: 'trek' | 'provider' | 'both') => {
|
||||
setError(null)
|
||||
try {
|
||||
await docsyncApi.resolve(tripId, itemId, keep)
|
||||
await load()
|
||||
return true
|
||||
} catch (e: unknown) {
|
||||
// Reload first, so the counts match what the server has, then say why.
|
||||
// The other way round the reload cleared the message again.
|
||||
await load()
|
||||
setError(readError(e))
|
||||
return false
|
||||
}
|
||||
}, [tripId, load])
|
||||
|
||||
/** Providers the admin switched on that also have a working adapter. */
|
||||
const usableProviders = useMemo(() => providers.filter(p => p.available), [providers])
|
||||
|
||||
return {
|
||||
providers: usableProviders,
|
||||
connections, links, itemCounts,
|
||||
loading, busy, error,
|
||||
connectionFor, load,
|
||||
saveConnection, testConnection,
|
||||
loadScopes, createScope,
|
||||
createLink, updateLink, removeLink, syncNow, resolveConflict,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The error code a failed call carries, or `unknown`.
|
||||
*
|
||||
* Both shells render this as `docsync.error.<code>`, so anything that is not
|
||||
* one of the codes reaches the screen as a raw translation key, and the server
|
||||
* answers plenty of routes with a sentence ("Link not found") rather than a
|
||||
* code. A general message is worse than a specific one and far better than
|
||||
* `docsync.error.Link not found`.
|
||||
*/
|
||||
function readError(e: unknown): string {
|
||||
const res = (e as { response?: { data?: { error?: string; message?: string } } })?.response
|
||||
const raw = res?.data?.error || res?.data?.message || ''
|
||||
// A code passes through: the sync codes and the handful of keys the routes
|
||||
// answer with are all of this shape. A sentence does not: several routes
|
||||
// answer with prose ("Link not found"), and both shells render this as
|
||||
// `docsync.error.<value>`, so that reached the screen as a raw translation
|
||||
// key. A general message is worse than a specific one and far better than
|
||||
// `docsync.error.Link not found`.
|
||||
return /^[a-z0-9_.]+$/i.test(raw) ? raw : 'unknown'
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// FE-DOCSYNC-OFFER-001 to FE-DOCSYNC-OFFER-013
|
||||
|
||||
/**
|
||||
* Whether the Files screen offers document sync.
|
||||
*
|
||||
* The providers ship switched off, so the rule is what keeps an upgraded
|
||||
* instance from growing a button into an empty dialog on every trip: a bound
|
||||
* trip shows it to everybody, an unbound one only to somebody who could bind
|
||||
* it, and only once the admin has switched a provider on.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { act, renderHook, waitFor } from '../../../../tests/helpers/render'
|
||||
import { server } from '../../../../tests/helpers/msw/server'
|
||||
import { useDocSyncOfferStore } from '../../../store/docSyncOfferStore'
|
||||
import { setForcedOffline } from '../../../sync/networkMode'
|
||||
import { useDocSyncOffered } from './useDocSyncOffered'
|
||||
|
||||
const listeners = new Set<(e: Record<string, unknown>) => void>()
|
||||
|
||||
vi.mock('../../../api/websocket', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../api/websocket')>()),
|
||||
addListener: (fn: (e: Record<string, unknown>) => void) => { listeners.add(fn) },
|
||||
removeListener: (fn: (e: Record<string, unknown>) => void) => { listeners.delete(fn) },
|
||||
}))
|
||||
|
||||
/** Deliver an event the way the websocket layer would. */
|
||||
function emit(type: string): void {
|
||||
for (const fn of [...listeners]) fn({ type })
|
||||
}
|
||||
|
||||
const TRIP = 4
|
||||
|
||||
let providerCalls = 0
|
||||
let linkCalls = 0
|
||||
|
||||
function routes({ providers = [] as unknown[], links = [] as unknown[], linksStatus = 200 } = {}) {
|
||||
server.use(
|
||||
http.get('/api/trips/:tripId/docsync/providers', () => {
|
||||
providerCalls += 1
|
||||
return HttpResponse.json(providers)
|
||||
}),
|
||||
http.get('/api/trips/:tripId/docsync/links', () => {
|
||||
linkCalls += 1
|
||||
return linksStatus === 200
|
||||
? HttpResponse.json(links)
|
||||
: HttpResponse.json({ error: 'nope' }, { status: linksStatus })
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const paperless = { id: 'paperless', name: 'Paperless-ngx', available: true }
|
||||
const binding = { id: 1, providerId: 'paperless' }
|
||||
|
||||
beforeEach(() => {
|
||||
providerCalls = 0
|
||||
linkCalls = 0
|
||||
listeners.clear()
|
||||
useDocSyncOfferStore.setState({ bound: {}, providers: null })
|
||||
})
|
||||
|
||||
afterEach(() => setForcedOffline(false))
|
||||
|
||||
describe('useDocSyncOffered', () => {
|
||||
it('FE-DOCSYNC-OFFER-001: somebody who may bind the trip sees it once a provider is on, without asking about bindings', async () => {
|
||||
routes({ providers: [paperless] })
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, true))
|
||||
|
||||
await waitFor(() => expect(result.current).toBe(true))
|
||||
expect(providerCalls).toBe(1)
|
||||
expect(linkCalls).toBe(0)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-002: with every provider off and nothing bound, nobody sees it', async () => {
|
||||
routes({ providers: [] })
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, true))
|
||||
|
||||
await waitFor(() => expect(linkCalls).toBe(1))
|
||||
expect(result.current).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-003: a provider row without an adapter does not count as offered', async () => {
|
||||
routes({ providers: [{ ...paperless, available: false }] })
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, true))
|
||||
|
||||
await waitFor(() => expect(linkCalls).toBe(1))
|
||||
expect(result.current).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-004: a member sees a bound trip, and is never asked about providers', async () => {
|
||||
routes({ providers: [paperless], links: [binding] })
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, false))
|
||||
|
||||
await waitFor(() => expect(result.current).toBe(true))
|
||||
expect(providerCalls).toBe(0)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-005: a member does not see an unbound trip, providers or not', async () => {
|
||||
routes({ providers: [paperless], links: [] })
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, false))
|
||||
|
||||
await waitFor(() => expect(linkCalls).toBe(1))
|
||||
expect(result.current).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-006: a bound trip keeps the button after the admin switched every provider off', async () => {
|
||||
routes({ providers: [], links: [binding] })
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, true))
|
||||
|
||||
await waitFor(() => expect(result.current).toBe(true))
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-007: the last answer renders at once on the next visit, then is checked again', async () => {
|
||||
routes({ links: [binding] })
|
||||
const first = renderHook(() => useDocSyncOffered(TRIP, false))
|
||||
await waitFor(() => expect(first.result.current).toBe(true))
|
||||
first.unmount()
|
||||
|
||||
const second = renderHook(() => useDocSyncOffered(TRIP, false))
|
||||
expect(second.result.current).toBe(true)
|
||||
await waitFor(() => expect(linkCalls).toBe(2))
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-008: offline it asks nothing and keeps what it knew, and asks again once back', async () => {
|
||||
routes({ links: [] })
|
||||
useDocSyncOfferStore.setState({ bound: { [TRIP]: true } })
|
||||
act(() => setForcedOffline(true))
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, false))
|
||||
|
||||
expect(result.current).toBe(true)
|
||||
expect(linkCalls).toBe(0)
|
||||
|
||||
act(() => setForcedOffline(false))
|
||||
await waitFor(() => expect(result.current).toBe(false))
|
||||
expect(linkCalls).toBe(1)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-009: a request that never got an answer leaves the last one standing', async () => {
|
||||
server.use(http.get('/api/trips/:tripId/docsync/links', () => HttpResponse.error()))
|
||||
useDocSyncOfferStore.setState({ bound: { [TRIP]: true } })
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, false))
|
||||
|
||||
await act(() => useDocSyncOfferStore.getState().refresh(TRIP, false))
|
||||
expect(result.current).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-010: the Documents addon switched off is a real no', async () => {
|
||||
routes({ linksStatus: 403 })
|
||||
useDocSyncOfferStore.setState({ bound: { [TRIP]: true } })
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, false))
|
||||
|
||||
await waitFor(() => expect(result.current).toBe(false))
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-011: a refresh asked for while offline sends nothing and changes nothing', async () => {
|
||||
routes({ providers: [paperless] })
|
||||
useDocSyncOfferStore.setState({ providers: false })
|
||||
setForcedOffline(true)
|
||||
|
||||
await useDocSyncOfferStore.getState().refresh(TRIP, true)
|
||||
|
||||
expect(providerCalls).toBe(0)
|
||||
expect(useDocSyncOfferStore.getState().providers).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-012: a member on the Files tab gets the button when the owner binds the trip', async () => {
|
||||
routes({ links: [] })
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, false))
|
||||
await waitFor(() => expect(linkCalls).toBe(1))
|
||||
expect(result.current).toBe(false)
|
||||
|
||||
// The owner binds it: nothing remounts here, the server only pings.
|
||||
routes({ links: [binding] })
|
||||
act(() => emit('docsync:changed'))
|
||||
|
||||
await waitFor(() => expect(result.current).toBe(true))
|
||||
expect(linkCalls).toBe(2)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-OFFER-013: the button goes when the last binding does, with every provider off', async () => {
|
||||
routes({ providers: [], links: [binding] })
|
||||
const { result } = renderHook(() => useDocSyncOffered(TRIP, true))
|
||||
await waitFor(() => expect(result.current).toBe(true))
|
||||
|
||||
routes({ providers: [], links: [] })
|
||||
act(() => emit('docsync:changed'))
|
||||
|
||||
await waitFor(() => expect(result.current).toBe(false))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useNetworkMode } from '../../../hooks/useNetworkMode'
|
||||
import { useDocSyncOfferStore } from '../../../store/docSyncOfferStore'
|
||||
import { useServerPing } from '../../../sync/useServerPing'
|
||||
|
||||
/**
|
||||
* Whether this trip's Files screen shows the "Document sync" button.
|
||||
*
|
||||
* One hook for both shells, so the toolbar and the phone header cannot drift
|
||||
* on who sees it. The last known answer renders straight away; the server is
|
||||
* asked again when the screen mounts and when the connection comes back, and
|
||||
* never while offline, where the button keeps whatever it last knew.
|
||||
*
|
||||
* It is also asked on every `docsync:changed`, which the server sends when a
|
||||
* binding comes or goes. A member can sit on the Files tab while the owner
|
||||
* binds the trip, and on desktop that tab may never remount before a reload.
|
||||
*/
|
||||
export function useDocSyncOffered(tripId: number | string, canManage: boolean): boolean {
|
||||
const offered = useDocSyncOfferStore(
|
||||
s => s.bound[String(tripId)] === true || (canManage && s.providers === true),
|
||||
)
|
||||
const refresh = useDocSyncOfferStore(s => s.refresh)
|
||||
const { offline } = useNetworkMode()
|
||||
|
||||
useEffect(() => {
|
||||
if (!offline) void refresh(tripId, canManage)
|
||||
}, [tripId, canManage, offline, refresh])
|
||||
|
||||
// Off while offline: the effect above already asks on the way back, and the
|
||||
// ping's own return-to-online refetch would only ask a second time.
|
||||
useServerPing('docsync:changed', !offline, () => refresh(tripId, canManage))
|
||||
|
||||
return offered
|
||||
}
|
||||
@@ -6,6 +6,9 @@ import { filesApi } from '../../api/client'
|
||||
import type { Place, Reservation, TripFile, Day, AssignmentsMap } from '../../types'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { canManageDocSync } from './docsync/useDocSync'
|
||||
import { useDocSyncOffered } from './docsync/useDocSyncOffered'
|
||||
import { getAuthUrl } from '../../api/authUrl'
|
||||
import { isImage, isMedia, isWalletPass } from './FileManager.helpers'
|
||||
import { openFile as openFileInTab } from '../../utils/fileDownload'
|
||||
@@ -30,6 +33,7 @@ export interface FileManagerProps {
|
||||
*/
|
||||
export function useFileManager({ files = [], onUpload, onDelete, onUpdate, places, days = [], assignments = {}, reservations = [], tripId, allowedFileTypes }: FileManagerProps) {
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [showDocSync, setShowDocSync] = useState(false)
|
||||
const [filterType, setFilterType] = useState('all')
|
||||
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null)
|
||||
const [showTrash, setShowTrash] = useState(false)
|
||||
@@ -38,6 +42,9 @@ export function useFileManager({ files = [], onUpload, onDelete, onUpdate, place
|
||||
const toast = useToast()
|
||||
const can = useCanDo()
|
||||
const trip = useTripStore((s) => s.trip)
|
||||
const currentUser = useAuthStore((s) => s.user)
|
||||
const canManageSync = canManageDocSync(currentUser, trip)
|
||||
const docSyncOffered = useDocSyncOffered(tripId, canManageSync)
|
||||
const { t, locale } = useTranslation()
|
||||
|
||||
const loadTrash = useCallback(async () => {
|
||||
@@ -210,6 +217,7 @@ export function useFileManager({ files = [], onUpload, onDelete, onUpdate, place
|
||||
previewFile, setPreviewFile, previewFileUrl, assignFileId, setAssignFileId,
|
||||
getRootProps, getInputProps, isDragActive, handlePaste, filteredFiles, handleDelete,
|
||||
handleAssign, mediaFiles, openFile,
|
||||
showDocSync, setShowDocSync, canManageSync, docSyncOffered,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// FE-JRN-DAYDAW-001 to FE-JRN-DAYDAW-008
|
||||
/**
|
||||
* The fold a journal day carries for the stays Dawarich recorded on it.
|
||||
*
|
||||
* The rows inside it are `SuggestionRow`, which the panel's own suite pins end to end, so
|
||||
* what is worth holding here is the fold: that it says nothing on a quiet day, that the
|
||||
* line reads before it is opened, and that the two actions reach the journal with the
|
||||
* stay they belong to. The whole point of this component is that forty stays no longer
|
||||
* stand between a reader and their first entry, and that only works while it starts shut.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, within } from '../../../tests/helpers/render'
|
||||
import { fireEvent } from '@testing-library/react'
|
||||
import type { DawarichSuggestion } from '@trek/shared'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import JourneyDayDawarich from './JourneyDayDawarich'
|
||||
|
||||
function stay(over: Partial<DawarichSuggestion> & { id: number }): DawarichSuggestion {
|
||||
const date = over.localDate ?? '2026-09-10'
|
||||
return {
|
||||
id: over.id,
|
||||
sourceVisitId: String(over.id),
|
||||
tripId: null,
|
||||
tripTitle: null,
|
||||
name: over.name ?? 'Cafe Reichard',
|
||||
lat: 50.94,
|
||||
lng: 6.96,
|
||||
startedAt: over.startedAt ?? `${date}T10:15:00+02:00`,
|
||||
endedAt: over.endedAt ?? `${date}T12:40:00+02:00`,
|
||||
durationMinutes: over.durationMinutes ?? 145,
|
||||
localDate: date,
|
||||
sourceStatus: 'suggested',
|
||||
confidence: null,
|
||||
confidenceBand: null,
|
||||
state: 'new',
|
||||
target: null,
|
||||
acceptedPlaceId: null,
|
||||
acceptedJournalEntryId: null,
|
||||
acceptedBucketListItemId: null,
|
||||
sourceChanged: false,
|
||||
sourceMissing: false,
|
||||
matchedBucketListItemId: null,
|
||||
matchedBucketListName: null,
|
||||
countryCode: null,
|
||||
firstSeenAt: `${date}T06:00:00Z`,
|
||||
lastSeenAt: `${date}T06:00:00Z`,
|
||||
...over,
|
||||
} as DawarichSuggestion
|
||||
}
|
||||
|
||||
function fold(suggestions: DawarichSuggestion[], over: Partial<{ busyId: number | null }> = {}) {
|
||||
const onAccept = vi.fn()
|
||||
const onDismiss = vi.fn()
|
||||
const view = render(
|
||||
<JourneyDayDawarich
|
||||
suggestions={suggestions}
|
||||
busyId={over.busyId ?? null}
|
||||
onAccept={onAccept}
|
||||
onDismiss={onDismiss}
|
||||
/>,
|
||||
)
|
||||
return { onAccept, onDismiss, ...view }
|
||||
}
|
||||
|
||||
const head = () => screen.getByRole('button', { expanded: false }) ?? screen.getByRole('button')
|
||||
|
||||
describe('JourneyDayDawarich', () => {
|
||||
it('FE-JRN-DAYDAW-001: a day with nothing pending draws nothing at all', () => {
|
||||
// Not an empty row saying so: a connected, quiet integration is invisible, and this
|
||||
// one would otherwise appear on every single day of the journey.
|
||||
const { container } = fold([])
|
||||
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('FE-JRN-DAYDAW-002: shut, it says how many and which part of the day they cover', () => {
|
||||
fold([
|
||||
stay({ id: 1, startedAt: '2026-09-10T08:00:00+02:00', endedAt: '2026-09-10T09:30:00+02:00' }),
|
||||
stay({ id: 2, startedAt: '2026-09-10T14:00:00+02:00', endedAt: '2026-09-10T17:08:00+02:00' }),
|
||||
])
|
||||
|
||||
expect(screen.getByText('2 stays from Dawarich')).toBeInTheDocument()
|
||||
// First arrival to last departure, not each stay's own range.
|
||||
expect(screen.getByText('08:00 – 17:08')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-JRN-DAYDAW-003: one stay takes the singular', () => {
|
||||
// A single key with a placeholder would read "1 stays".
|
||||
fold([stay({ id: 1 })])
|
||||
|
||||
expect(screen.getByText('1 stay from Dawarich')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-JRN-DAYDAW-004: it starts shut, and the stays are not in the page until it opens', () => {
|
||||
fold([stay({ id: 1, name: 'Cafe Reichard' })])
|
||||
|
||||
expect(screen.queryByText('Cafe Reichard')).toBeNull()
|
||||
expect(head()).toHaveAttribute('aria-expanded', 'false')
|
||||
|
||||
fireEvent.click(head())
|
||||
|
||||
expect(screen.getByText('Cafe Reichard')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-JRN-DAYDAW-005: open, each stay is a row with its own two actions', () => {
|
||||
const { onDismiss } = fold([stay({ id: 7, name: 'Cafe Reichard' })])
|
||||
fireEvent.click(head())
|
||||
|
||||
const row = screen.getByText('Cafe Reichard').closest('div')!.parentElement!
|
||||
fireEvent.click(within(row).getByRole('button', { name: 'Not a place I visited' }))
|
||||
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1)
|
||||
expect(onDismiss.mock.calls[0][0]).toMatchObject({ id: 7 })
|
||||
})
|
||||
|
||||
it('FE-JRN-DAYDAW-006: accepting hands back the stay it was asked about and where it goes', () => {
|
||||
const { onAccept } = fold([stay({ id: 7, name: 'Cafe Reichard' })])
|
||||
fireEvent.click(head())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /journal|journey/i }))
|
||||
|
||||
expect(onAccept).toHaveBeenCalledTimes(1)
|
||||
expect(onAccept.mock.calls[0][0]).toMatchObject({ id: 7 })
|
||||
expect(onAccept.mock.calls[0][1]).toBe('journal')
|
||||
})
|
||||
|
||||
it('FE-JRN-DAYDAW-007: the stay a write is in flight for is the one that goes busy', () => {
|
||||
fold([stay({ id: 7, name: 'Cafe Reichard' }), stay({ id: 8, name: 'Zum Treppchen' })], { busyId: 7 })
|
||||
fireEvent.click(head())
|
||||
|
||||
const busyRow = screen.getByText('Cafe Reichard').closest('div')!.parentElement!
|
||||
const idleRow = screen.getByText('Zum Treppchen').closest('div')!.parentElement!
|
||||
expect(within(busyRow).getAllByRole('button')[0]).toBeDisabled()
|
||||
expect(within(idleRow).getAllByRole('button')[0]).not.toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-JRN-DAYDAW-008: the span follows the traveller own clock', () => {
|
||||
useSettingsStore.setState(s => ({ settings: { ...s.settings, time_format: '12h' } }))
|
||||
fold([
|
||||
stay({ id: 1, startedAt: '2026-09-10T08:00:00+02:00', endedAt: '2026-09-10T09:30:00+02:00' }),
|
||||
stay({ id: 2, startedAt: '2026-09-10T14:00:00+02:00', endedAt: '2026-09-10T17:08:00+02:00' }),
|
||||
])
|
||||
|
||||
expect(screen.getByText('8:00 AM – 5:08 PM')).toBeInTheDocument()
|
||||
useSettingsStore.setState(s => ({ settings: { ...s.settings, time_format: '24h' } }))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import React, { useState } from 'react'
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react'
|
||||
import type { DawarichSuggestion, DawarichSuggestionTarget } from '@trek/shared'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import { SuggestionRow } from '../Dawarich/DawarichSuggestionsPanel'
|
||||
import { timeRange } from '../Dawarich/dawarichSuggestionModel'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
|
||||
/**
|
||||
* The stays Dawarich recorded on ONE day of the journal, folded into that day.
|
||||
*
|
||||
* They used to be a panel above the timeline: every open stay of every day, stacked over
|
||||
* the entries, so a fortnight of driving put forty rows between the reader and their own
|
||||
* first entry. The list belongs where the day is (discussion with Roel, 16.09.), and a
|
||||
* day of driving still produces four to eleven stays, so the day shows one line with a
|
||||
* count and opens on a tap.
|
||||
*
|
||||
* Shut, it reads as one more card in the day: the mark says where it came from without a
|
||||
* word of explanation, and the times say which part of the day it covers. Open, it is the
|
||||
* same rows the panel drew, which is why `SuggestionRow` is imported rather than copied.
|
||||
*
|
||||
* It never appears on a day with nothing pending: an integration that is connected and
|
||||
* quiet should be invisible, not a permanent empty row on every day of the journey.
|
||||
*/
|
||||
export default function JourneyDayDawarich({
|
||||
suggestions,
|
||||
busyId,
|
||||
onAccept,
|
||||
onDismiss,
|
||||
}: {
|
||||
/** The open stays of this day, in the order they were lived. */
|
||||
suggestions: DawarichSuggestion[]
|
||||
/** The stay a write is in flight for, or null. */
|
||||
busyId: number | null
|
||||
onAccept: (suggestion: DawarichSuggestion, target: DawarichSuggestionTarget) => void
|
||||
onDismiss: (suggestion: DawarichSuggestion) => void
|
||||
}): React.ReactElement | null {
|
||||
const { t } = useTranslation()
|
||||
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
if (suggestions.length === 0) return null
|
||||
|
||||
// From the first arrival to the last departure: what part of the day this covers, in
|
||||
// one line, so the row says something even while it is shut. Through the same formatter
|
||||
// the rows use, so the summary and the stays under it cannot disagree about the clock.
|
||||
const span = timeRange(suggestions[0]!.startedAt, suggestions[suggestions.length - 1]!.endedAt, is12h)
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-edge bg-surface-secondary overflow-hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(v => !v)}
|
||||
aria-expanded={open}
|
||||
className="flex w-full items-center gap-2.5 px-3 py-2.5 text-left transition-colors hover:bg-surface-hover"
|
||||
>
|
||||
{/* The brand mark in its own colours, which is what tells this row from an entry
|
||||
at a glance. No second label saying "Dawarich": the mark is the label. */}
|
||||
<DawarichIcon size={18} className="shrink-0" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[13px] font-semibold text-content">
|
||||
{/* Two keys picked by the count, the shape this codebase uses for a number
|
||||
that changes its noun: there is no plural engine in the i18n layer, and one
|
||||
key with {count} in it reads as "1 stays". */}
|
||||
{t(
|
||||
suggestions.length === 1 ? 'dawarich.journey.dayStays.one' : 'dawarich.journey.dayStays.other',
|
||||
{ count: suggestions.length },
|
||||
)}
|
||||
</span>
|
||||
{span && <span className="block text-[11px] text-content-faint tabular-nums">{span}</span>}
|
||||
</span>
|
||||
{open
|
||||
? <ChevronDown size={16} className="shrink-0 text-content-faint" aria-hidden />
|
||||
: <ChevronRight size={16} className="shrink-0 text-content-faint" aria-hidden />}
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="flex flex-col gap-1 pb-2">
|
||||
{suggestions.map(suggestion => (
|
||||
<SuggestionRow
|
||||
key={suggestion.id}
|
||||
suggestion={suggestion}
|
||||
busy={busyId === suggestion.id}
|
||||
// The journal is the one place a stay goes from here, and every row in this
|
||||
// list is already on the day it belongs to, so neither the date nor a trip
|
||||
// name adds anything.
|
||||
allowJournal
|
||||
onAccept={target => onAccept(suggestion, target)}
|
||||
onDismiss={() => onDismiss(suggestion)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-JRN-EDITOR-001 to FE-JRN-EDITOR-040
|
||||
// FE-JRN-EDITOR-001 to FE-JRN-EDITOR-059
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { http, HttpResponse, delay } from 'msw'
|
||||
@@ -1028,4 +1028,47 @@ describe('EntryEditor', () => {
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
confirmSpy.mockRestore()
|
||||
})
|
||||
it('FE-JRN-EDITOR-056: a clip without a poster is a play badge, not a request for its thumbnail (#2341)', () => {
|
||||
// The thumbnail route answers 404 for such a clip on purpose, and the old
|
||||
// fallback to /original would have handed an <img> the video file itself.
|
||||
const clip = { ...buildPhoto(100), media_type: 'video', provider: 'local', thumbnail_path: null }
|
||||
const { container } = mountEditor(buildEntry({ id: 10, photos: [clip] }))
|
||||
|
||||
expect(container.querySelector('img[src="/api/photos/100/thumbnail"]')).not.toBeInTheDocument()
|
||||
expect(container.querySelector('svg.lucide-play')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-JRN-EDITOR-057: a clip with its poster shows the poster like any photo', () => {
|
||||
const clip = { ...buildPhoto(100), media_type: 'video', provider: 'local', thumbnail_path: 'journey/poster.jpg' }
|
||||
const { container } = mountEditor(buildEntry({ id: 10, photos: [clip] }))
|
||||
|
||||
expect(container.querySelector('img[src="/api/photos/100/thumbnail"]')).toBeInTheDocument()
|
||||
expect(container.querySelector('svg.lucide-play')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-JRN-EDITOR-058: the gallery picker gives a clip without a poster the same play badge (#2341)', async () => {
|
||||
const user = userEvent.setup()
|
||||
const clip = { ...buildGalleryPhoto(200), media_type: 'video', provider: 'local', thumbnail_path: null }
|
||||
const { container } = mountEditor(buildEntry(), { galleryPhotos: [clip] })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'From Gallery' }))
|
||||
|
||||
expect(container.querySelector('img[src="/api/photos/200/thumbnail"]')).not.toBeInTheDocument()
|
||||
expect(container.querySelector('svg.lucide-play')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-JRN-EDITOR-059: a clip whose poster fails to load is not retried as the clip itself', async () => {
|
||||
// The /original of a video is the video file, which an <img> cannot draw.
|
||||
const user = userEvent.setup()
|
||||
const strip = { ...buildPhoto(100), media_type: 'video', provider: 'local', thumbnail_path: 'journey/a.jpg' }
|
||||
const picker = { ...buildGalleryPhoto(200), media_type: 'video', provider: 'local', thumbnail_path: 'journey/b.jpg' }
|
||||
const { container } = mountEditor(buildEntry({ id: 10, photos: [strip] }), { galleryPhotos: [picker] })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'From Gallery' }))
|
||||
for (const id of [100, 200]) {
|
||||
const img = container.querySelector(`img[src="/api/photos/${id}/thumbnail"]`) as HTMLImageElement
|
||||
fireEvent.error(img)
|
||||
expect(img.getAttribute('src')).toBe(`/api/photos/${id}/thumbnail`)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useMemo, useState, useRef } from 'react'
|
||||
import { useEffect, useMemo, useState, useRef, type SyntheticEvent } from 'react'
|
||||
import { localIsoDate } from '../../utils/localDate'
|
||||
import { X, Plus, Image, Minus, Check, MapPin, Locate, Camera } from 'lucide-react'
|
||||
import { X, Plus, Image, Minus, Check, MapPin, Locate, Camera, Play } from 'lucide-react'
|
||||
import { normalizeImageFiles } from '../../utils/convertHeic'
|
||||
import { isVideoFile } from '../../utils/videoPoster'
|
||||
import { type ResilientResult, type UploadProgress } from '../../utils/uploadQueue'
|
||||
@@ -11,7 +11,7 @@ import { getCurrentPositionOnce } from '../../hooks/useGeolocation'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import type { JourneyEntry, JourneyPhoto, GalleryPhoto, JourneyTrip } from '../../store/journeyStore'
|
||||
import { MOOD_CONFIG, WEATHER_CONFIG } from '../../pages/journeyDetail/JourneyDetailPage.constants'
|
||||
import { photoUrl, isValidGeoPoint, geoOnceErrorKey } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import { photoUrl, posterlessVideo, isValidGeoPoint, geoOnceErrorKey } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import MarkdownToolbar from './MarkdownToolbar'
|
||||
import { DatePicker } from './JourneyDetailPageDatePicker'
|
||||
import CustomTimePicker from '../shared/CustomTimePicker'
|
||||
@@ -21,6 +21,27 @@ import { journeyWeatherCategory } from '../../mobile/screens/journey/mobileJourn
|
||||
|
||||
type PendingProviderGroup = ProviderPhotoGroup & { provider: string }
|
||||
|
||||
// A photo whose thumbnail is missing can still be drawn from its original. A
|
||||
// clip's original is the video file, which no <img> can show, so a clip gets
|
||||
// no fallback (#2341).
|
||||
function thumbnailFallback(p: { photo_id: number; media_type?: string | null }) {
|
||||
if (p.media_type === 'video') return undefined
|
||||
return (e: SyntheticEvent<HTMLImageElement>) => {
|
||||
const img = e.currentTarget
|
||||
if (!img.src.includes('/original')) img.src = photoUrl(p, 'original')
|
||||
}
|
||||
}
|
||||
|
||||
// No poster to show and falling back to /original would hand an <img> the clip
|
||||
// itself, so this tile stays a play badge.
|
||||
function ClipTile() {
|
||||
return (
|
||||
<div className="absolute inset-0 bg-black flex items-center justify-center text-white">
|
||||
<Play size={18} className="ml-0.5" fill="currentColor" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips, userId = 0, showVerdict = true, showMood = true, showWeather = true, onClose, onSave, onUploadPhotos, onAddProviderPhotos, onDone }: {
|
||||
entry: JourneyEntry
|
||||
journeyId: number
|
||||
@@ -434,7 +455,11 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips,
|
||||
className="relative block w-full rounded-xl overflow-hidden border-0 p-0 bg-transparent cursor-pointer hover:ring-2 hover:ring-zinc-900 dark:hover:ring-white hover:ring-offset-1 dark:hover:ring-offset-zinc-900 transition-all"
|
||||
style={{ paddingTop: '100%' }}
|
||||
>
|
||||
<img src={photoUrl(gp)} alt="" className="absolute inset-0 w-full h-full object-cover" loading="lazy" onError={e => { const img = e.currentTarget; const orig = photoUrl(gp, 'original'); if (!img.src.includes('/original')) img.src = orig }} />
|
||||
{posterlessVideo(gp) ? (
|
||||
<ClipTile />
|
||||
) : (
|
||||
<img src={photoUrl(gp)} alt="" className="absolute inset-0 w-full h-full object-cover" loading="lazy" onError={thumbnailFallback(gp)} />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
{availableGalleryPhotos.length === 0 && (
|
||||
@@ -527,7 +552,11 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips,
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{photos.map((p, idx) => (
|
||||
<div key={p.id} className={`w-20 h-20 rounded-xl overflow-hidden relative group ${idx === 0 && photos.length > 1 ? 'ring-2 ring-zinc-900 dark:ring-white ring-offset-1 dark:ring-offset-zinc-900' : ''}`}>
|
||||
<img src={photoUrl(p)} className="w-full h-full object-cover" alt="" onError={e => { const img = e.currentTarget; const orig = photoUrl(p, 'original'); if (!img.src.includes('/original')) img.src = orig }} />
|
||||
{posterlessVideo(p) ? (
|
||||
<ClipTile />
|
||||
) : (
|
||||
<img src={photoUrl(p)} className="w-full h-full object-cover" alt="" onError={thumbnailFallback(p)} />
|
||||
)}
|
||||
{idx === 0 && photos.length > 1 && (
|
||||
<span className="absolute bottom-0.5 left-0.5 px-1 py-px rounded text-[8px] font-bold bg-zinc-900/70 text-white">{t('journey.editor.photoFirst')}</span>
|
||||
)}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { journeyApi, addonsApi, memoriesApi } from '../../api/client'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import type { JourneyEntry, GalleryPhoto, JourneyTrip } from '../../store/journeyStore'
|
||||
import { photoUrl } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import { photoUrl, posterlessVideo } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import { ProviderPicker } from './JourneyDetailPageProviderPicker'
|
||||
import { ScrollTrigger } from './JourneyDetailPageScrollTrigger'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
@@ -151,9 +151,7 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhot
|
||||
onClick={() => onPhotoClick(allPhotos, i)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onPhotoClick(allPhotos, i) } }}
|
||||
>
|
||||
{photo.media_type === 'video' &&
|
||||
photo.provider === 'local' &&
|
||||
!photo.thumbnail_path ? (
|
||||
{posterlessVideo(photo) ? (
|
||||
// Poster-less local video: show a neutral tile.
|
||||
<div className="w-full h-full bg-zinc-200 dark:bg-zinc-800" />
|
||||
) : (
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render } from '../../../tests/helpers/render'
|
||||
import { PhotoImg } from './JourneyDetailPagePhotoGrid'
|
||||
import type { JourneyPhoto } from '../../store/journeyStore'
|
||||
|
||||
function buildPhoto(overrides: Partial<JourneyPhoto> = {}): JourneyPhoto {
|
||||
return {
|
||||
id: 1,
|
||||
entry_id: 10,
|
||||
photo_id: 515,
|
||||
sort_order: 0,
|
||||
shared: 1,
|
||||
created_at: 0,
|
||||
provider: 'local',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('PhotoImg', () => {
|
||||
it('asks for the thumbnail of a photo', () => {
|
||||
const { container } = render(<PhotoImg photo={buildPhoto()} />)
|
||||
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', '/api/photos/515/thumbnail')
|
||||
})
|
||||
|
||||
it('shows the poster of a clip behind the play badge', () => {
|
||||
const { container } = render(<PhotoImg photo={buildPhoto({ media_type: 'video', thumbnail_path: 'journey/poster.jpg' })} />)
|
||||
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', '/api/photos/515/thumbnail')
|
||||
expect(container.querySelector('svg')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('draws no image for a clip without a poster, whose thumbnail route answers 404 (#2341)', () => {
|
||||
// The tile stays black with the play badge on it. An <img> here would only
|
||||
// add the broken-image glyph the reporter saw.
|
||||
const { container } = render(<PhotoImg photo={buildPhoto({ media_type: 'video', thumbnail_path: null })} />)
|
||||
|
||||
expect(container.querySelector('img')).toBeNull()
|
||||
expect(container.querySelector('svg')).not.toBeNull()
|
||||
expect(container.firstElementChild?.className).toContain('bg-black')
|
||||
})
|
||||
|
||||
it('still asks the server for a provider clip, which serves its own poster', () => {
|
||||
const { container } = render(<PhotoImg photo={buildPhoto({ media_type: 'video', provider: 'immich', thumbnail_path: null })} />)
|
||||
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', '/api/photos/515/thumbnail')
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Image, Play } from 'lucide-react'
|
||||
import type { JourneyPhoto } from '../../store/journeyStore'
|
||||
import { photoUrl } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import { photoUrl, posterlessVideo } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
|
||||
export function PhotoImg({ photo, className, style }: { photo: JourneyPhoto; className?: string; style?: React.CSSProperties }) {
|
||||
const src = photoUrl(photo, 'thumbnail')
|
||||
@@ -11,12 +11,16 @@ export function PhotoImg({ photo, className, style }: { photo: JourneyPhoto; cla
|
||||
className={`relative overflow-hidden ${isVideo ? 'bg-black' : ''} ${className || ''}`}
|
||||
style={style}
|
||||
>
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className={`w-full h-full ${isVideo ? 'object-contain' : 'object-cover'}`}
|
||||
loading="lazy"
|
||||
/>
|
||||
{/* A clip without a poster keeps the black tile and the play badge; asking
|
||||
for its thumbnail would only draw the broken-image glyph over them. */}
|
||||
{!posterlessVideo(photo) && (
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className={`w-full h-full ${isVideo ? 'object-contain' : 'object-cover'}`}
|
||||
loading="lazy"
|
||||
/>
|
||||
)}
|
||||
|
||||
{isVideo && (
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// FE-JRN-PICKER-001 to FE-JRN-PICKER-021
|
||||
// FE-JRN-PICKER-001 to FE-JRN-PICKER-023
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { describe, it, expect, afterAll, beforeAll, beforeEach, vi } from 'vitest'
|
||||
import { http, HttpResponse, delay } from 'msw'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render'
|
||||
@@ -54,6 +54,16 @@ function mountPicker(props: Partial<React.ComponentProps<typeof ProviderPicker>>
|
||||
return { ...utils, onClose, onAdd }
|
||||
}
|
||||
|
||||
// The day headings follow the reader's wall clock now, so they would follow the
|
||||
// runner's zone too. Nothing in the vitest config pins one, so this file does.
|
||||
const runnerTimeZone = process.env.TZ
|
||||
|
||||
beforeAll(() => { process.env.TZ = 'UTC' })
|
||||
afterAll(() => {
|
||||
if (runnerTimeZone === undefined) delete process.env.TZ
|
||||
else process.env.TZ = runnerTimeZone
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
searchReturns([asset('a1')])
|
||||
})
|
||||
@@ -103,7 +113,9 @@ describe('ProviderPicker', () => {
|
||||
await user.click(screen.getByRole('button', { name: /All Photos/ }))
|
||||
|
||||
await waitFor(() => expect(ranges).toHaveLength(2))
|
||||
expect(ranges[1]).toEqual({ from: '', to: '', page: 1, size: 50 })
|
||||
// utc_offset_minutes rides along on every search: the server cannot tell
|
||||
// which 24 hours a date-only bound means without it (#2336).
|
||||
expect(ranges[1]).toEqual({ from: '', to: '', page: 1, size: 50, utc_offset_minutes: 0 })
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-006: the album tab loads albums and reports when there are none', async () => {
|
||||
@@ -286,6 +298,55 @@ describe('ProviderPicker', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-022: says which zone the searched day is meant in', async () => {
|
||||
const ranges: Record<string, unknown>[] = []
|
||||
server.use(http.post('/api/integrations/memories/immich/search', async ({ request }) => {
|
||||
ranges.push(await request.json() as Record<string, unknown>)
|
||||
return HttpResponse.json({ assets: [asset('a1')], hasMore: false })
|
||||
}))
|
||||
process.env.TZ = 'Australia/Sydney'
|
||||
try {
|
||||
mountPicker({ initialDate: '2026-03-15' })
|
||||
await waitFor(() => expect(ranges).toHaveLength(1))
|
||||
} finally {
|
||||
process.env.TZ = 'UTC'
|
||||
}
|
||||
|
||||
// +11 on 15 March, read at local noon of the day being searched rather than
|
||||
// at "now" — Sydney is +10 for half the year, so a day picked out of the
|
||||
// other half would otherwise be an hour off.
|
||||
expect(ranges[0]).toMatchObject({ from: '2026-03-15', to: '2026-03-15', utc_offset_minutes: 660 })
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-023: keeps paging when a page holds no photos of the searched day', async () => {
|
||||
// The local-day filter can empty a whole page (50 shots taken the next
|
||||
// morning). The sentinel used to live inside the grid, so an empty page
|
||||
// mounted none and the picker sat on "no photos" forever (#2336).
|
||||
const pages: number[] = []
|
||||
server.use(http.post('/api/integrations/memories/immich/search', async ({ request }) => {
|
||||
const body = await request.json() as { page: number }
|
||||
pages.push(body.page)
|
||||
return HttpResponse.json({ assets: body.page < 2 ? [] : [asset('a1')], hasMore: body.page < 2 })
|
||||
}))
|
||||
class ImmediateObserver {
|
||||
constructor(private cb: IntersectionObserverCallback) {}
|
||||
observe() { this.cb([{ isIntersecting: true } as IntersectionObserverEntry], this as unknown as IntersectionObserver) }
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
const original = globalThis.IntersectionObserver
|
||||
globalThis.IntersectionObserver = ImmediateObserver as unknown as typeof IntersectionObserver
|
||||
try {
|
||||
mountPicker()
|
||||
await waitFor(() => expect(pages).toEqual([1, 2]))
|
||||
expect(await screen.findAllByAltText('')).toHaveLength(1)
|
||||
// And the empty first page never claimed there were none to find.
|
||||
expect(screen.queryByText('No photos yet')).not.toBeInTheDocument()
|
||||
} finally {
|
||||
globalThis.IntersectionObserver = original
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-018: the embedded variant drops the header, the add-to bar and the date captions', async () => {
|
||||
mountPicker({ embedded: true, initialDate: '2026-03-15' })
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from '../../i18n';
|
||||
import {
|
||||
groupPhotosByDate,
|
||||
sortProviderPhotos,
|
||||
utcOffsetMinutesForDay,
|
||||
type GeoPoint,
|
||||
} from '../../pages/journeyDetail/JourneyDetailPage.helpers';
|
||||
import type { JourneyEntry, JourneyTrip } from '../../store/journeyStore';
|
||||
@@ -94,7 +95,17 @@ export function ProviderPicker({
|
||||
setSearchTo(to);
|
||||
setSearchPage(page);
|
||||
try {
|
||||
const data = await memoriesApi.search(provider, { from, to, page, size: 50 }, signal);
|
||||
// The bounds are calendar days as this browser reads them, so the zone they
|
||||
// are meant in travels with them. Without it the server can only take them
|
||||
// as UTC days and a reader outside UTC gets somebody else's 24 hours
|
||||
// (#2336). A single offset leaves a one-hour sliver at the far end of a
|
||||
// multi-day range that crosses a DST change, and none at all for a single
|
||||
// day, which is the case this fixes.
|
||||
const data = await memoriesApi.search(
|
||||
provider,
|
||||
{ from, to, page, size: 50, utc_offset_minutes: utcOffsetMinutesForDay(from || to) },
|
||||
signal,
|
||||
);
|
||||
const assets = data.assets || [];
|
||||
setPhotos((prev) => (append ? [...prev, ...assets] : assets));
|
||||
setHasMore(!!data.hasMore);
|
||||
@@ -162,6 +173,9 @@ export function ProviderPicker({
|
||||
[photos, contextLocation?.lat, contextLocation?.lng],
|
||||
);
|
||||
|
||||
// Albums come back whole, so they never page.
|
||||
const morePagesPending = hasMore && !selectedAlbum;
|
||||
|
||||
const toggleAsset = (id: string) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Map(prev);
|
||||
@@ -474,82 +488,91 @@ export function ProviderPicker({
|
||||
<div className="flex justify-center py-12">
|
||||
<div className="h-6 w-6 animate-spin rounded-full border-2 border-zinc-300 border-t-zinc-900" />
|
||||
</div>
|
||||
) : sortedPhotos.length === 0 ? (
|
||||
<div className="py-12 text-center">
|
||||
<p className="text-[13px] text-zinc-500">
|
||||
{filter === 'trip' && !tripRange.from
|
||||
? t('journey.trips.noTripsLinkedSettings')
|
||||
: t('journey.detail.noPhotos')}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{groupPhotosByDate(sortedPhotos).map((group) => (
|
||||
<div key={group.date}>
|
||||
{(!embedded || filter !== 'day') && (
|
||||
<p className="mt-4 mb-2 text-[11px] font-medium text-zinc-500 first:mt-0 dark:text-zinc-400">
|
||||
{group.label}
|
||||
</p>
|
||||
)}
|
||||
<div className="mb-1 grid grid-cols-3 gap-1.5 sm:grid-cols-4 md:grid-cols-5">
|
||||
{group.assets.map((asset: any) => {
|
||||
const isSelected = selected.has(asset.id);
|
||||
const alreadyAdded = existingAssetIds.has(asset.id);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={asset.id}
|
||||
disabled={alreadyAdded}
|
||||
aria-pressed={isSelected}
|
||||
aria-label={asset.city || group.label}
|
||||
onClick={() => !alreadyAdded && toggleAsset(asset.id)}
|
||||
className={`relative block aspect-square w-full overflow-hidden rounded-lg ${
|
||||
alreadyAdded
|
||||
? 'cursor-not-allowed opacity-40'
|
||||
: isSelected
|
||||
? 'cursor-pointer ring-2 ring-zinc-900 ring-offset-2 dark:ring-white dark:ring-offset-zinc-900'
|
||||
: 'cursor-pointer'
|
||||
}`}
|
||||
>
|
||||
<img
|
||||
src={`/api/integrations/memories/${provider}/assets/0/${asset.id}/${userId}/thumbnail${selectedAlbumPassphrase ? `?passphrase=${encodeURIComponent(selectedAlbumPassphrase)}` : ''}`}
|
||||
alt=""
|
||||
className="h-full w-full object-cover"
|
||||
loading="lazy"
|
||||
onError={(e) => {
|
||||
const img = e.currentTarget;
|
||||
const original = `/api/integrations/memories/${provider}/assets/0/${asset.id}/${userId}/original${selectedAlbumPassphrase ? `?passphrase=${encodeURIComponent(selectedAlbumPassphrase)}` : ''}`;
|
||||
if (!img.src.includes('/original')) img.src = original;
|
||||
}}
|
||||
/>
|
||||
{alreadyAdded && (
|
||||
<div className="absolute top-1.5 right-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-zinc-500 text-white">
|
||||
<Check size={12} />
|
||||
</div>
|
||||
)}
|
||||
{isSelected && !alreadyAdded && (
|
||||
<div className="absolute top-1.5 right-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-zinc-900 text-white dark:bg-white dark:text-zinc-900">
|
||||
<Check size={12} />
|
||||
</div>
|
||||
)}
|
||||
{asset.mediaType === 'video' && (
|
||||
<div className="pointer-events-none absolute bottom-1.5 left-1.5 z-10 flex h-4 w-4 items-center justify-center rounded-full bg-black/60">
|
||||
<Play size={8} className="ml-px text-white" fill="currentColor" />
|
||||
</div>
|
||||
)}
|
||||
{asset.city && (
|
||||
<div className="absolute right-0 bottom-0 left-0 bg-gradient-to-t from-black/50 to-transparent p-1">
|
||||
<p className="truncate text-[8px] text-white">{asset.city}</p>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{sortedPhotos.length === 0 ? (
|
||||
<div className="py-12 text-center">
|
||||
<p className="text-[13px] text-zinc-500">
|
||||
{filter === 'trip' && !tripRange.from
|
||||
? t('journey.trips.noTripsLinkedSettings')
|
||||
: morePagesPending
|
||||
? t('common.loading')
|
||||
: t('journey.detail.noPhotos')}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
{/* Infinite scroll trigger */}
|
||||
{hasMore && !selectedAlbum && <ScrollTrigger onVisible={loadMorePhotos} loading={loadingMore} />}
|
||||
) : (
|
||||
<div>
|
||||
{groupPhotosByDate(sortedPhotos).map((group) => (
|
||||
<div key={group.date}>
|
||||
{(!embedded || filter !== 'day') && (
|
||||
<p className="mt-4 mb-2 text-[11px] font-medium text-zinc-500 first:mt-0 dark:text-zinc-400">
|
||||
{group.label}
|
||||
</p>
|
||||
)}
|
||||
<div className="mb-1 grid grid-cols-3 gap-1.5 sm:grid-cols-4 md:grid-cols-5">
|
||||
{group.assets.map((asset: any) => {
|
||||
const isSelected = selected.has(asset.id);
|
||||
const alreadyAdded = existingAssetIds.has(asset.id);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={asset.id}
|
||||
disabled={alreadyAdded}
|
||||
aria-pressed={isSelected}
|
||||
aria-label={asset.city || group.label}
|
||||
onClick={() => !alreadyAdded && toggleAsset(asset.id)}
|
||||
className={`relative block aspect-square w-full overflow-hidden rounded-lg ${
|
||||
alreadyAdded
|
||||
? 'cursor-not-allowed opacity-40'
|
||||
: isSelected
|
||||
? 'cursor-pointer ring-2 ring-zinc-900 ring-offset-2 dark:ring-white dark:ring-offset-zinc-900'
|
||||
: 'cursor-pointer'
|
||||
}`}
|
||||
>
|
||||
<img
|
||||
src={`/api/integrations/memories/${provider}/assets/0/${asset.id}/${userId}/thumbnail${selectedAlbumPassphrase ? `?passphrase=${encodeURIComponent(selectedAlbumPassphrase)}` : ''}`}
|
||||
alt=""
|
||||
className="h-full w-full object-cover"
|
||||
loading="lazy"
|
||||
onError={(e) => {
|
||||
const img = e.currentTarget;
|
||||
const original = `/api/integrations/memories/${provider}/assets/0/${asset.id}/${userId}/original${selectedAlbumPassphrase ? `?passphrase=${encodeURIComponent(selectedAlbumPassphrase)}` : ''}`;
|
||||
if (!img.src.includes('/original')) img.src = original;
|
||||
}}
|
||||
/>
|
||||
{alreadyAdded && (
|
||||
<div className="absolute top-1.5 right-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-zinc-500 text-white">
|
||||
<Check size={12} />
|
||||
</div>
|
||||
)}
|
||||
{isSelected && !alreadyAdded && (
|
||||
<div className="absolute top-1.5 right-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-zinc-900 text-white dark:bg-white dark:text-zinc-900">
|
||||
<Check size={12} />
|
||||
</div>
|
||||
)}
|
||||
{asset.mediaType === 'video' && (
|
||||
<div className="pointer-events-none absolute bottom-1.5 left-1.5 z-10 flex h-4 w-4 items-center justify-center rounded-full bg-black/60">
|
||||
<Play size={8} className="ml-px text-white" fill="currentColor" />
|
||||
</div>
|
||||
)}
|
||||
{asset.city && (
|
||||
<div className="absolute right-0 bottom-0 left-0 bg-gradient-to-t from-black/50 to-transparent p-1">
|
||||
<p className="truncate text-[8px] text-white">{asset.city}</p>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{/* Outside the empty/grid choice on purpose: a page whose photos all
|
||||
belong to a neighbouring day leaves the grid empty, and a sentinel
|
||||
that only exists next to photos would never ask for the next page
|
||||
(#2336). */}
|
||||
{morePagesPending && <ScrollTrigger onVisible={loadMorePhotos} loading={loadingMore} />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -377,8 +377,11 @@ describe('JourneySettingsDialog', () => {
|
||||
it('FE-JRN-SETTINGS-023: the trip-GPX switch reads off by default and turns on in one click (#2194)', async () => {
|
||||
const { onRefresh, onSaved } = mountDialog()
|
||||
|
||||
const sw = screen.getByRole('switch', { name: /GPX/i })
|
||||
expect(sw).toHaveAttribute('aria-checked', 'false')
|
||||
// The shared ToggleSwitch is a button with aria-pressed, not a role="switch" with
|
||||
// aria-checked: the dialog drew its own switches by hand until they turned out to be
|
||||
// white on near-white in the dark.
|
||||
const sw = screen.getByRole('button', { name: /GPX/i })
|
||||
expect(sw).toHaveAttribute('aria-pressed', 'false')
|
||||
|
||||
await userEvent.click(sw)
|
||||
|
||||
@@ -393,8 +396,8 @@ describe('JourneySettingsDialog', () => {
|
||||
// The column is INTEGER, so what arrives over the wire is 1, not true.
|
||||
mountDialog(buildJourney({ show_trip_tracks: 1 }))
|
||||
|
||||
const sw = screen.getByRole('switch', { name: /GPX/i })
|
||||
expect(sw).toHaveAttribute('aria-checked', 'true')
|
||||
const sw = screen.getByRole('button', { name: /GPX/i })
|
||||
expect(sw).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
await userEvent.click(sw)
|
||||
await waitFor(() => expect(updateJourney).toHaveBeenCalledWith(3, { show_trip_tracks: false }))
|
||||
@@ -404,7 +407,7 @@ describe('JourneySettingsDialog', () => {
|
||||
updateJourney.mockRejectedValueOnce(new Error('nope'))
|
||||
const { onClose } = mountDialog()
|
||||
|
||||
await userEvent.click(screen.getByRole('switch', { name: /GPX/i }))
|
||||
await userEvent.click(screen.getByRole('button', { name: /GPX/i }))
|
||||
|
||||
await waitFor(() => expect(toastSpy).toHaveBeenCalled())
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { JourneyDetail } from '../../store/journeyStore'
|
||||
import { pickGradient } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import { AddTripDialog } from './JourneyDetailPageAddTripDialog'
|
||||
import { normalizeImageFile } from '../../utils/convertHeic'
|
||||
import ToggleSwitch from '../Settings/ToggleSwitch'
|
||||
|
||||
export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite, onRefresh, onRestoreSuggestions }: {
|
||||
journey: JourneyDetail
|
||||
@@ -188,25 +189,17 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
{/* Trip GPX tracks on the journey map (#2194) */}
|
||||
<div>
|
||||
<label className="text-[10px] font-semibold tracking-[0.12em] uppercase text-zinc-500 block mb-1.5">{t('journey.settings.tracks')}</label>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={!!journey.show_trip_tracks}
|
||||
disabled={savingTracks}
|
||||
onClick={handleTracksToggle}
|
||||
className="w-full flex items-center gap-3 px-3.5 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-xl bg-white dark:bg-zinc-800 text-left disabled:opacity-60"
|
||||
>
|
||||
<div className={`w-full flex items-center gap-3 px-3.5 py-2.5 border border-edge rounded-xl bg-surface-card text-left${savingTracks ? ' opacity-60' : ''}`}>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block text-[14px] text-zinc-900 dark:text-white">{t('journey.settings.showTripTracks')}</span>
|
||||
<span className="block text-[11px] text-zinc-500">{t('journey.settings.showTripTracksHint')}</span>
|
||||
<span className="block text-[14px] text-content-primary">{t('journey.settings.showTripTracks')}</span>
|
||||
<span className="block text-[11px] text-content-faint">{t('journey.settings.showTripTracksHint')}</span>
|
||||
</span>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`w-9 h-5 rounded-full flex-shrink-0 p-0.5 transition-colors ${journey.show_trip_tracks ? 'bg-emerald-500' : 'bg-zinc-300 dark:bg-zinc-600'}`}
|
||||
>
|
||||
<span className={`block w-4 h-4 rounded-full bg-white transition-transform ${journey.show_trip_tracks ? 'translate-x-4' : ''}`} />
|
||||
</span>
|
||||
</button>
|
||||
<ToggleSwitch
|
||||
on={!!journey.show_trip_tracks}
|
||||
onToggle={() => { if (!savingTracks) handleTracksToggle() }}
|
||||
label={t('journey.settings.showTripTracks')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* The three fields a journey may put away (discussion #2299) */}
|
||||
@@ -221,21 +214,17 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
] as const).map(([field, label]) => {
|
||||
const on = journey[field] !== 0
|
||||
return (
|
||||
<button
|
||||
<div
|
||||
key={field}
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={on}
|
||||
aria-label={label}
|
||||
disabled={savingField !== null}
|
||||
onClick={() => handleFieldToggle(field)}
|
||||
className="w-full flex items-center gap-3 px-3.5 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-xl bg-white dark:bg-zinc-800 text-left disabled:opacity-60"
|
||||
className={`w-full flex items-center gap-3 px-3.5 py-2.5 border border-edge rounded-xl bg-surface-card text-left${savingField !== null ? ' opacity-60' : ''}`}
|
||||
>
|
||||
<span className="flex-1 min-w-0 text-[14px] text-zinc-900 dark:text-white">{label}</span>
|
||||
<span aria-hidden="true" className={`w-9 h-5 rounded-full flex-shrink-0 p-0.5 transition-colors ${on ? 'bg-emerald-500' : 'bg-zinc-300 dark:bg-zinc-600'}`}>
|
||||
<span className={`block w-4 h-4 rounded-full bg-white transition-transform ${on ? 'translate-x-4' : ''}`} />
|
||||
</span>
|
||||
</button>
|
||||
<span className="flex-1 min-w-0 text-[14px] text-content-primary">{label}</span>
|
||||
<ToggleSwitch
|
||||
on={on}
|
||||
onToggle={() => { if (savingField === null) handleFieldToggle(field) }}
|
||||
label={label}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-JRN-COVER-001 to FE-JRN-COVER-008
|
||||
// FE-JRN-COVER-001 to FE-JRN-COVER-010
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
@@ -112,4 +112,23 @@ describe('JourneyEntryCover', () => {
|
||||
|
||||
expect(onClick).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('FE-JRN-COVER-009: a clip without a poster falls back to the ground, marked as a clip (#2341)', () => {
|
||||
// Its thumbnail route 404s on purpose, so an <img> would have been a broken face
|
||||
// across the whole card.
|
||||
const entry = buildEntry({ photos: [{ photo_id: 7, media_type: 'video', provider: 'local', thumbnail_path: null }] })
|
||||
const { container } = render(<JourneyEntryCover entry={entry} dayColor="#6366f1" isActive={false} onClick={() => {}} />)
|
||||
|
||||
expect(container.querySelector('img[src*="/thumbnail"]')).toBeNull()
|
||||
expect(container.querySelector('svg.lucide-play')).toBeInTheDocument()
|
||||
expect(container.querySelector('svg.lucide-map-pin')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-JRN-COVER-010: a clip with its poster fills the card like any photo', () => {
|
||||
const entry = buildEntry({ photos: [{ photo_id: 7, media_type: 'video', provider: 'local', thumbnail_path: 'journey/poster.jpg' }] })
|
||||
const { container } = render(<JourneyEntryCover entry={entry} dayColor="#6366f1" isActive={false} onClick={() => {}} />)
|
||||
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', '/api/photos/7/thumbnail')
|
||||
expect(container.querySelector('svg.lucide-play')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { MapPin, Plus } from 'lucide-react'
|
||||
import { MapPin, Play, Plus } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { moodMeta, weatherMeta } from '../../mobile/screens/journey/mobileJourneyMeta'
|
||||
import { posterlessVideo } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import CountryFlag from '../shared/CountryFlag'
|
||||
import { cardDateLabel, cardPhotoId, cardPlace, cardTitle, type CardPhoto } from './journeyCard'
|
||||
import type { JourneyEntry } from '../../store/journeyStore'
|
||||
@@ -25,6 +26,13 @@ import type { JourneyEntry } from '../../store/journeyStore'
|
||||
* which needs no tokens at all.
|
||||
*/
|
||||
|
||||
/** A card's photo, plus what says whether a clip has a poster to draw (#2341). */
|
||||
export interface CoverPhoto extends CardPhoto {
|
||||
media_type?: string | null
|
||||
provider?: string | null
|
||||
thumbnail_path?: string | null
|
||||
}
|
||||
|
||||
/** The subset of an entry a card reads. Shared journeys hand over less than the journey's own. */
|
||||
export interface CoverEntry {
|
||||
id: number
|
||||
@@ -39,7 +47,7 @@ export interface CoverEntry {
|
||||
entry_time?: string | null
|
||||
mood?: string | null
|
||||
weather?: string | null
|
||||
photos?: CardPhoto[]
|
||||
photos?: CoverPhoto[]
|
||||
}
|
||||
|
||||
interface Props {
|
||||
@@ -69,8 +77,12 @@ export default function JourneyEntryCover({
|
||||
const { t, locale } = useTranslation()
|
||||
const isSuggestion = entry.type === 'skeleton'
|
||||
|
||||
const photoId = cardPhotoId(entry.photos?.[0])
|
||||
const src = photoId == null ? null : photoUrlFor ? photoUrlFor(photoId) : `/api/photos/${photoId}/thumbnail`
|
||||
const first = entry.photos?.[0]
|
||||
const photoId = cardPhotoId(first)
|
||||
// A clip without a poster has no picture to fill the card with; its thumbnail
|
||||
// route 404s and an <img> pointed at it would draw the broken glyph (#2341).
|
||||
const posterless = first != null && posterlessVideo(first)
|
||||
const src = photoId == null || posterless ? null : photoUrlFor ? photoUrlFor(photoId) : `/api/photos/${photoId}/thumbnail`
|
||||
|
||||
const title = cardTitle(entry, t)
|
||||
const place = cardPlace(entry)
|
||||
@@ -112,7 +124,9 @@ export default function JourneyEntryCover({
|
||||
<img src={src} alt="" loading="lazy" className="absolute inset-0 h-full w-full rounded-[18px] object-cover" />
|
||||
) : (
|
||||
<span className="absolute inset-0 flex items-center justify-center">
|
||||
<MapPin size={24} strokeWidth={1.8} style={{ color: dayColor }} className="opacity-60" />
|
||||
{posterless
|
||||
? <Play size={24} strokeWidth={1.8} fill="currentColor" style={{ color: dayColor }} className="ml-0.5 opacity-60" />
|
||||
: <MapPin size={24} strokeWidth={1.8} style={{ color: dayColor }} className="opacity-60" />}
|
||||
</span>
|
||||
)}
|
||||
|
||||
|
||||
@@ -27,6 +27,10 @@ vi.mock('leaflet', () => {
|
||||
setView: vi.fn(),
|
||||
flyTo: vi.fn(),
|
||||
panTo: vi.fn(),
|
||||
// Runs the callback at once on a map with a view, else on its load event.
|
||||
// The default is the loaded map; the two "no view yet" tests below hold
|
||||
// the callback back and release it by hand.
|
||||
whenReady: vi.fn((cb: () => void) => { cb(); }),
|
||||
getZoom: vi.fn(() => 10),
|
||||
// Leaflet throws "Set map center and zoom first." out of these until the map
|
||||
// has a view; the loaded map is the default here, FE-COMP-JOURNEYMAP-050
|
||||
@@ -334,13 +338,21 @@ describe('JourneyMap', () => {
|
||||
expect(mockedMap().flyTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-JOURNEYMAP-018: focusMarker swallows leaflet errors when the map has no view yet', () => {
|
||||
it('FE-COMP-JOURNEYMAP-018: focusMarker waits for the first view when the map has none yet', () => {
|
||||
const ref = React.createRef<JourneyMapHandle>();
|
||||
render(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} />);
|
||||
vi.mocked(mockedMap().panTo).mockImplementationOnce(() => { throw new Error('Set map center and zoom first'); });
|
||||
// Leaflet does not refuse a pan on a viewless map, it takes it as the first
|
||||
// view with the zoom undefined, and the tile layer then aborts the load event
|
||||
// before the markers are added. So the pan has to wait for the fit.
|
||||
let onLoad: (() => void) | null = null;
|
||||
vi.mocked(mockedMap().whenReady).mockImplementationOnce((cb: () => void) => { onLoad = cb; });
|
||||
|
||||
expect(() => act(() => { ref.current!.focusMarker('e1'); })).not.toThrow();
|
||||
expect(mockedMap().flyTo).not.toHaveBeenCalled();
|
||||
act(() => { ref.current!.focusMarker('e1'); });
|
||||
expect(mockedMap().panTo).not.toHaveBeenCalled();
|
||||
|
||||
act(() => { onLoad!(); });
|
||||
expect(mockedMap().panTo).toHaveBeenCalledWith({ lat: 0, lng: 0 }, { animate: true, duration: 0.5 });
|
||||
expect(mockedMap().setView).not.toHaveBeenCalledWith({ lat: 0, lng: 0 }, 12);
|
||||
});
|
||||
|
||||
it('FE-COMP-JOURNEYMAP-019: invalidateSize forwards to the leaflet map', () => {
|
||||
@@ -482,14 +494,22 @@ describe('JourneyMap', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-COMP-JOURNEYMAP-029: activeMarkerId falls back to setView while the map has no view yet', () => {
|
||||
it('FE-COMP-JOURNEYMAP-029: activeMarkerId waits for the first view while the map has none yet', () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
render(<JourneyMap checkins={[]} entries={entriesWithCoords} activeMarkerId="e1" />);
|
||||
vi.mocked(mockedMap().panTo).mockImplementationOnce(() => { throw new Error('Set map center and zoom first'); });
|
||||
// The 50 ms timer can beat the rAF that sets the first view, in a
|
||||
// background tab most of all. A pan at that point used to become the first
|
||||
// view itself, with no zoom, and left the map without its markers; the next
|
||||
// rebuild then crashed the page in Leaflet's icon removal.
|
||||
let onLoad: (() => void) | null = null;
|
||||
vi.mocked(mockedMap().whenReady).mockImplementationOnce((cb: () => void) => { onLoad = cb; });
|
||||
act(() => { vi.advanceTimersByTime(60); });
|
||||
// The catch is where a map with no view at all gets its first one.
|
||||
expect(mockedMap().setView).toHaveBeenCalledWith({ lat: 0, lng: 0 }, 12);
|
||||
expect(mockedMap().panTo).not.toHaveBeenCalled();
|
||||
expect(mockedMap().setView).not.toHaveBeenCalledWith({ lat: 0, lng: 0 }, 12);
|
||||
|
||||
act(() => { onLoad!(); });
|
||||
expect(mockedMap().panTo).toHaveBeenCalledWith({ lat: 0, lng: 0 }, { animate: true, duration: 0.5 });
|
||||
expect(mockedMap().flyTo).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
|
||||
@@ -161,6 +161,27 @@ function markerSvg(dayColor: string, dayLabel: number, highlighted: boolean): st
|
||||
</div>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Pan, don't zoom: the initial fitBounds decides how far out the reader starts,
|
||||
* and a focus keeps that (discussion #2299).
|
||||
*
|
||||
* Deferred until the map has its first view. That view is set on a rAF after
|
||||
* the build, and the active entry asks for its pan on a 50 ms timer, so a tab
|
||||
* in the background or a slow frame lets the pan come first. Leaflet does not
|
||||
* refuse a pan on a viewless map, it takes it as the first view, with the zoom
|
||||
* still undefined: the tile layer aborts its own add on that, the load event
|
||||
* stops halfway, and every marker queued behind it never makes it onto the map.
|
||||
* The next rebuild then tears down markers that were never added and dies in
|
||||
* Leaflet's icon removal, which took the whole journey page with it after each
|
||||
* save. whenReady runs the pan at once on a map with a view and otherwise right
|
||||
* after the fit lands.
|
||||
*/
|
||||
function panToMarker(map: L.Map, marker: L.Marker): void {
|
||||
map.whenReady(() => {
|
||||
map.panTo(marker.getLatLng(), { animate: true, duration: 0.5 })
|
||||
})
|
||||
}
|
||||
|
||||
const EMPTY_TRAIL: { lat: number; lng: number }[] = []
|
||||
const EMPTY_TRACKS: JourneyTrack[] = []
|
||||
/** Fallback when a track carries no colour of its own, matching the planner's default. */
|
||||
@@ -254,11 +275,7 @@ function JourneyMap(
|
||||
const focusMarker = useCallback((id: string) => {
|
||||
highlightMarker(id)
|
||||
const marker = markersRef.current.get(id)
|
||||
if (marker && mapRef.current) {
|
||||
try {
|
||||
mapRef.current.panTo(marker.getLatLng(), { animate: true, duration: 0.5 })
|
||||
} catch { /* map not yet initialized */ }
|
||||
}
|
||||
if (marker && mapRef.current) panToMarker(mapRef.current, marker)
|
||||
}, [])
|
||||
|
||||
const invalidateSize = useCallback(() => {
|
||||
@@ -511,14 +528,7 @@ function JourneyMap(
|
||||
highlightMarker(activeMarkerId)
|
||||
const marker = markersRef.current.get(activeMarkerId)
|
||||
if (!marker || !mapRef.current) return
|
||||
// Pan, don't zoom — see focusMarker. fitBounds may still be pending when this
|
||||
// fires, and panTo on a map with no view throws "Set map center and zoom
|
||||
// first", so the catch is where the map gets its first one.
|
||||
try {
|
||||
mapRef.current.panTo(marker.getLatLng(), { animate: true, duration: 0.5 })
|
||||
} catch {
|
||||
mapRef.current.setView(marker.getLatLng(), 12)
|
||||
}
|
||||
panToMarker(mapRef.current, marker)
|
||||
}, 50)
|
||||
return () => clearTimeout(timer)
|
||||
}, [activeMarkerId])
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-JENTRYVIEW-001 to FE-COMP-JENTRYVIEW-017
|
||||
// FE-COMP-JENTRYVIEW-001 to FE-COMP-JENTRYVIEW-020
|
||||
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
@@ -234,4 +234,25 @@ describe('MobileEntryView', () => {
|
||||
expect(screen.queryByText('Amazing')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Sunny')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-JENTRYVIEW-019: a clip is drawn from its poster, in the hero as in the strip (#2341)', () => {
|
||||
// Its original is the video file, which an <img> cannot show, so the hero used
|
||||
// to be a broken image for every clip, poster or not.
|
||||
const clip = { ...buildPhoto(4), media_type: 'video', provider: 'local', thumbnail_path: 'journey/poster.jpg' }
|
||||
const { container } = renderView(buildEntry({ photos: [clip, buildPhoto(5)] }))
|
||||
const images = container.querySelectorAll('img')
|
||||
expect(images[0]).toHaveAttribute('src', '/api/photos/4/thumbnail')
|
||||
expect(images[1]).toHaveAttribute('src', '/api/photos/4/thumbnail')
|
||||
expect(container.querySelectorAll('svg.lucide-play')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-COMP-JENTRYVIEW-020: a clip without a poster keeps the play badge and asks for no image at all', () => {
|
||||
const clip = { ...buildPhoto(4), media_type: 'video', provider: 'local', thumbnail_path: null }
|
||||
const { container } = renderView(buildEntry({ photos: [clip, buildPhoto(5)] }))
|
||||
const images = container.querySelectorAll('img')
|
||||
// The second photo's strip thumbnail is the only image left.
|
||||
expect(images).toHaveLength(1)
|
||||
expect(images[0]).toHaveAttribute('src', '/api/photos/5/thumbnail')
|
||||
expect(container.querySelectorAll('svg.lucide-play')).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import JournalBody from './JournalBody'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { formatLocationName } from '../../utils/formatters'
|
||||
import { posterlessVideo } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import type { JourneyEntry, JourneyPhoto } from '../../store/journeyStore'
|
||||
|
||||
// Labels are translation keys, like the desktop tables in
|
||||
@@ -105,12 +106,18 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
|
||||
}`}
|
||||
onClick={() => onPhotoClick(photos, 0)}
|
||||
>
|
||||
<img
|
||||
src={photoUrl(photos[0], 'original', publicPhotoUrl)}
|
||||
alt=""
|
||||
className={`w-full max-h-[50vh] ${photos[0].media_type === 'video' ? 'object-contain' : 'object-cover'
|
||||
}`}
|
||||
/>
|
||||
{/* A clip is drawn from its poster, its original being the video file.
|
||||
Without a poster the black ground and the play badge are the hero (#2341). */}
|
||||
{posterlessVideo(photos[0]) ? (
|
||||
<span className="block aspect-video w-full max-h-[50vh]" />
|
||||
) : (
|
||||
<img
|
||||
src={photoUrl(photos[0], photos[0].media_type === 'video' ? 'thumbnail' : 'original', publicPhotoUrl)}
|
||||
alt=""
|
||||
className={`w-full max-h-[50vh] ${photos[0].media_type === 'video' ? 'object-contain' : 'object-cover'
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{photos[0].media_type === 'video' && (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
|
||||
@@ -140,12 +147,14 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
|
||||
}`}
|
||||
onClick={() => onPhotoClick(photos, i)}
|
||||
>
|
||||
<img
|
||||
src={photoUrl(p, 'thumbnail', publicPhotoUrl)}
|
||||
alt=""
|
||||
className={`h-full w-full ${p.media_type === 'video' ? 'object-contain' : 'object-cover'
|
||||
}`}
|
||||
/>
|
||||
{!posterlessVideo(p) && (
|
||||
<img
|
||||
src={photoUrl(p, 'thumbnail', publicPhotoUrl)}
|
||||
alt=""
|
||||
className={`h-full w-full ${p.media_type === 'video' ? 'object-contain' : 'object-cover'
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{p.media_type === 'video' && (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const plyrCtor = vi.fn()
|
||||
vi.mock('plyr', () => ({
|
||||
default: class {
|
||||
el: HTMLElement
|
||||
original: Node
|
||||
constructor(el: HTMLElement, options: Record<string, unknown>) {
|
||||
plyrCtor(el, options)
|
||||
this.el = el
|
||||
this.original = el.cloneNode(true)
|
||||
}
|
||||
// What the real destroy() does to the document: the element as it was at
|
||||
// construction goes back in, whatever React wrote to it since.
|
||||
destroy() {
|
||||
this.el.replaceWith(this.original)
|
||||
}
|
||||
},
|
||||
}))
|
||||
vi.mock('plyr/dist/plyr.css', () => ({}))
|
||||
|
||||
import { render } from '../../../tests/helpers/render'
|
||||
import VideoPlayer from './VideoPlayer'
|
||||
|
||||
describe('VideoPlayer', () => {
|
||||
beforeEach(() => { plyrCtor.mockClear() })
|
||||
|
||||
it('hands Plyr the sprite from this origin, not the one on cdn.plyr.io (#2341)', () => {
|
||||
// connect-src refuses cdn.plyr.io, so with the default the player worked and
|
||||
// every button in it was blank. The sprite ships with the bundle instead.
|
||||
render(<VideoPlayer src="/api/photos/7/original" autoPlay={false} />)
|
||||
|
||||
expect(plyrCtor).toHaveBeenCalledTimes(1)
|
||||
const [, options] = plyrCtor.mock.calls[0]
|
||||
// A hashed asset URL in the bundle, the raw file (with its query) under vitest.
|
||||
expect(String(options.iconUrl)).toMatch(/plyr[^/]*\.svg(\?|$)/)
|
||||
expect(String(options.iconUrl)).not.toContain('cdn.plyr.io')
|
||||
})
|
||||
|
||||
it('resets the element to an empty source on teardown rather than a clip on the CDN', () => {
|
||||
// media-src refuses cdn.plyr.io too; an empty source aborts the stream just the
|
||||
// same, and the element is out of the document by then.
|
||||
render(<VideoPlayer src="/api/photos/7/original" autoPlay={false} />)
|
||||
|
||||
const [, options] = plyrCtor.mock.calls[0]
|
||||
expect(options.blankVideo).toBe('')
|
||||
})
|
||||
|
||||
it('mounts the player on the video element it renders', () => {
|
||||
const { container } = render(<VideoPlayer src="/api/photos/7/original" poster="/api/photos/7/thumbnail" />)
|
||||
|
||||
const [el] = plyrCtor.mock.calls[0]
|
||||
expect(el).toBe(container.querySelector('video'))
|
||||
expect(container.querySelector('video')).toHaveAttribute('poster', '/api/photos/7/thumbnail')
|
||||
})
|
||||
|
||||
it('stepping to another clip builds the player on a fresh element, so the clip on screen is the new one', () => {
|
||||
// Rebuilding Plyr on the same <video> ran after React had already pointed it at
|
||||
// the next clip, and destroy() then swapped the first clip back in. The file
|
||||
// lightboxes do not key the player themselves, so this has to hold here.
|
||||
const { container, rerender } = render(<VideoPlayer src="/api/photos/7/original" autoPlay={false} />)
|
||||
rerender(<VideoPlayer src="/api/photos/8/original" autoPlay={false} />)
|
||||
|
||||
expect(plyrCtor).toHaveBeenCalledTimes(2)
|
||||
const [first] = plyrCtor.mock.calls[0]
|
||||
const [second] = plyrCtor.mock.calls[1]
|
||||
expect(second).not.toBe(first)
|
||||
expect(second).toBe(container.querySelector('video'))
|
||||
expect(container.querySelector('video')).toHaveAttribute('src', '/api/photos/8/original')
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,18 @@
|
||||
import React, { useEffect, useRef } from 'react'
|
||||
import Plyr from 'plyr'
|
||||
import 'plyr/dist/plyr.css'
|
||||
// The control icons, served from this origin. Plyr's default points at cdn.plyr.io,
|
||||
// which connect-src refuses: the player worked but every button in it was blank.
|
||||
// A file, not a data URL, because Plyr tells same-origin from cross-origin by the
|
||||
// host and would fetch a data URL over XHR, which connect-src refuses as well.
|
||||
import plyrSprite from 'plyr/dist/plyr.svg?no-inline'
|
||||
|
||||
interface Props {
|
||||
src: string
|
||||
poster?: string
|
||||
autoPlay?: boolean
|
||||
style?: React.CSSProperties
|
||||
}
|
||||
|
||||
/**
|
||||
* Video player for gallery/lightbox playback (#823), built on Plyr over a native
|
||||
@@ -8,18 +20,17 @@ import 'plyr/dist/plyr.css'
|
||||
* the source carries the correct video MIME from the server. The Plyr instance is
|
||||
* created once per mounted source and destroyed on unmount, so navigating away in
|
||||
* the lightbox stops playback.
|
||||
*
|
||||
* A new source is a new element: Plyr's destroy() puts a clone of the element as
|
||||
* it was at construction back into the document, so rebuilding the player on a
|
||||
* <video> React had already pointed at the next clip left the first clip on
|
||||
* screen under the next one's name.
|
||||
*/
|
||||
export default function VideoPlayer({
|
||||
src,
|
||||
poster,
|
||||
autoPlay = true,
|
||||
style,
|
||||
}: {
|
||||
src: string
|
||||
poster?: string
|
||||
autoPlay?: boolean
|
||||
style?: React.CSSProperties
|
||||
}): React.ReactElement {
|
||||
export default function VideoPlayer(props: Props): React.ReactElement {
|
||||
return <PlyrVideo key={props.src} {...props} />
|
||||
}
|
||||
|
||||
function PlyrVideo({ src, poster, autoPlay = true, style }: Props): React.ReactElement {
|
||||
const videoRef = useRef<HTMLVideoElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -40,6 +51,12 @@ export default function VideoPlayer({
|
||||
autoplay: autoPlay,
|
||||
clickToPlay: true,
|
||||
hideControls: false,
|
||||
iconUrl: plyrSprite,
|
||||
// On teardown Plyr points the element at a blank clip to abort the stream,
|
||||
// by default one on cdn.plyr.io, which media-src refuses. An empty source
|
||||
// aborts the stream just the same, and the element is out of the document
|
||||
// by then, so the error it would otherwise report has nowhere to show.
|
||||
blankVideo: '',
|
||||
})
|
||||
|
||||
return () => {
|
||||
@@ -49,7 +66,7 @@ export default function VideoPlayer({
|
||||
/* already torn down */
|
||||
}
|
||||
}
|
||||
}, [src, autoPlay])
|
||||
}, [autoPlay])
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-005
|
||||
// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-006
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||
import { MapLayerSwitcher } from './MapLayerSwitcher'
|
||||
import { MapLayerSwitcher, MAP_ROUND_CONTROL_SIZE } from './MapLayerSwitcher'
|
||||
|
||||
describe('MapLayerSwitcher', () => {
|
||||
it('FE-COMP-MAPLAYER-001: on the default layer, offers the switch to satellite', () => {
|
||||
@@ -41,4 +41,17 @@ describe('MapLayerSwitcher', () => {
|
||||
fireEvent.mouseLeave(button)
|
||||
expect(button.style.background).toBe('transparent')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPLAYER-006: the shell is as wide as the size its neighbours are placed off', () => {
|
||||
render(<MapLayerSwitcher active="default" onToggle={() => {}} />)
|
||||
const button = screen.getByRole('button')
|
||||
const shell = button.parentElement as HTMLElement
|
||||
|
||||
// The phone's compass stands beside the switcher at inset + size + gap. If the
|
||||
// markup grew without the constant, the compass would slide back under the shell.
|
||||
expect(shell.style.padding).toBe('4px')
|
||||
expect(button.style.width).toBe('34px')
|
||||
expect(button.style.height).toBe('34px')
|
||||
expect(parseFloat(button.style.width) + 2 * parseFloat(shell.style.padding)).toBe(MAP_ROUND_CONTROL_SIZE)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,9 +5,22 @@ import { MAP_CONTROL_SHADOW } from './mapControlShadow'
|
||||
|
||||
export type BaseLayer = 'default' | 'satellite'
|
||||
|
||||
// Round base-layer switcher for the Leaflet planner map (default street tiles ↔
|
||||
// satellite). Same frosted shell as MapCompassPill so it lines up with the other
|
||||
// map controls; the icon shows the layer it switches to.
|
||||
// Where the switcher sits and how much room it takes, so a control placed beside it
|
||||
// (the phone's compass) is positioned off the same numbers instead of guessing them.
|
||||
// Both map engines place the switcher with the inset, so they cannot drift apart either.
|
||||
|
||||
/** Distance from the map's left edge (plus any side panel) to the switcher. */
|
||||
export const MAP_LAYER_SWITCHER_INSET = 20
|
||||
/**
|
||||
* Outer size of the round shell: a 34px button in 4px of padding, the same shell as
|
||||
* MapCompassPill. The markup below keeps its literals, and FE-COMP-MAPLAYER-006 holds
|
||||
* them to this number.
|
||||
*/
|
||||
export const MAP_ROUND_CONTROL_SIZE = 42
|
||||
|
||||
// Round base-layer switcher for both planner maps, Leaflet and GL (default street
|
||||
// tiles ↔ satellite). Same frosted shell as MapCompassPill so it lines up with the
|
||||
// other map controls; the icon shows the layer it switches to.
|
||||
export function MapLayerSwitcher({ active, onToggle }: { active: BaseLayer; onToggle: () => void }) {
|
||||
const { t } = useTranslation()
|
||||
const isSatellite = active === 'satellite'
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
/**
|
||||
* Clicking a place pin after the map has been dragged (#2504).
|
||||
*
|
||||
* Nothing Leaflet-related is mocked here on purpose. The bug lived in the space between
|
||||
* our drag wiring and Leaflet's own event routing: the pins swallow mousedown so a drag
|
||||
* onto a day can start without the map sliding away, and Leaflet only forgets that the
|
||||
* map was panned when it sees the next mousedown. A mocked react-leaflet, like the one
|
||||
* MapView.test.tsx uses, has no such memory and kept passing throughout.
|
||||
*
|
||||
* The click itself has to keep taking Leaflet's route and the page's: it is what closes
|
||||
* an open popup on the map, and an open context menu beside it.
|
||||
*/
|
||||
import React, { useState } from 'react'
|
||||
import { flushSync } from 'react-dom'
|
||||
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest'
|
||||
import { render, waitFor, act } from '../../../tests/helpers/render'
|
||||
import { resetAllStores } from '../../../tests/helpers/store'
|
||||
import { buildPlace } from '../../../tests/helpers/factories'
|
||||
|
||||
vi.mock('../../hooks/useGeolocation', () => ({
|
||||
useGeolocation: () => ({ position: null, mode: 'off', error: null, errorCode: null, cycleMode: vi.fn(), setMode: vi.fn() }),
|
||||
}))
|
||||
|
||||
vi.mock('../../services/photoService', () => ({
|
||||
getCached: vi.fn(() => null),
|
||||
isLoading: vi.fn(() => false),
|
||||
fetchPhoto: vi.fn(),
|
||||
onThumbReady: vi.fn(() => () => {}),
|
||||
getAllThumbs: vi.fn(() => ({})),
|
||||
}))
|
||||
|
||||
import L from 'leaflet'
|
||||
import { MapView } from './MapView'
|
||||
import { ContextMenu } from '../shared/ContextMenu'
|
||||
|
||||
// Every map this file builds, newest last, for the tests that reach past the component.
|
||||
const maps: L.Map[] = []
|
||||
L.Map.addInitHook(function (this: L.Map) { maps.push(this) })
|
||||
|
||||
// A raster template keeps the basemap a plain TileLayer: the vector default needs WebGL.
|
||||
const RASTER = 'https://tiles.example.test/{z}/{x}/{y}.png'
|
||||
|
||||
// Leaflet sizes the map from the container, which jsdom lays out at 0 x 0. The cluster
|
||||
// group only draws pins inside the visible bounds, so the map needs a real size.
|
||||
const sized = ['clientWidth', 'clientHeight'] as const
|
||||
const originals = new Map<string, PropertyDescriptor | undefined>()
|
||||
beforeAll(() => {
|
||||
// The pans here are synthetic and instant. With inertia, Leaflet would carry them on in
|
||||
// animation frames that can land after a test has already unmounted its map.
|
||||
L.Map.mergeOptions({ inertia: false })
|
||||
for (const key of sized) {
|
||||
originals.set(key, Object.getOwnPropertyDescriptor(HTMLElement.prototype, key))
|
||||
Object.defineProperty(HTMLElement.prototype, key, { configurable: true, get: () => (key === 'clientWidth' ? 1000 : 700) })
|
||||
}
|
||||
})
|
||||
afterAll(() => {
|
||||
L.Map.mergeOptions({ inertia: true })
|
||||
for (const key of sized) {
|
||||
const original = originals.get(key)
|
||||
if (original) Object.defineProperty(HTMLElement.prototype, key, original)
|
||||
else delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key]
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
resetAllStores()
|
||||
})
|
||||
|
||||
/** Leaflet only starts a pan for the primary button, which it reads off `which`. */
|
||||
function mouse(type: string, x: number, y: number): MouseEvent {
|
||||
const event = new MouseEvent(type, { bubbles: true, cancelable: true, button: 0, clientX: x, clientY: y })
|
||||
Object.defineProperty(event, 'which', { value: 1 })
|
||||
return event
|
||||
}
|
||||
|
||||
/** Drag the map by its background, the way a user pans it. */
|
||||
function panMap(container: Element) {
|
||||
act(() => {
|
||||
container.dispatchEvent(mouse('mousedown', 300, 300))
|
||||
container.dispatchEvent(mouse('mousemove', 340, 320))
|
||||
container.dispatchEvent(mouse('mousemove', 380, 340))
|
||||
container.dispatchEvent(mouse('mouseup', 380, 340))
|
||||
})
|
||||
}
|
||||
|
||||
/** A plain click on an element: press, release, click, all on the same spot. */
|
||||
function clickOn(el: Element) {
|
||||
act(() => {
|
||||
el.dispatchEvent(mouse('mousedown', 500, 350))
|
||||
el.dispatchEvent(mouse('mouseup', 500, 350))
|
||||
el.dispatchEvent(mouse('click', 500, 350))
|
||||
})
|
||||
}
|
||||
|
||||
// Two stops a few hundred metres apart in Nara: separate pins at this zoom, not a cluster.
|
||||
const places = [
|
||||
{ ...buildPlace({ id: 1, name: 'Todai-ji', lat: 34.689, lng: 135.8398 }), category_name: null, category_color: null, category_icon: null },
|
||||
{ ...buildPlace({ id: 2, name: 'Kasuga Taisha', lat: 34.6812, lng: 135.8484 }), category_name: null, category_color: null, category_icon: null },
|
||||
]
|
||||
|
||||
async function renderMap() {
|
||||
const onMarkerClick = vi.fn()
|
||||
const onMapClick = vi.fn()
|
||||
const view = render(
|
||||
<MapView places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER} onMarkerClick={onMarkerClick} onMapClick={onMapClick} />,
|
||||
)
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement
|
||||
// The cluster group takes its markers in on a timer (chunkedLoading).
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2))
|
||||
const pins = [...container.querySelectorAll('.leaflet-marker-icon[draggable="true"]')] as HTMLElement[]
|
||||
return { container, pins, onMarkerClick, onMapClick }
|
||||
}
|
||||
|
||||
describe('MapView on a real Leaflet map', () => {
|
||||
it('FE-MAPCLICK-001: a pin opens its place on a map nobody has dragged yet', async () => {
|
||||
const { pins, onMarkerClick, onMapClick } = await renderMap()
|
||||
clickOn(pins[0])
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1)
|
||||
// Still the marker's click, not one on the empty map behind it.
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-MAPCLICK-002: a pin still opens its place after the map was dragged (#2504)', async () => {
|
||||
const { container, pins, onMarkerClick, onMapClick } = await renderMap()
|
||||
panMap(container)
|
||||
clickOn(pins[0])
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1)
|
||||
// And again: the report was that every click after the pan went nowhere.
|
||||
clickOn(pins[1])
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(2)
|
||||
expect(onMarkerClick.mock.calls.map(call => call[0]).sort()).toEqual([1, 2])
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-MAPCLICK-003: the click that ends a pan still counts for nothing', async () => {
|
||||
const { container, onMarkerClick, onMapClick } = await renderMap()
|
||||
panMap(container)
|
||||
// The browser aims the click that closes a drag at the element both ends share,
|
||||
// which is the map rather than the pin the pointer happened to stop on. Leaflet
|
||||
// swallows it, and must go on doing so: it is not a click on the empty map either.
|
||||
act(() => { container.dispatchEvent(mouse('click', 380, 340)) })
|
||||
expect(onMarkerClick).not.toHaveBeenCalled()
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("FE-MAPCLICK-004: a pin on a touch screen keeps Leaflet's own click and no drag wiring", async () => {
|
||||
const original = Object.getOwnPropertyDescriptor(window.navigator, 'maxTouchPoints')
|
||||
Object.defineProperty(window.navigator, 'maxTouchPoints', { configurable: true, value: 5 })
|
||||
try {
|
||||
const onMarkerClick = vi.fn()
|
||||
const view = render(<MapView places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER} onMarkerClick={onMarkerClick} />)
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon').length).toBe(2))
|
||||
const pin = container.querySelector('.leaflet-marker-icon') as HTMLElement
|
||||
expect(pin.getAttribute('draggable')).toBeNull()
|
||||
clickOn(pin)
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
if (original) Object.defineProperty(window.navigator, 'maxTouchPoints', original)
|
||||
else delete (window.navigator as unknown as Record<string, unknown>).maxTouchPoints
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-MAPCLICK-005: the place a pin opens stays open when the pin redraws mid-click', async () => {
|
||||
// The selection a pin makes redraws its icon, which replaces the element the click
|
||||
// landed on. Leaflet has to have found the pin before that happens: reading the target
|
||||
// afterwards, it finds it cut out of the map and takes the click for one on the empty
|
||||
// background, which would close the place again straight away.
|
||||
const onMapClick = vi.fn()
|
||||
function Planner() {
|
||||
const [selected, setSelected] = useState<number | null>(null)
|
||||
return (
|
||||
<>
|
||||
<output data-testid="selected">{selected ?? ''}</output>
|
||||
<MapView
|
||||
places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER}
|
||||
selectedPlaceId={selected}
|
||||
onMarkerClick={(id: number) => flushSync(() => setSelected(id))}
|
||||
onMapClick={() => { onMapClick(); setSelected(null) }}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
const view = render(<Planner />)
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2))
|
||||
const pin = container.querySelector('.leaflet-marker-icon[draggable="true"]') as HTMLElement
|
||||
// The pointer lands on the photo inside the pin, which the redraw replaces.
|
||||
clickOn(pin.firstElementChild as HTMLElement)
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
expect(view.getByTestId('selected').textContent).not.toBe('')
|
||||
})
|
||||
|
||||
it('FE-MAPCLICK-006: a pin click after a pan still closes an open popup on the map', async () => {
|
||||
const { container, pins, onMarkerClick } = await renderMap()
|
||||
const map = maps[maps.length - 1]
|
||||
panMap(container)
|
||||
// A hazard or plugin popup, as the planner opens them. Leaflet closes those on the
|
||||
// "preclick" it sends ahead of every click it routes, a pin's included.
|
||||
const popup = L.popup({ autoPan: false }).setLatLng([34.685, 135.844]).setContent('Road closed')
|
||||
act(() => { popup.openOn(map) })
|
||||
expect(map.hasLayer(popup)).toBe(true)
|
||||
clickOn(pins[0])
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1)
|
||||
expect(map.hasLayer(popup)).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-MAPCLICK-007: a pin click after a pan still reaches the page and closes an open context menu', async () => {
|
||||
const onClose = vi.fn()
|
||||
const onMarkerClick = vi.fn()
|
||||
const view = render(
|
||||
<>
|
||||
{/* The menu the places list and the day plan open on a right click. It closes on
|
||||
any click that reaches the document. */}
|
||||
<ContextMenu menu={{ x: 20, y: 20, items: [{ label: 'Edit' }] }} onClose={onClose} />
|
||||
<MapView places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER} onMarkerClick={onMarkerClick} />
|
||||
</>,
|
||||
)
|
||||
const container = view.container.querySelector('.leaflet-container') as HTMLElement
|
||||
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2))
|
||||
const pin = container.querySelector('.leaflet-marker-icon[draggable="true"]') as HTMLElement
|
||||
panMap(container)
|
||||
clickOn(pin)
|
||||
expect(onMarkerClick).toHaveBeenCalledTimes(1)
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-MAPCLICK-008: pressing a pin after a pan still holds the map still for a drag onto a day', async () => {
|
||||
const { container, pins } = await renderMap()
|
||||
const map = maps[maps.length - 1]
|
||||
panMap(container)
|
||||
const before = map.getCenter()
|
||||
// Press on the pin and move off it, as the start of a drag towards the day plan.
|
||||
act(() => {
|
||||
pins[0].dispatchEvent(mouse('mousedown', 500, 350))
|
||||
document.dispatchEvent(mouse('mousemove', 560, 390))
|
||||
document.dispatchEvent(mouse('mousemove', 620, 430))
|
||||
document.dispatchEvent(mouse('mouseup', 620, 430))
|
||||
})
|
||||
expect(map.getCenter()).toEqual(before)
|
||||
// The pan handler is back on, and the background still pans the map.
|
||||
expect(map.dragging.enabled()).toBe(true)
|
||||
panMap(container)
|
||||
expect(map.getCenter()).not.toEqual(before)
|
||||
})
|
||||
})
|
||||
@@ -56,6 +56,37 @@ vi.mock('../../hooks/useGeolocation', () => ({
|
||||
// after the map already rendered.
|
||||
const thumbCallbacks = vi.hoisted(() => new Map<string, (thumb: string) => void>())
|
||||
|
||||
// The cluster group and the Leaflet markers MapView reaches for when a selection lands
|
||||
// on a stop that shares its coordinates and so has no pin of its own. `stacked` decides
|
||||
// whether the group answers with a bubble or with the marker itself.
|
||||
const clusterMock = vi.hoisted(() => {
|
||||
const spiderfy = vi.fn()
|
||||
return {
|
||||
spiderfy,
|
||||
stacked: false,
|
||||
asked: [] as unknown[],
|
||||
markers: new Map<Element, object>(),
|
||||
/**
|
||||
* One marker double per pin, not per coordinate. Stops that share a coordinate are
|
||||
* the whole point here, and a registry keyed by place id only proves anything when
|
||||
* the two markers on that coordinate can be told apart.
|
||||
*/
|
||||
stub(node: Element) {
|
||||
const existing = clusterMock.markers.get(node)
|
||||
if (existing) return existing
|
||||
const fresh = { pin: node }
|
||||
clusterMock.markers.set(node, fresh)
|
||||
return fresh
|
||||
},
|
||||
group: {
|
||||
getVisibleParent(marker: unknown) {
|
||||
clusterMock.asked.push(marker)
|
||||
return clusterMock.stacked ? { spiderfy } : marker
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('react-leaflet', () => ({
|
||||
// center/zoom are surfaced so tests can assert the camera the map is built
|
||||
// with; maxZoom because a cluster refuses to attach to a map without one.
|
||||
@@ -63,9 +94,16 @@ vi.mock('react-leaflet', () => ({
|
||||
<div data-testid="map-container" data-center={JSON.stringify(center)} data-zoom={zoom} data-maxzoom={maxZoom}>{children}</div>
|
||||
),
|
||||
TileLayer: () => <div data-testid="tile-layer" />,
|
||||
Marker: ({ children, eventHandlers, position, icon, zIndexOffset }: any) => (
|
||||
Marker: ({ children, eventHandlers, position, icon, zIndexOffset, ref }: any) => (
|
||||
<div
|
||||
ref={node => { if (node && zIndexOffset === 500) eventHandlers?.add?.({ target: { getElement: () => node } }) }}
|
||||
ref={node => {
|
||||
if (node && zIndexOffset === 500) eventHandlers?.add?.({ target: { getElement: () => node } })
|
||||
// Stands in for the L.Marker react-leaflet hands back, so MapView's registry has
|
||||
// something to look a selected stop up by. Only the markers the cluster group
|
||||
// holds get one: a place pin is all this double stands in for, and the route-via
|
||||
// markers outside the group expect a Leaflet marker of their own.
|
||||
ref?.(node?.closest('[data-testid="cluster-group"]') ? clusterMock.stub(node) : null)
|
||||
}}
|
||||
data-testid="marker"
|
||||
data-lat={position[0]}
|
||||
data-lng={position[1]}
|
||||
@@ -118,8 +156,8 @@ vi.mock('react-leaflet', () => ({
|
||||
vi.mock('react-leaflet-cluster', () => ({
|
||||
// The real cluster group calls iconCreateFunction itself; the probe button
|
||||
// lets a test invoke it with a chosen child count.
|
||||
default: ({ children, iconCreateFunction }: any) => (
|
||||
<div data-testid="cluster-group">
|
||||
default: ({ children, iconCreateFunction, ref }: any) => (
|
||||
<div data-testid="cluster-group" ref={node => { ref?.(node ? clusterMock.group : null) }}>
|
||||
<button
|
||||
data-testid="cluster-icon-probe"
|
||||
onClick={(e: any) => {
|
||||
@@ -174,6 +212,9 @@ const ORIGINAL_WIDTH = window.innerWidth
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetAllStores()
|
||||
clusterMock.markers.clear()
|
||||
clusterMock.asked.length = 0
|
||||
clusterMock.stacked = false
|
||||
mapMock.panes.clear()
|
||||
thumbCallbacks.clear()
|
||||
geoMock.position = null
|
||||
@@ -558,6 +599,32 @@ describe('MapView', () => {
|
||||
expect(screen.getAllByTestId('polyline').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-082: a booking switched on for another day keeps drawing unless the map is held to the day', () => {
|
||||
// The desktop passes no scope, so a booking switched on stays drawn on every day.
|
||||
// Only a caller that asks for it drops the booking from a day it does not run on.
|
||||
const days = [{ id: 10, trip_id: 1, day_number: 1 }, { id: 11, trip_id: 1, day_number: 2 }]
|
||||
const reservation = buildReservation({
|
||||
id: 44,
|
||||
type: 'flight',
|
||||
day_id: 10,
|
||||
end_day_id: 10,
|
||||
endpoints: [
|
||||
{ role: 'from', sequence: 0, name: 'A', code: 'AAA', lat: 1, lng: 2, timezone: null, local_time: null, local_date: null },
|
||||
{ role: 'to', sequence: 1, name: 'B', code: 'BBB', lat: 3, lng: 4, timezone: null, local_time: null, local_date: null },
|
||||
],
|
||||
})
|
||||
const reservations = [reservation]
|
||||
const ids = [44]
|
||||
const { rerender } = render(<MapView reservations={reservations} visibleConnectionIds={ids} days={days} selectedDayId={11} />)
|
||||
expect(screen.getAllByTestId('polyline').length).toBeGreaterThan(0)
|
||||
|
||||
rerender(<MapView reservations={reservations} visibleConnectionIds={ids} days={days} selectedDayId={11} scopeConnectionsToDay />)
|
||||
expect(screen.queryByTestId('polyline')).not.toBeInTheDocument()
|
||||
|
||||
rerender(<MapView reservations={reservations} visibleConnectionIds={ids} days={days} selectedDayId={10} scopeConnectionsToDay />)
|
||||
expect(screen.getAllByTestId('polyline').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-073: a category icon that throws leaves the marker circle intact', () => {
|
||||
// Icon components come from a lookup table a plugin can extend; one that
|
||||
// throws must not take the whole map down, only its own glyph.
|
||||
@@ -879,6 +946,14 @@ describe('MapView selection panning (#921)', () => {
|
||||
expect(mapMock.panTo).toHaveBeenCalledWith([48, 2], { animate: true })
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-083: pans to a selected stay whose pin a filter keeps off the map', () => {
|
||||
const places = [buildMapPlace({ id: 9, lat: 48, lng: 2 })]
|
||||
const stay = buildMapPlace({ id: 11, lat: 50, lng: 4 })
|
||||
const { rerender } = render(<MapView places={places} selectedPlaceId={null} />)
|
||||
rerender(<MapView places={places} selectedPlaceId={11} selectedPlace={stay} />)
|
||||
expect(mapMock.panTo).toHaveBeenCalledWith([50, 4], { animate: true })
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-053: a selected place without coordinates is not panned to', () => {
|
||||
const places = [buildMapPlace({ id: 10, lat: null, lng: null })]
|
||||
const { rerender } = render(<MapView places={places} selectedPlaceId={null} />)
|
||||
@@ -988,6 +1063,42 @@ describe('MapView live location', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Follow my location' }))
|
||||
expect(geoMock.cycleMode).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-064b: turning the phone sideways and back takes the button with it', () => {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 })
|
||||
geoMock.mode = 'off'
|
||||
render(<MapView />)
|
||||
expect(screen.getByRole('button', { name: 'Show my location' })).toBeInTheDocument()
|
||||
|
||||
// landscape crosses the 768px cut without remounting the map
|
||||
act(() => {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 844 })
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
})
|
||||
expect(screen.queryByRole('button', { name: 'Show my location' })).toBeNull()
|
||||
|
||||
act(() => {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 })
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
})
|
||||
expect(screen.getByRole('button', { name: 'Show my location' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-077: the map draws no credit control of its own, on either width', () => {
|
||||
const desktop = render(<MapView />)
|
||||
// The desktop credit is Leaflet's own, in its own container; this component adds none.
|
||||
expect(screen.queryByRole('button', { name: 'Map credits' })).toBeNull()
|
||||
desktop.unmount()
|
||||
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 })
|
||||
const { container } = render(<MapView />)
|
||||
// The phone used to get an (i) here that opened the credit through a class on the
|
||||
// wrapper. The phone map now carries no visible credit at all (mobile.css), so neither
|
||||
// the button nor the class it toggled is left behind.
|
||||
expect(screen.queryByRole('button', { name: 'Map credits' })).toBeNull()
|
||||
const wrapper = container.querySelector('div.w-full.h-full.relative') as HTMLElement
|
||||
expect(wrapper.classList.contains('m-attrib-open')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView bounds fitting', () => {
|
||||
@@ -1048,6 +1159,50 @@ describe('MapView bounds fitting', () => {
|
||||
rerender(<MapView places={places} fitKey={2} />)
|
||||
expect(mapMock.fitBounds).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-078: a caller padding frames the focus points instead of the phone margin, and the day fit keeps its own', () => {
|
||||
// A phone shell lays a chip rail over the top of the map and a bar plus the dock over
|
||||
// the bottom. The flat margin put the ends of a framed leg under either of them.
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 })
|
||||
const leg: [number, number][] = [[48.1, 2.1], [48.3, 2.4]]
|
||||
const chrome = { top: 120, right: 16, bottom: 290, left: 16 }
|
||||
const { rerender } = render(<MapView places={[]} fitKey={1} />)
|
||||
expect(mapMock.fitBounds).not.toHaveBeenCalled()
|
||||
|
||||
rerender(<MapView places={[]} fitKey={1} focusPoints={leg} fitPadding={chrome} />)
|
||||
expect(mapMock.fitBounds).toHaveBeenCalledTimes(1)
|
||||
expect(mapMock.fitBounds.mock.calls[0][1]).toMatchObject({ paddingTopLeft: [16, 120], paddingBottomRight: [16, 290] })
|
||||
|
||||
// Picking a day is not the caller's frame, so that fit keeps the phone margin.
|
||||
const places = [buildMapPlace({ id: 1, lat: 48, lng: 2 }), buildMapPlace({ id: 2, lat: 48.2, lng: 2.2 })]
|
||||
rerender(<MapView places={places} fitKey={2} focusPoints={leg} fitPadding={chrome} />)
|
||||
expect(mapMock.fitBounds).toHaveBeenCalledTimes(2)
|
||||
expect(mapMock.fitBounds.mock.calls[1][1]).toMatchObject({ paddingTopLeft: [40, 20], paddingBottomRight: [40, 20] })
|
||||
|
||||
// And without one, the focus fit falls back to that margin too.
|
||||
const stage: [number, number][] = [[47, 1], [47.5, 1.5]]
|
||||
rerender(<MapView places={places} fitKey={2} focusPoints={stage} />)
|
||||
expect(mapMock.fitBounds).toHaveBeenCalledTimes(3)
|
||||
expect(mapMock.fitBounds.mock.calls[2][1]).toMatchObject({ paddingTopLeft: [40, 20], paddingBottomRight: [40, 20] })
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-079: the caller padding is read by value, so only new numbers refit the points on screen', () => {
|
||||
const leg: [number, number][] = [[48.1, 2.1], [48.3, 2.4]]
|
||||
const { rerender } = render(
|
||||
<MapView places={[]} fitKey={1} focusPoints={leg} fitPadding={{ top: 120, right: 16, bottom: 290, left: 16 }} />,
|
||||
)
|
||||
expect(mapMock.fitBounds).toHaveBeenCalledTimes(1)
|
||||
|
||||
// A parent that builds the object inline hands a new one on every render. The camera
|
||||
// belongs to the traveller between fits, so that alone must not take it back.
|
||||
rerender(<MapView places={[]} fitKey={1} focusPoints={leg} fitPadding={{ top: 120, right: 16, bottom: 290, left: 16 }} />)
|
||||
expect(mapMock.fitBounds).toHaveBeenCalledTimes(1)
|
||||
|
||||
// New numbers mean the chrome moved, so the same points are framed again around it.
|
||||
rerender(<MapView places={[]} fitKey={1} focusPoints={leg} fitPadding={{ top: 120, right: 16, bottom: 98, left: 16 }} />)
|
||||
expect(mapMock.fitBounds).toHaveBeenCalledTimes(2)
|
||||
expect(mapMock.fitBounds.mock.calls[1][1]).toMatchObject({ paddingTopLeft: [16, 120], paddingBottomRight: [16, 98] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView photo thumbnails', () => {
|
||||
@@ -1120,6 +1275,31 @@ describe('MapView photo thumbnails', () => {
|
||||
expect(thumbCallbacks.size).toBe(0)
|
||||
expect(vi.mocked(photoService.fetchPhoto)).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-080: an uploaded photo fills its marker whatever its proportions', () => {
|
||||
// Leaflet's marker pane sets `width: auto` on every img in it, so a photo sized
|
||||
// by attributes was drawn at its full pixel size and the circle only ever showed
|
||||
// the transparent corner of it, over the category colour.
|
||||
render(<MapView places={[buildMapPlace({ id: 27, lat: 48, lng: 2, image_url: '/uploads/places/wide.jpg' })]} />)
|
||||
const holder = document.createElement('div')
|
||||
holder.innerHTML = iconHtmlOf(screen.getAllByTestId('marker')[0])
|
||||
const img = holder.querySelector('img')!
|
||||
|
||||
expect(img.getAttribute('src')).toBe('/uploads/places/wide.jpg')
|
||||
expect(img.style.width).toBe('100%')
|
||||
expect(img.style.height).toBe('100%')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-081: taking the upload off a place asks for its auto photo again, without a reload', () => {
|
||||
const place = buildMapPlace({ id: 28, lat: 48, lng: 2, google_place_id: 'gp-28', name: 'Tower', image_url: '/uploads/places/own.jpg' })
|
||||
const { rerender } = render(<MapView places={[place]} />)
|
||||
expect(vi.mocked(photoService.fetchPhoto)).not.toHaveBeenCalled()
|
||||
|
||||
rerender(<MapView places={[{ ...place, image_url: null }]} />)
|
||||
|
||||
expect(vi.mocked(photoService.fetchPhoto)).toHaveBeenCalledWith('gp-28', 'gp-28', 48, 2, 'Tower')
|
||||
expect(thumbCallbacks.has('gp-28')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
// The marker HTML is a hand-built string handed to L.divIcon, i.e. innerHTML.
|
||||
@@ -1157,3 +1337,54 @@ describe('MapView — untrusted values in the marker HTML', () => {
|
||||
expect(iconHtml()).toContain('#00ff00')
|
||||
})
|
||||
})
|
||||
|
||||
// Stops modelling one building — drop the bags, check in, the museum inside it — all
|
||||
// carry the same coordinates, so only the top pin of the pile is ever on screen. The
|
||||
// places rail used to raise the chosen one with a z-index; inside a bubble there is no
|
||||
// pin to raise, so the bubble has to open instead (#2344).
|
||||
describe('MapView — picking a stop that shares its coordinates', () => {
|
||||
const hotel = { lat: 48.8584, lng: 2.2945 }
|
||||
const stacked = [
|
||||
buildMapPlace({ id: 1, name: 'Drop the bags', ...hotel }),
|
||||
buildMapPlace({ id: 2, name: 'Check in', ...hotel }),
|
||||
buildMapPlace({ id: 3, name: 'Louvre', lat: 48.8606, lng: 2.3376 }),
|
||||
]
|
||||
/** The place pins, in the order the places were handed over. */
|
||||
const pins = () => screen.getAllByTestId('marker').filter(node => node.closest('[data-testid="cluster-group"]'))
|
||||
const markerOf = (index: number) => clusterMock.markers.get(pins()[index])
|
||||
|
||||
it('FE-COMP-MAPVIEW-077: the bubble it is hiding in is fanned open', () => {
|
||||
clusterMock.stacked = true
|
||||
const { rerender } = render(<MapView places={stacked} />)
|
||||
expect(clusterMock.spiderfy).not.toHaveBeenCalled()
|
||||
|
||||
rerender(<MapView places={stacked} selectedPlaceId={2} />)
|
||||
expect(clusterMock.spiderfy).toHaveBeenCalled()
|
||||
// And it asked about the stop that was picked — not about the one stacked under it,
|
||||
// which carries the same coordinates, and not about whichever registered first.
|
||||
expect(clusterMock.asked).toContain(markerOf(1))
|
||||
expect(clusterMock.asked).not.toContain(markerOf(0))
|
||||
expect(clusterMock.asked).not.toContain(markerOf(2))
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-079: a stop in another pile is looked up by its own id', () => {
|
||||
clusterMock.stacked = true
|
||||
const { rerender } = render(<MapView places={stacked} />)
|
||||
rerender(<MapView places={stacked} selectedPlaceId={3} />)
|
||||
|
||||
expect(clusterMock.asked).toContain(markerOf(2))
|
||||
expect(clusterMock.asked).not.toContain(markerOf(0))
|
||||
expect(clusterMock.asked).not.toContain(markerOf(1))
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-078: a stop with a pin of its own is left alone, camera included', () => {
|
||||
clusterMock.stacked = false
|
||||
const { rerender } = render(<MapView places={stacked} />)
|
||||
rerender(<MapView places={stacked} selectedPlaceId={1} />)
|
||||
|
||||
expect(clusterMock.spiderfy).not.toHaveBeenCalled()
|
||||
// The selection still only pans: the zoom belongs to the day fit.
|
||||
expect(mapMock.panTo).toHaveBeenCalled()
|
||||
expect(mapMock.setView).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,6 +4,7 @@ import { renderIconMarkup } from '../../utils/iconMarkup'
|
||||
import { MapContainer, TileLayer, Marker, Polyline, CircleMarker, Circle, useMap, Tooltip } from 'react-leaflet'
|
||||
import MarkerClusterGroup from 'react-leaflet-cluster'
|
||||
import { makeMarkerDraggable, makePoiDraggable, draggedPoiId } from './markerDrag'
|
||||
import { CLUSTER_OPTIONS, createClusterIcon, revealInCluster, type ClusterGroupLike } from './markerCluster'
|
||||
import RoadtripViaMarkers from './RoadtripViaMarkers'
|
||||
import HazardLayers from './HazardLayers'
|
||||
import { ALT_CASING, ALT_LABEL_TEXT } from '../Roadtrip/alternativeColors'
|
||||
@@ -61,7 +62,7 @@ import { crsForBasemap } from './gcj02Crs'
|
||||
import { isGcj02Basemap, resolveBasemap } from '../../utils/tileUrl'
|
||||
import VectorBasemap from './VectorBasemap'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { MapLayerSwitcher } from './MapLayerSwitcher'
|
||||
import { MapLayerSwitcher, MAP_LAYER_SWITCHER_INSET } from './MapLayerSwitcher'
|
||||
import { computeMapViewport, TILE_SIZE_RASTER, type ViewportPadding } from '../../utils/mapViewport'
|
||||
|
||||
function categoryIconSvg(iconName: string | null | undefined, size: number): string {
|
||||
@@ -194,7 +195,7 @@ function createPlaceIcon(place, orderNumbers, isSelected) {
|
||||
box-shadow:${shadow};
|
||||
overflow:hidden;background:${bgColor};
|
||||
">
|
||||
<img src="${escapeHtml(place.image_url)}" width="${size}" height="${size}" style="display:block;border-radius:50%;object-fit:cover;" />
|
||||
${markerPhotoHtml(place.image_url)}
|
||||
</div>
|
||||
${badgeHtml}
|
||||
</div>`,
|
||||
@@ -329,10 +330,11 @@ interface SelectionControllerProps {
|
||||
places: Place[]
|
||||
selectedPlaceId: number | null
|
||||
dayPlaces: Place[]
|
||||
selectedPlace: Place | null
|
||||
paddingOpts: L.FitBoundsOptions
|
||||
}
|
||||
|
||||
function SelectionController({ places, selectedPlaceId, dayPlaces, paddingOpts }: SelectionControllerProps) {
|
||||
function SelectionController({ places, selectedPlaceId, dayPlaces, selectedPlace, paddingOpts }: SelectionControllerProps) {
|
||||
const map = useMap()
|
||||
const prev = useRef(null)
|
||||
|
||||
@@ -342,7 +344,7 @@ function SelectionController({ places, selectedPlaceId, dayPlaces, paddingOpts }
|
||||
// side-panel + bottom-inspector padding so the pin lands in the middle of the
|
||||
// *visible* map area rather than the geometric centre (where the bottom panel
|
||||
// would cover it). Reuses the same paddingOpts the fit-bounds path uses.
|
||||
const selected = places.find(p => p.id === selectedPlaceId)
|
||||
const selected = selectedPlaceTarget(selectedPlaceId, places, dayPlaces, selectedPlace)
|
||||
if (selected?.lat != null && selected?.lng != null) {
|
||||
const latlng: [number, number] = [selected.lat, selected.lng]
|
||||
const tl = paddingOpts.paddingTopLeft as [number, number] | undefined
|
||||
@@ -356,7 +358,7 @@ function SelectionController({ places, selectedPlaceId, dayPlaces, paddingOpts }
|
||||
}
|
||||
}
|
||||
prev.current = selectedPlaceId
|
||||
}, [selectedPlaceId, places, map])
|
||||
}, [selectedPlaceId, places, dayPlaces, selectedPlace, map])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -399,15 +401,33 @@ interface BoundsControllerProps {
|
||||
* needs that leg on screen, which is neither the day nor the trip.
|
||||
*/
|
||||
focusPoints?: [number, number][]
|
||||
/**
|
||||
* What the caller's own chrome covers while `focusPoints` is framed, in pixels per edge.
|
||||
*
|
||||
* `paddingOpts` knows the planner's panels and nothing else, and on a phone it is a flat
|
||||
* margin. A shell that lays its own bars over the map passes what they cover, so the
|
||||
* frame lands in the part still visible. Only the fit on `focusPoints` reads it.
|
||||
* Compared by value: the same numbers in a new object do not refit, while new numbers
|
||||
* refit the points already handed over, because the chrome they must clear has moved.
|
||||
*/
|
||||
fitPadding?: ViewportPadding
|
||||
}
|
||||
|
||||
function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false, focusPoints }: BoundsControllerProps) {
|
||||
/** A padding box as Leaflet's fit options spell it, corner pairs rather than edges. */
|
||||
function leafletPadding(box: ViewportPadding): L.FitBoundsOptions {
|
||||
return {
|
||||
paddingTopLeft: [box.left, box.top],
|
||||
paddingBottomRight: [box.right, box.bottom],
|
||||
}
|
||||
}
|
||||
|
||||
function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false, focusPoints, fitPadding }: BoundsControllerProps) {
|
||||
const map = useMap()
|
||||
const prevFitKey = useRef(-1)
|
||||
const awaitingRoute = useRef(false)
|
||||
const fitRan = useRef(false)
|
||||
|
||||
const fitTo = useCallback((coords: [number, number][]) => {
|
||||
const fitTo = useCallback((coords: [number, number][], padding: L.FitBoundsOptions = paddingOpts) => {
|
||||
if (coords.length === 0) return
|
||||
try {
|
||||
const bounds = L.latLngBounds(coords)
|
||||
@@ -426,7 +446,7 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
|
||||
* (#1982). MapViewGL never had the nudge, so this also brings the two
|
||||
* renderers back into agreement.
|
||||
*/
|
||||
map.fitBounds(bounds, { ...paddingOpts, maxZoom: 16, animate: true })
|
||||
map.fitBounds(bounds, { ...padding, maxZoom: 16, animate: true })
|
||||
}
|
||||
} catch {}
|
||||
}, [map, paddingOpts])
|
||||
@@ -458,14 +478,18 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
|
||||
fitTo([...places.map(p => [p.lat, p.lng] as [number, number]), ...routeCoords])
|
||||
}, [routeCoords]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// The caller's padding as a value, so a parent that builds the object inline on every
|
||||
// render does not move the camera each time it renders.
|
||||
const fitPaddingKey = fitPadding ? [fitPadding.top, fitPadding.right, fitPadding.bottom, fitPadding.left].join(' ') : ''
|
||||
|
||||
// Frame whatever was handed over. Nothing happens when it empties, so closing the
|
||||
// picker leaves the map where the user left it rather than snapping back.
|
||||
useEffect(() => {
|
||||
if (!focusPoints?.length) return
|
||||
// A day fit that has not run yet must not overwrite this a moment later.
|
||||
awaitingRoute.current = false
|
||||
fitTo(focusPoints)
|
||||
}, [focusPoints]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
fitTo(focusPoints, fitPadding ? leafletPadding(fitPadding) : paddingOpts)
|
||||
}, [focusPoints, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -520,15 +544,17 @@ function MapContextMenuHandler({ onContextMenu }: { onContextMenu: ((e: L.Leafle
|
||||
|
||||
// Module-level photo cache shared with PlaceAvatar
|
||||
import { getCached, isLoading, fetchPhoto, onThumbReady, getAllThumbs } from '../../services/photoService'
|
||||
import { isCustomPlaceImage, photoCacheKey } from './placePhoto'
|
||||
import { isCustomPlaceImage, markerPhotoHtml, photoCacheKey, photoSourcesKey } from './placePhoto'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useGeolocation } from '../../hooks/useGeolocation'
|
||||
import LocationButton from './LocationButton'
|
||||
import { useIsPhone } from '../../mobile/useIsPhone'
|
||||
|
||||
// Live-location rendering inside the Leaflet map. Subscribes via the
|
||||
// shared useGeolocation hook so the Leaflet and Mapbox variants behave
|
||||
// identically. Heading is shown as a rotated conic SVG when available.
|
||||
import type { GeoPosition, TrackingMode } from '../../hooks/useGeolocation'
|
||||
import { selectedPlaceTarget } from './selectedPlaceTarget'
|
||||
|
||||
function LeafletLocationLayer({ position, mode }: { position: GeoPosition | null; mode: TrackingMode }) {
|
||||
const map = useMap()
|
||||
@@ -596,6 +622,32 @@ function LeafletLocationLayer({ position, mode }: { position: GeoPosition | null
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a place pin a drag source without losing its clicks to an old pan.
|
||||
*
|
||||
* The drag wiring swallows mousedown so the map holds still while a drag starts. Leaflet
|
||||
* tells a click from the end of a pan by a flag it only clears on the next mousedown it
|
||||
* sees, so once the map had been dragged, every click on a pin was taken for the tail of
|
||||
* that pan and dropped, until something else on the map was pressed (#2504). A press on
|
||||
* the pin now clears that flag itself, as the map would have. Switching the pan handler
|
||||
* off and on again is the public way to do that, and nothing is being panned at that
|
||||
* moment. The click then takes Leaflet's normal route, so it still closes open popups
|
||||
* and still reaches listeners further up the page, like an open context menu.
|
||||
*/
|
||||
function wireDraggablePin(el: HTMLElement, placeId: number, map: L.Map): () => void {
|
||||
const undoDrag = makeMarkerDraggable(el, placeId)
|
||||
const forgetPan = (e: MouseEvent) => {
|
||||
if (e.button !== 0 || !map.dragging.enabled()) return
|
||||
map.dragging.disable()
|
||||
map.dragging.enable()
|
||||
}
|
||||
el.addEventListener('mousedown', forgetPan)
|
||||
return () => {
|
||||
undoDrag()
|
||||
el.removeEventListener('mousedown', forgetPan)
|
||||
}
|
||||
}
|
||||
|
||||
interface MemoMarkerProps {
|
||||
place: any
|
||||
isSelected: boolean
|
||||
@@ -606,16 +658,26 @@ interface MemoMarkerProps {
|
||||
onHoverOut: () => void
|
||||
/** Off in read-only trips and on the phone, where HTML5 drag does not exist. */
|
||||
draggable: boolean
|
||||
/** Hands the Leaflet marker up, so a selection can find the bubble it is hiding in. */
|
||||
onRegister: (id: number, marker: unknown) => void
|
||||
}
|
||||
|
||||
const MemoMarker = memo(function MemoMarker({
|
||||
place, isSelected, orderNumbers, photoUrl, onClickPlace, onHover, onHoverOut, draggable,
|
||||
place, isSelected, orderNumbers, photoUrl, onClickPlace, onHover, onHoverOut, draggable, onRegister,
|
||||
}: MemoMarkerProps) {
|
||||
const icon = createPlaceIcon({ ...place, image_url: photoUrl }, orderNumbers, isSelected)
|
||||
const map = useMap()
|
||||
const cleanupRef = useRef<(() => void) | null>(null)
|
||||
// react-leaflet compares `position` by reference and calls setLatLng whenever it
|
||||
// differs, and the cluster group answers a moved child by taking it out and putting
|
||||
// it back — which collapses an open fan. A fresh array literal here did that on
|
||||
// every render the marker took part in.
|
||||
const position = useMemo<[number, number]>(() => [place.lat, place.lng], [place.lat, place.lng])
|
||||
const register = useCallback((marker: unknown) => { onRegister(place.id, marker) }, [onRegister, place.id])
|
||||
return (
|
||||
<Marker
|
||||
position={[place.lat, place.lng]}
|
||||
ref={register}
|
||||
position={position}
|
||||
icon={icon}
|
||||
eventHandlers={{
|
||||
// The element only exists once Leaflet has put the marker on the map,
|
||||
@@ -623,7 +685,7 @@ const MemoMarker = memo(function MemoMarker({
|
||||
// so the wiring is redone on every add rather than once on mount.
|
||||
add: (e: any) => {
|
||||
cleanupRef.current?.()
|
||||
cleanupRef.current = draggable ? makeMarkerDraggable(e.target.getElement() as HTMLElement, place.id) : null
|
||||
cleanupRef.current = draggable ? wireDraggablePin(e.target.getElement() as HTMLElement, place.id, map) : null
|
||||
},
|
||||
remove: () => { cleanupRef.current?.(); cleanupRef.current = null },
|
||||
click: () => onClickPlace(place.id),
|
||||
@@ -645,6 +707,8 @@ export const MapView = memo(function MapView({
|
||||
routeColors = null,
|
||||
routeSegments = [],
|
||||
selectedPlaceId = null,
|
||||
// The selected place itself, for when no pin on this map stands for it.
|
||||
selectedPlace = null,
|
||||
hoverDisabled = false,
|
||||
onMarkerClick,
|
||||
onMapClick,
|
||||
@@ -666,6 +730,9 @@ export const MapView = memo(function MapView({
|
||||
showTransitRoutes = true,
|
||||
days = [] as Day[],
|
||||
selectedDayId = null,
|
||||
// Whether a booking switched on by hand also has to run on the selected day to be
|
||||
// drawn. Only the phone's plan map asks for it; see RouteVisibilityOptions.
|
||||
scopeConnectionsToDay = false,
|
||||
onReservationClick,
|
||||
pois = [] as Poi[],
|
||||
onPoiClick,
|
||||
@@ -685,6 +752,7 @@ export const MapView = memo(function MapView({
|
||||
onRemoveVia,
|
||||
alternativeRoutes,
|
||||
focusPoints,
|
||||
fitPadding,
|
||||
clusterLoosely = false,
|
||||
activeAlternative,
|
||||
onChooseAlternative,
|
||||
@@ -728,8 +796,8 @@ export const MapView = memo(function MapView({
|
||||
</Marker>
|
||||
)), [pois, onPoiClick, onPoiDropOnRoute])
|
||||
const visibleReservations = useMemo(() => (
|
||||
visibleRouteReservations(reservations, { visibleConnectionIds, showTransitRoutes, selectedDayId, days })
|
||||
), [reservations, visibleConnectionIds, showTransitRoutes, selectedDayId, days])
|
||||
visibleRouteReservations(reservations, { visibleConnectionIds, showTransitRoutes, selectedDayId, days, scopeConnectionsToDay })
|
||||
), [reservations, visibleConnectionIds, showTransitRoutes, selectedDayId, days, scopeConnectionsToDay])
|
||||
// Real road geometry for car/bus/taxi/bicycle bookings (straight line until it loads/if it fails).
|
||||
const transportRoutes = useTransportRoutes(visibleReservations)
|
||||
// Dynamic padding: account for sidebars + bottom inspector + day detail panel
|
||||
@@ -746,10 +814,7 @@ export const MapView = memo(function MapView({
|
||||
}
|
||||
}, [leftWidth, rightWidth, hasInspector, hasDayDetail])
|
||||
|
||||
const paddingOpts = useMemo((): L.FitBoundsOptions => ({
|
||||
paddingTopLeft: [paddingBox.left, paddingBox.top],
|
||||
paddingBottomRight: [paddingBox.right, paddingBox.bottom],
|
||||
}), [paddingBox])
|
||||
const paddingOpts = useMemo(() => leafletPadding(paddingBox), [paddingBox])
|
||||
|
||||
// Open framed on the places rather than on the caller's default, so a trip in Japan shows
|
||||
// Japan straight away instead of the world view followed by a flight across the planet.
|
||||
@@ -817,7 +882,7 @@ export const MapView = memo(function MapView({
|
||||
const pendingThumbsRef = useRef<Record<string, string>>({})
|
||||
const thumbRafRef = useRef<number | null>(null)
|
||||
|
||||
const placeIds = useMemo(() => places.map(p => p.id).join(','), [places])
|
||||
const photoSources = useMemo(() => photoSourcesKey(places), [places])
|
||||
// Flattened [lat,lng] points of the selected day's route, so the bounds fit can
|
||||
// include the full polyline once it has been computed.
|
||||
const routeCoords = useMemo<[number, number][]>(() => (route || []).flat() as [number, number][], [route])
|
||||
@@ -874,23 +939,46 @@ export const MapView = memo(function MapView({
|
||||
thumbRafRef.current = null
|
||||
}
|
||||
}
|
||||
}, [placeIds, placesPhotosEnabled])
|
||||
|
||||
const clusterIconCreateFunction = useCallback((cluster) => {
|
||||
const count = cluster.getChildCount()
|
||||
const size = count < 10 ? 36 : count < 50 ? 42 : 48
|
||||
return L.divIcon({
|
||||
html: `<div class="marker-cluster-custom" style="width:${size}px;height:${size}px;"><span>${count}</span></div>`,
|
||||
className: 'marker-cluster-wrapper',
|
||||
iconSize: L.point(size, size),
|
||||
})
|
||||
}, [])
|
||||
}, [photoSources, placesPhotosEnabled])
|
||||
|
||||
const isTouchDevice = typeof window !== 'undefined' && navigator.maxTouchPoints > 0
|
||||
// Drag a marker onto a day (#891). Pointer-driven, so it is off wherever
|
||||
// HTML5 drag does not exist — and the day plan is not on screen there anyway.
|
||||
const markersDraggable = !isTouchDevice
|
||||
|
||||
/**
|
||||
* Reaching a stop that shares its coordinates with others.
|
||||
*
|
||||
* Such a stop has no pin of its own while the stack is collapsed — it is inside a
|
||||
* cluster bubble — so the z-index that used to lift the selected pin out of the pile
|
||||
* has nothing to lift. Fan the bubble open instead, which leaves the camera alone
|
||||
* (#2344). The registry is what lets a selection find its Leaflet marker at all.
|
||||
*/
|
||||
const clusterGroupRef = useRef<ClusterGroupLike | null>(null)
|
||||
const placeMarkersRef = useRef(new Map<number, unknown>())
|
||||
const registerClusterGroup = useCallback((group: unknown) => {
|
||||
clusterGroupRef.current = (group as ClusterGroupLike | null) ?? null
|
||||
}, [])
|
||||
const registerMarker = useCallback((id: number, marker: unknown) => {
|
||||
if (marker) placeMarkersRef.current.set(id, marker)
|
||||
else placeMarkersRef.current.delete(id)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedPlaceId == null) return
|
||||
let frame: number | null = null
|
||||
const reveal = () => {
|
||||
frame = null
|
||||
revealInCluster(clusterGroupRef.current, placeMarkersRef.current.get(selectedPlaceId))
|
||||
}
|
||||
reveal()
|
||||
// The group takes its markers in on a microtask and adds them in chunks, so a
|
||||
// selection that arrives with the map — a link straight into a day — finds nothing
|
||||
// on the first pass. A second attempt one frame later does.
|
||||
if (typeof requestAnimationFrame === 'function') frame = requestAnimationFrame(reveal)
|
||||
return () => { if (frame !== null) cancelAnimationFrame(frame) }
|
||||
}, [selectedPlaceId, places])
|
||||
|
||||
const markers = useMemo(() => places.map((place) => {
|
||||
const isSelected = place.id === selectedPlaceId
|
||||
const pck = photoCacheKey(place)
|
||||
@@ -908,9 +996,10 @@ export const MapView = memo(function MapView({
|
||||
onHover={handleMarkerHover}
|
||||
onHoverOut={handleMarkerHoverOut}
|
||||
draggable={markersDraggable}
|
||||
onRegister={registerMarker}
|
||||
/>
|
||||
)
|
||||
}), [places, selectedPlaceId, dayOrderMap, photoUrls, handleMarkerClick, handleMarkerHover, handleMarkerHoverOut, markersDraggable])
|
||||
}), [places, selectedPlaceId, dayOrderMap, photoUrls, handleMarkerClick, handleMarkerHover, handleMarkerHoverOut, markersDraggable, registerMarker])
|
||||
|
||||
// Parsing track geometry is the expensive part (tracks run to tens of thousands
|
||||
// of points), so it hangs off `places` alone — a selection change must not
|
||||
@@ -979,7 +1068,10 @@ export const MapView = memo(function MapView({
|
||||
const { position: userPosition, mode: trackingMode, error: trackingError, errorCode: trackingErrorCode, cycleMode: cycleTrackingMode } = useGeolocation()
|
||||
// Desktop browsers only get IP-based geolocation (city-level accuracy),
|
||||
// so the button would be misleading. Mobile, where real GPS lives, keeps it.
|
||||
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768
|
||||
// The width is followed rather than read once: a phone turned sideways and
|
||||
// back crosses the breakpoint twice, and the button used to stay with
|
||||
// whatever the map saw when it mounted.
|
||||
const isMobile = useIsPhone()
|
||||
// When the day-detail panel is open it slides up over the map (bottom: navh+20,
|
||||
// height var(--day-panel-h)) and covers the button's band, so lift the button
|
||||
// above it; otherwise keep the plain bottom-nav offset. #1348
|
||||
@@ -1068,8 +1160,8 @@ export const MapView = memo(function MapView({
|
||||
)}
|
||||
|
||||
<MapController center={center} zoom={zoom} />
|
||||
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} />
|
||||
<SelectionController places={places} selectedPlaceId={selectedPlaceId} dayPlaces={dayPlaces} paddingOpts={paddingOpts} />
|
||||
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} fitPadding={fitPadding} />
|
||||
<SelectionController places={places} selectedPlaceId={selectedPlaceId} dayPlaces={dayPlaces} selectedPlace={selectedPlace} paddingOpts={paddingOpts} />
|
||||
<MapClickHandler onClick={onMapClick} />
|
||||
<MapContextMenuHandler onContextMenu={onMapContextMenu} />
|
||||
<CameraHoverGuard movingRef={mapMovingRef} onMoveStart={clearHover} onZoom={setMapZoom} />
|
||||
@@ -1077,18 +1169,7 @@ export const MapView = memo(function MapView({
|
||||
<PoiDropTarget onPoiDropOnRoute={onPoiDropOnRoute} />
|
||||
<LeafletLocationLayer position={userPosition} mode={trackingMode} />
|
||||
|
||||
<MarkerClusterGroup
|
||||
chunkedLoading
|
||||
chunkInterval={30}
|
||||
chunkDelay={0}
|
||||
maxClusterRadius={20}
|
||||
disableClusteringAtZoom={9}
|
||||
spiderfyOnMaxZoom
|
||||
showCoverageOnHover={false}
|
||||
zoomToBoundsOnClick
|
||||
animate={false}
|
||||
iconCreateFunction={clusterIconCreateFunction}
|
||||
>
|
||||
<MarkerClusterGroup ref={registerClusterGroup} {...CLUSTER_OPTIONS} iconCreateFunction={createClusterIcon}>
|
||||
{markers}
|
||||
</MarkerClusterGroup>
|
||||
|
||||
@@ -1242,7 +1323,7 @@ export const MapView = memo(function MapView({
|
||||
top of the map, which read as the control moving house rather than as room being
|
||||
made: the inspector is a centred card at most 800 wide, so the corner it would
|
||||
have been clearing is one the card never reaches. */}
|
||||
<div style={{ position: 'absolute', left: leftWidth + 20, bottom: switcherBottom, zIndex: 1000, pointerEvents: 'none' }}>
|
||||
<div style={{ position: 'absolute', left: leftWidth + MAP_LAYER_SWITCHER_INSET, bottom: switcherBottom, zIndex: 1000, pointerEvents: 'none' }}>
|
||||
<MapLayerSwitcher active={baseLayer} onToggle={toggleBaseLayer} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user