diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 47d23772a..ab2ea9a46 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -25,6 +25,13 @@ updates: groups: npm-minor-and-patch: update-types: [minor, patch] + ignore: + # TypeScript 7 is the native compiler and has no JavaScript API yet: + # typescript-eslint, the coverage instrumenter and the Postgres probe all + # call into it (readConfigFile, ScriptTarget). It moves by hand once the + # tooling supports it. + - dependency-name: typescript + update-types: [version-update:semver-major] # plugin-sdk is standalone with a lockfile of its own and ships to npm. - package-ecosystem: npm diff --git a/.github/workflows/docker-dev.yml b/.github/workflows/docker-dev.yml index 4141f4bd1..183ca31c3 100644 --- a/.github/workflows/docker-dev.yml +++ b/.github/workflows/docker-dev.yml @@ -175,7 +175,7 @@ jobs: - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} @@ -236,7 +236,7 @@ jobs: - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 3f788a3ef..0d09a7893 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -140,7 +140,9 @@ jobs: set -eu # Derive version from git tags, no package.json dependency - STABLE_TAG=$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' | grep -v '\-pre\.' | sort -V | tail -1) + # Only a plain vX.Y.Z is a release: the glob alone also matches the apps' TestFlight tags + # (v5.1.0-tf.15), whose suffix then broke the arithmetic below. + STABLE_TAG=$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1) STABLE="${STABLE_TAG#v}" STABLE="${STABLE:-0.0.0}" @@ -342,7 +344,7 @@ jobs: - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} @@ -401,7 +403,7 @@ jobs: - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} diff --git a/.github/workflows/native-release.yml b/.github/workflows/native-release.yml new file mode 100644 index 000000000..62abf81cc --- /dev/null +++ b/.github/workflows/native-release.yml @@ -0,0 +1,196 @@ +name: Native apps release + +# Builds the signed store builds of the iOS and Android apps and uploads them: +# the Android App Bundle to a Google Play testing track, the iOS archive to +# App Store Connect (TestFlight). Promotion to production stays a manual step +# in both consoles. +# +# Runs only in liketrek/TREK, only by hand or on a version tag, and only after a +# required reviewer approves the `store` environment, which holds every secret +# (see wiki/Native-Apps.md for the list). Pull requests never reach it. +# +# Both stores get the same numbers: the version from client/package.json +# without a prerelease suffix, and a build number that only grows. A prerelease +# reuses its X.Y.Z with a higher build number and belongs on the internal track +# and in TestFlight only. + +on: + workflow_dispatch: + inputs: + track: + description: Google Play track + type: choice + options: [internal, alpha, beta] + default: internal + push: + tags: ['v*'] + +permissions: + contents: read + +concurrency: + group: native-release + cancel-in-progress: false + +jobs: + android: + # Gated on a repository variable so the release can ship iOS alone while the + # Google Play account and its signing secrets are not yet in place. Set the + # repository variable NATIVE_RELEASE_ANDROID to 1 to turn the Android half on. + if: github.repository == 'liketrek/TREK' && vars.NATIVE_RELEASE_ANDROID == '1' + runs-on: ubuntu-24.04 + timeout-minutes: 40 + environment: store + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: npm + + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: 21 + cache: gradle + + - name: Version and build number + id: version + run: | + echo "version=$(node -p "require('./client/package.json').version.split('-')[0]")" >> "$GITHUB_OUTPUT" + echo "build=$((GITHUB_RUN_NUMBER + 1000))" >> "$GITHUB_OUTPUT" + + - name: Install + run: npm ci --workspace=shared --workspace=client + + - name: Build shared + run: npm run build --workspace=shared + + - name: Build the address screen and sync it into the shell + working-directory: client + run: npm run cap:sync -- android + + - name: Upload key + env: + KEYSTORE_B64: ${{ secrets.ANDROID_UPLOAD_KEYSTORE_B64 }} + run: printf '%s' "$KEYSTORE_B64" | base64 -d > "$RUNNER_TEMP/upload.jks" + + - name: Build the signed App Bundle + working-directory: client/android + env: + ORG_GRADLE_PROJECT_trekKeystorePassword: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ORG_GRADLE_PROJECT_trekKeyAlias: ${{ secrets.ANDROID_KEY_ALIAS }} + ORG_GRADLE_PROJECT_trekKeyPassword: ${{ secrets.ANDROID_KEY_PASSWORD }} + run: >- + ./gradlew bundleRelease --no-daemon + -PtrekVersionName=${{ steps.version.outputs.version }} + -PtrekVersionCode=${{ steps.version.outputs.build }} + -PtrekKeystore="$RUNNER_TEMP/upload.jks" + + - uses: actions/upload-artifact@v6 + with: + name: trek-android-${{ steps.version.outputs.version }}-${{ steps.version.outputs.build }} + path: client/android/app/build/outputs/bundle/release/app-release.aab + retention-days: 30 + + # Play only accepts API uploads once one bundle was uploaded by hand + # (wiki/Native-Apps.md). `draft` until the app has left draft in the console. + - name: Upload to Google Play + uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5 # v1.1.5 + with: + serviceAccountJsonPlainText: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }} + packageName: com.liketrek.trek + releaseFiles: client/android/app/build/outputs/bundle/release/app-release.aab + track: ${{ inputs.track || 'internal' }} + status: draft + + - name: Remove the upload key + if: always() + run: rm -f "$RUNNER_TEMP/upload.jks" + + ios: + if: github.repository == 'liketrek/TREK' + runs-on: xcode-27 + timeout-minutes: 60 + environment: store + steps: + - uses: actions/checkout@v6 + + # The iOS 27.1 SDK, on the xcode-27 image: an app built against an older SDK + # runs letterboxed on the inner display of an iPhone Duo. + - name: Select Xcode 27.1 + run: | + XCODE=/Applications/Xcode_27.1.app + test -d "$XCODE" + sudo xcode-select -s "$XCODE" + xcodebuild -version + xcodebuild -showsdks | grep iphoneos27.1 + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: npm + + - name: Version and build number + id: version + run: | + echo "version=$(node -p "require('./client/package.json').version.split('-')[0]")" >> "$GITHUB_OUTPUT" + echo "build=$((GITHUB_RUN_NUMBER + 1000))" >> "$GITHUB_OUTPUT" + + - name: Install + run: npm ci --workspace=shared --workspace=client + + - name: Build shared + run: npm run build --workspace=shared + + - name: Build the address screen and sync it into the shell + working-directory: client + run: npm run cap:sync -- ios + + - name: App Store Connect API key + env: + ASC_KEY_P8_B64: ${{ secrets.ASC_KEY_P8_B64 }} + run: printf '%s' "$ASC_KEY_P8_B64" | base64 -d > "$RUNNER_TEMP/AuthKey.p8" + + - name: Distribution certificate + env: + APPLE_DIST_CERT_P12_B64: ${{ secrets.APPLE_DIST_CERT_P12_B64 }} + run: printf '%s' "$APPLE_DIST_CERT_P12_B64" | base64 -d > "$RUNNER_TEMP/dist.p12" + + # Signs for distribution and uploads to TestFlight. Automatic signing cannot + # run on a device-less CI runner (it signs for development and then needs a + # development profile, which needs a registered device), so client/fastlane/Fastfile + # imports the stored distribution certificate and creates the App Store profile + # through the API key. + # The tag's message, past its subject line, is what testers read under + # "What to Test": one short line per change worth trying. + - name: TestFlight notes from the tag + if: startsWith(github.ref, 'refs/tags/') + run: | + git fetch --force --depth=1 origin "+${GITHUB_REF}:${GITHUB_REF}" + { + echo 'TESTFLIGHT_NOTES<> "$GITHUB_ENV" + + - name: Build and upload to TestFlight + working-directory: client + env: + ASC_KEY_ID: ${{ secrets.ASC_KEY_ID }} + ASC_ISSUER_ID: ${{ secrets.ASC_ISSUER_ID }} + ASC_KEY_PATH: ${{ runner.temp }}/AuthKey.p8 + CERT_P12_PATH: ${{ runner.temp }}/dist.p12 + CERT_P12_PASSWORD: ${{ secrets.APPLE_DIST_CERT_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + MARKETING_VERSION: ${{ steps.version.outputs.version }} + CURRENT_PROJECT_VERSION: ${{ steps.version.outputs.build }} + FASTLANE_SKIP_UPDATE_CHECK: '1' + FASTLANE_HIDE_CHANGELOG: '1' + run: fastlane ios beta + + - name: Remove secrets + if: always() + run: rm -f "$RUNNER_TEMP/AuthKey.p8" "$RUNNER_TEMP/dist.p12" diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml new file mode 100644 index 000000000..734e8a923 --- /dev/null +++ b/.github/workflows/native.yml @@ -0,0 +1,279 @@ +name: Native apps + +permissions: + contents: read + +# Builds the iOS and Android shells whenever they, their address screen or the +# Capacitor plugins change. Nobody on the team has to own a Mac for the Swift +# side to be compiled on every change, and every run leaves a debug APK to +# install on a phone. +# +# Unsigned on purpose: signing and store uploads need secrets that fork PRs do +# not get, and belong in a release workflow of their own. +on: + pull_request: + paths: + - 'client/android/**' + - 'client/ios/**' + - 'client/native-shell/**' + - 'client/src/native/trekShell.ts' + - 'client/src/native/watch.ts' + - 'client/src/native/serverAddress.ts' + - 'client/capacitor.config.ts' + - 'client/vite.native.config.js' + - 'client/scripts/check-store-metadata.mjs' + - 'client/fastlane/**' + - 'client/package.json' + - 'package-lock.json' + - 'shared/src/i18n/*/native.ts' + - '.github/workflows/native.yml' + workflow_dispatch: + +concurrency: + group: native-${{ github.ref }} + cancel-in-progress: true + +jobs: + # The store texts fit their limits and every listing image has its size and + # no alpha channel (client/fastlane/README.md). Plain Node, no install. + metadata: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + + - name: Check the store listings + run: node client/scripts/check-store-metadata.mjs + + android: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: npm + + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: 21 + cache: gradle + + - name: Install + run: npm ci --workspace=shared --workspace=client + + - name: Build shared + run: npm run build --workspace=shared + + - name: Build the address screen and sync it into the shells + working-directory: client + run: npm run cap:sync -- android + + # The release build runs R8 with the keep rules in proguard-rules.pro, so a + # rule that goes missing fails here rather than in the store build. It is + # unsigned: the upload key only exists in native-release.yml. + - name: Assemble debug and release APKs + working-directory: client/android + run: ./gradlew assembleDebug assembleRelease lintDebug testDebugUnitTest --no-daemon + + - uses: actions/upload-artifact@v6 + with: + name: trek-android-debug + path: client/android/app/build/outputs/apk/debug/app-debug.apk + retention-days: 14 + + ios: + runs-on: xcode-27 + timeout-minutes: 40 + steps: + - uses: actions/checkout@v6 + + # The iOS 27.1 SDK, on the xcode-27 image: an app built against an older SDK + # runs letterboxed on the inner display of an iPhone Duo. + - name: Select Xcode 27.1 + run: | + XCODE=/Applications/Xcode_27.1.app + test -d "$XCODE" + sudo xcode-select -s "$XCODE" + xcodebuild -version + xcodebuild -showsdks | grep iphoneos27.1 + + - name: Check the property lists + run: plutil -lint client/ios/App/App/Info.plist client/ios/ExportOptions.plist client/ios/App/NotificationService/Info.plist client/ios/App/NotificationService/NotificationService.entitlements client/ios/App/App/App.entitlements client/ios/App/TREKWidgets/Info.plist client/ios/App/TREKWidgets/TREKWidgets.entitlements client/ios/App/TREKWidgets/*.lproj/Localizable.strings client/ios/App/ShareExtension/Info.plist client/ios/App/ShareExtension/ShareExtension.entitlements client/ios/App/ShareExtension/*.lproj/Localizable.strings client/ios/App/TREKWatch/Info.plist client/ios/App/TREKWatch/TREKWatch.entitlements client/ios/App/TREKWatch/*.lproj/Localizable.strings client/ios/App/TREKWatchWidgets/Info.plist client/ios/App/TREKWatchWidgets/TREKWatchWidgets.entitlements + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: npm + + - name: Install + run: npm ci --workspace=shared --workspace=client + + - name: Build shared + run: npm run build --workspace=shared + + - name: Build the address screen and sync it into the shells + working-directory: client + run: npm run cap:sync -- ios + + # Capacitor's xcframeworks come from GitHub release downloads, which answer + # 504 now and then; SwiftPM then reports the half-written file as "already + # exists in file system". Resolve on a clean artifact cache, a few times + # with growing pauses, before the build needs the packages. + - name: Resolve the Swift packages + working-directory: client/ios/App + run: | + for attempt in 1 2 3 4 5; do + rm -rf ~/Library/Caches/org.swift.swiftpm/artifacts + if xcodebuild -resolvePackageDependencies -project App.xcodeproj -scheme App; then exit 0; fi + echo "Resolving the Swift packages failed (attempt $attempt of 5)" + sleep $((attempt * 30)) + done + exit 1 + + # No -sdk: the scheme builds the embedded watch app and its complications + # against the watchOS simulator SDK and the rest against the iOS one. + - name: Build for the simulator + working-directory: client/ios/App + run: | + xcodebuild build \ + -project App.xcodeproj \ + -scheme App \ + -configuration Debug \ + -destination 'generic/platform=iOS Simulator' \ + CODE_SIGNING_ALLOWED=NO + + # The widgets drawn to PNGs (client/ios/WidgetPreviews): every size, light and + # dark, for a trip ahead, a trip under way and none, plus a home screen and + # a lock screen of them. Nobody has to install a build to see a widget change. + # Started by hand only (Run workflow): the apps are on TestFlight and Play now, + # where a change is looked at on a device; on every PR it only held the queue. + widget-previews: + if: github.event_name == 'workflow_dispatch' + runs-on: macos-15 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + + - name: Select Xcode 26 + run: | + XCODE=$(ls -d /Applications/Xcode_26*.app | sort -V | tail -1) + test -n "$XCODE" + sudo xcode-select -s "$XCODE" + + - name: Render the widgets + working-directory: client/ios/WidgetPreviews + run: | + mkdir -p Sources/WidgetPreviews/Widgets + cp ../App/TREKWidgets/WidgetSnapshot.swift ../App/TREKWidgets/TrekStyle.swift ../App/TREKWidgets/TrekFamily.swift ../App/TREKWidgets/WorldGrid.swift \ + ../App/TREKWidgets/*Content.swift Sources/WidgetPreviews/Widgets/ + swift run -c release WidgetPreviews out "$PWD/../App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png" + + - uses: actions/upload-artifact@v6 + with: + name: widget-previews + path: client/ios/WidgetPreviews/out + retention-days: 14 + + # The watch's half in the UI (client/src/native/watch.ts): the snapshot it + # builds and the ticks it takes back, typechecked and tested here as well, + # so a change to the bridge is checked next to the Swift that reads it. + watch-bridge: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: npm + + - name: Install + run: npm ci --workspace=shared --workspace=client + + - name: Build shared + run: npm run build --workspace=shared + + - name: Typecheck the client + working-directory: client + run: npm run typecheck + + - name: Test the widget and watch snapshots + working-directory: client + run: npx vitest run src/native/watch.test.ts src/native/widgets.test.ts src/native/widgetExtras.test.ts + + # The watch app on watchOS simulators in its screenshot mode (DemoMode.swift): + # every screen on the largest and the smallest watch, the main ones in every + # language, and the complications, as PNGs to look at without a watch. + # Started by hand only, like the widget previews: up to 90 minutes of macOS. + watch-screens: + if: github.event_name == 'workflow_dispatch' + runs-on: macos-15 + timeout-minutes: 90 + steps: + - uses: actions/checkout@v6 + + - name: Select Xcode 26 + run: | + XCODE=$(ls -d /Applications/Xcode_26*.app | sort -V | tail -1) + test -n "$XCODE" + sudo xcode-select -s "$XCODE" + + # The project resolves the Capacitor packages from node_modules, even for + # a target that uses none of them. + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: npm + + - name: Install + run: npm ci --workspace=shared --workspace=client + + - name: Make sure a watchOS simulator runtime is there + run: | + xcrun simctl list runtimes | grep -q watchOS || xcodebuild -downloadPlatform watchOS + xcrun simctl list runtimes + + # Capacitor's xcframeworks come from GitHub release downloads, which answer + # 504 now and then; SwiftPM then reports the half-written file as "already + # exists in file system". Resolve on a clean artifact cache, a few times + # with growing pauses, before the build needs the packages. + - name: Resolve the Swift packages + working-directory: client/ios/App + run: | + for attempt in 1 2 3 4 5; do + rm -rf ~/Library/Caches/org.swift.swiftpm/artifacts + if xcodebuild -resolvePackageDependencies -project App.xcodeproj -scheme App; then exit 0; fi + echo "Resolving the Swift packages failed (attempt $attempt of 5)" + sleep $((attempt * 30)) + done + exit 1 + + - name: Build the watch app for the simulator + working-directory: client/ios/App + run: | + xcodebuild build \ + -project App.xcodeproj \ + -target TREKWatch \ + -configuration Debug \ + -sdk watchsimulator \ + SYMROOT="$PWD/build" \ + CODE_SIGNING_ALLOWED=NO + + - name: Capture the screens + run: bash client/ios/scripts/watch-screens.sh client/ios/App/build/Debug-watchsimulator/TREKWatch.app "$PWD/watch-screens" + + - uses: actions/upload-artifact@v6 + if: always() + with: + name: watch-screens + path: watch-screens + retention-days: 14 diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index a3dc55129..d1bd3a20d 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -74,7 +74,7 @@ jobs: load: true tags: trek:scan - - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ff3b12459..33f54c7d8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -473,7 +473,10 @@ jobs: # tsconfig.strict.json is the same program with strictNullChecks and # noImplicitAny; its errors per file may not rise above # scripts/strict-baseline.json, and a file without an entry, every new - # one included, has to be clean (scripts/strict-lint.mjs). + # one included, has to be clean (scripts/strict-lint.mjs). It holds the + # whole program with strict checks, past Node's default ~4 GB heap. + env: + NODE_OPTIONS: --max-old-space-size=8192 run: cd client && npm run lint:strict - name: Page pattern check @@ -1159,7 +1162,7 @@ jobs: path: plugin-sdk/coverage/ - name: Scan - uses: SonarSource/sonarqube-scan-action@4d1dc0c91ee400dcf8a6dddf2f705ac36542e304 # v8.4.0 + uses: SonarSource/sonarqube-scan-action@59202af334b4ba7b5db01b701b8e79f8b3bef0f4 # v8.5.0 env: # SonarQube Cloud is the scan action's default host, so no # SONAR_HOST_URL — the token is a sonarcloud.io token for the @@ -1357,10 +1360,12 @@ jobs: bin="$RUNNER_TEMP/bin" mkdir -p "$bin" cd "$RUNNER_TEMP" - curl -sSfLo helm.tgz "https://get.helm.sh/helm-$HELM_VERSION-linux-amd64.tar.gz" + # GitHub's release downloads answer 504 now and then: retry, the checksum still decides. + fetch() { curl -sSfL --retry 5 --retry-delay 15 --retry-all-errors -o "$1" "$2"; } + fetch helm.tgz "https://get.helm.sh/helm-$HELM_VERSION-linux-amd64.tar.gz" echo "$HELM_SHA256 helm.tgz" | sha256sum -c - tar -xzf helm.tgz --strip-components=1 -C "$bin" linux-amd64/helm - curl -sSfLo kubeconform.tgz "https://github.com/yannh/kubeconform/releases/download/$KUBECONFORM_VERSION/kubeconform-linux-amd64.tar.gz" + fetch kubeconform.tgz "https://github.com/yannh/kubeconform/releases/download/$KUBECONFORM_VERSION/kubeconform-linux-amd64.tar.gz" echo "$KUBECONFORM_SHA256 kubeconform.tgz" | sha256sum -c - tar -xzf kubeconform.tgz -C "$bin" kubeconform echo "$bin" >> "$GITHUB_PATH" @@ -1395,6 +1400,10 @@ jobs: --set httpRoute.enabled=true \ --set 'httpRoute.parentRefs[0].name=gateway' \ > "$out/http-route.yaml" + helm template trek charts/trek \ + --set 'persistence.data.accessModes[0]=ReadWriteMany' \ + --set 'persistence.uploads.accessModes[0]=ReadWriteMany' \ + > "$out/access-modes.yaml" helm template trek charts/trek \ --set podSecurityContext.runAsUser=1000 \ --set podSecurityContext.runAsGroup=1000 \ diff --git a/Dockerfile b/Dockerfile index 069b15b44..e6ab8b731 100644 --- a/Dockerfile +++ b/Dockerfile @@ -70,12 +70,15 @@ COPY server/package.json ./server/ # 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. +# The upgrade takes the Debian security fixes the base image was built before +# (zlib, 11/2026, failed the image scan until node:24-trixie-slim caught up). # # postgresql-client-17 (Debian 13's own) brings pg_dump and pg_restore to # /usr/lib/postgresql/17/bin, which back up an install on Postgres # (TREK_DB_URL). pg_dump refuses a server newer than itself, so it stays at the # newest major TREK supports. RUN apt-get update && \ + apt-get upgrade -y --no-install-recommends && \ apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \ libkitinerary-bin libsqlite3-0 postgresql-client-17 && \ npm ci --workspace=server --omit=dev --ignore-scripts && \ diff --git a/NOTICE.md b/NOTICE.md index 8a0a6ed79..3b7eb3b02 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -20,7 +20,23 @@ geoBoundaries is licensed under **CC BY 4.0** The bundled files are simplified (coordinate-quantized) and re-tagged with the property names TREK consumes. Country borders (`admin0`) derive from the geoBoundaries CGAZ composite; sub-national regions (`admin1`) derive from the per-country open -(gbOpen) release. +(gbOpen) release, except for Ireland (below). + +## Tailte Éireann — counties of Ireland + +Ireland's regions in the same files (`admin1/IE.geojson.gz`, and its features in +`admin1.geojson.gz`) are the 26 counties from Tailte Éireann's *Counties - National +Statutory Boundaries - 2019 - Generalised 20m*, because geoBoundaries has no county +layer for Ireland. + +Contains Tailte Éireann data, © Tailte Éireann, licensed under **CC BY 4.0** +(https://creativecommons.org/licenses/by/4.0/). Source: +https://data-osi.opendata.arcgis.com/ + +The outlines are simplified, coordinate-quantized and re-tagged with ISO 3166-2:IE +codes by `server/scripts/build-atlas-geo.mjs`. Tailte Éireann publishes the +generalised boundaries for reference only; they may not match the statutory +boundaries exactly. ## OpenStreetMap — geocoding, place details & descriptions diff --git a/README.md b/README.md index 421f5face..7d90c3a1d 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu #### 🗺️ Atlas, Vacay and Collections - **Atlas**: countries and regions visited on [geoBoundaries](https://www.geoboundaries.org/) outlines, a bucket list, travel stats, and a tour activities tab with planned against recorded totals -- **Vacay**: leave calendar with half days, public holidays from date.nager.at, school holidays for 16 European countries, company holidays, carry-over between years, and joint or read-only sharing +- **Vacay**: leave calendar with half days, public holidays from [nagerholidays.com](https://nagerholidays.com), school holidays for 16 European countries, company holidays, carry-over between years, and joint or read-only sharing - **Collections** (off by default): a place library outside any trip with lists, labels, ratings, a status per place, cover images, GPX and file export, copy into a trip, and sharing by invite - **Dawarich** (off by default): link a Dawarich instance for recorded tracks, suggested stays and countries for the Atlas @@ -182,7 +182,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu #### 📱 Mobile and offline -- **Installable**: iOS and Android straight from the browser, no App Store, standalone with a themed status bar +- **Apps**: TREK Travel Planner for iPhone, iPad and Android connects to any TREK server, and the browser installs TREK as a standalone app with a themed status bar too - **Phone layouts**: their own screens for every part of the app, with a bottom bar and dashboard widgets the user orders - **Offline reads**: the app shell is precached and trips, places, tours, files and nearby places live in a per-user IndexedDB store, so a trip opens with no network - **Offline writes**: changes queue and replay with an `X-Idempotency-Key`, and a stale edit waits for a keep-mine or keep-theirs choice @@ -276,6 +276,8 @@ Open `http://localhost:3000`, or `http://:3000` from another machine. `COOKIE_SECURE=false` is only for trying TREK over plain HTTP: without it the browser drops the session cookie and the login does not stick. Once TREK sits behind HTTPS (see [Reverse Proxy](#reverse-proxy)), remove it. +**TrueNAS SCALE:** Install TREK directly from the Community catalog. See the [TrueNAS SCALE installation guide](https://github.com/liketrek/TREK/wiki/Install-TrueNAS-SCALE). + > [!TIP] > **No server yet?** TREK's own public services run on [**dataforest cloud**](https://cloud.dataforest.net/en?mtm_campaign=trek), our infrastructure sponsor. A small seed is plenty for a TREK instance and is ready within a minute. @@ -339,7 +341,7 @@ See [`charts/README.md`](https://github.com/liketrek/TREK/blob/main/charts/READM

Install as App (PWA)

-TREK works as a Progressive Web App — no App Store needed. +TREK works as a Progressive Web App, and the TREK Travel Planner app for iPhone, iPad and Android connects to the same server ([Native Apps](https://github.com/liketrek/TREK/wiki/Native-Apps)). To install the web app instead: 1. Open TREK in the browser (HTTPS required) 2. **iOS**: Share ▸ *Add to Home Screen* @@ -352,7 +354,7 @@ TREK then launches fullscreen with its own icon, just like a native app. ## Updating See [Updating](https://github.com/liketrek/TREK/wiki/Updating) — Docker Compose, -Docker run, Helm, Portainer, Unraid and Proxmox, plus the encryption-key note. +Docker run, Helm, Portainer, Unraid, TrueNAS SCALE and Proxmox, plus the encryption-key note.
@@ -441,8 +443,9 @@ Every variable, its default and what it does: see The Atlas map's country and sub-national (province/county) boundaries come from [**geoBoundaries**](https://www.geoboundaries.org/) (Runfola et al., 2020), licensed -[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). See [NOTICE.md](NOTICE.md) -for full third-party attributions. +[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); Ireland's counties come from +[**Tailte Éireann**](https://data-osi.opendata.arcgis.com/), also CC BY 4.0. See +[NOTICE.md](NOTICE.md) for full third-party attributions.
diff --git a/charts/README.md b/charts/README.md index 56cace6ac..48726dcb5 100644 --- a/charts/README.md +++ b/charts/README.md @@ -43,7 +43,8 @@ See `values.yaml` for more options. ## Notes - Ingress is off by default. Enable and configure hosts for your domain. - PVCs use the cluster's default StorageClass. Set `persistence.data.storageClassName` and/or `persistence.uploads.storageClassName` to bind a specific class. -- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, annotations) are then ignored. +- Both PVCs are `ReadWriteOnce`. Set `persistence.data.accessModes` and/or `persistence.uploads.accessModes` to override, for example `[ReadWriteMany]` so a backup pod can mount the volume. On the data volume such a pod may only read: SQLite corrupts `travel.db` when a second process writes it over a network filesystem. +- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, accessModes, annotations) are then ignored. - With `persistence.enabled: false`, the data and uploads volumes use an `emptyDir` — storage is ephemeral and lost on pod restart. Intended for testing only. - `database.url` runs TREK on a PostgreSQL database instead of the SQLite file. The chart writes it into its Secret as `TREK_DB_URL`; `database.existingSecret` and `database.existingSecretKey` read it from a Secret you manage. Leave both empty for SQLite. Keep `replicas: 1` either way. See the wiki page `Database-Postgres`. - `JWT_SECRET` is managed entirely by the server — auto-generated into the data PVC on first start and rotatable via the admin panel (Settings → Danger Zone). No Helm configuration needed. @@ -57,5 +58,5 @@ See `values.yaml` for more options. - `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.** - Web Push needs no chart settings: TREK generates its key pair on first start and keeps it in the database on the data PVC. To bring your own pair, set `env.VAPID_PUBLIC_KEY` and `secretEnv.VAPID_PRIVATE_KEY` together (and optionally `env.VAPID_SUBJECT`); changing the pair later means every device has to turn push on again. - Set `env.OIDC_DISCOVERY_URL` to override the auto-constructed OIDC discovery endpoint. Required for providers (e.g. Authentik) that expose it at a non-standard path. -- `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands any file under `/app/data` and `/app/uploads` that is not owned by `node` yet to `node`, and drops to `node`. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`. +- `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands `/app/data` and `/app/uploads` to `node` (uid 1000) if the directory or anything directly inside it is not owned by `node` yet, and drops to `node`. Deeper files are not checked. Only the owning user is changed (plus a `root` group), so a different `fsGroup` stays in place. A volume that refuses `chown` (NFS with `root_squash`) logs a warning instead; set `runAsUser: 1000` then. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`. - Use `extraVolumes` and `extraVolumeMounts` to add your own volumes to the pod. To give the booking import more KItinerary extractors, mount a ConfigMap at `/usr/local/share/kitinerary/extractors`, with one `.json` and one `.js` key for each extractor; see the example in `values.yaml`. diff --git a/charts/trek/Chart.yaml b/charts/trek/Chart.yaml index 6f18fc134..84ea5c5e5 100644 --- a/charts/trek/Chart.yaml +++ b/charts/trek/Chart.yaml @@ -1,5 +1,5 @@ apiVersion: v2 name: trek -version: 5.1.0 +version: 5.1.4 description: Minimal Helm chart for TREK app -appVersion: "5.1.0" +appVersion: "5.1.4" diff --git a/charts/trek/templates/configmap.yaml b/charts/trek/templates/configmap.yaml index fd6478837..b4545d287 100644 --- a/charts/trek/templates/configmap.yaml +++ b/charts/trek/templates/configmap.yaml @@ -127,6 +127,9 @@ data: {{- if .Values.env.TREK_VALHALLA_URL }} TREK_VALHALLA_URL: {{ .Values.env.TREK_VALHALLA_URL | quote }} {{- end }} + {{- if .Values.env.TREK_WALLET_SIGNER_URL }} + TREK_WALLET_SIGNER_URL: {{ .Values.env.TREK_WALLET_SIGNER_URL | quote }} + {{- end }} {{- if .Values.env.GOOGLE_LIST_DATA_BASE }} GOOGLE_LIST_DATA_BASE: {{ .Values.env.GOOGLE_LIST_DATA_BASE | quote }} {{- end }} diff --git a/charts/trek/templates/pvc.yaml b/charts/trek/templates/pvc.yaml index 5e6872dea..149175081 100644 --- a/charts/trek/templates/pvc.yaml +++ b/charts/trek/templates/pvc.yaml @@ -11,7 +11,7 @@ metadata: {{- end }} spec: accessModes: - - ReadWriteOnce + {{- toYaml (.Values.persistence.data.accessModes | default (list "ReadWriteOnce")) | nindent 4 }} {{- with .Values.persistence.data.storageClassName }} storageClassName: {{ . | quote }} {{- end }} @@ -33,7 +33,7 @@ metadata: {{- end }} spec: accessModes: - - ReadWriteOnce + {{- toYaml (.Values.persistence.uploads.accessModes | default (list "ReadWriteOnce")) | nindent 4 }} {{- with .Values.persistence.uploads.storageClassName }} storageClassName: {{ . | quote }} {{- end }} diff --git a/charts/trek/values.yaml b/charts/trek/values.yaml index 91fd20566..6abe14f01 100644 --- a/charts/trek/values.yaml +++ b/charts/trek/values.yaml @@ -162,6 +162,10 @@ env: # TREK_VALHALLA_URL: "" # The Valhalla of the TREK services, which this server relays routing to unless the admin picks another # routing service. The browser never talks to it. Defaults to https://valhalla.liketrek.com. + # TREK_WALLET_SIGNER_URL: "" + # Signs the Apple Wallet pass of a booking when someone taps "Add to Apple Wallet" in the iOS app. + # Only the pass's texts go there, once per tap. Never asked with TREK_SERVICES=off. + # Defaults to https://push.liketrek.com/v1/wallet/pass. # 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 @@ -259,12 +263,21 @@ persistence: size: 1Gi # Leave empty to use the cluster's default StorageClass; set to bind a specific class. storageClassName: "" - # Bind an existing PVC. The other values (size, storageClassName, annotations) are then ignored. + # Access modes of the claim. ReadWriteMany lets another pod mount the volume, for + # example a backup sidecar, but only for reading: SQLite needs every writer on one + # host, so two pods writing travel.db over a network filesystem corrupt it. + accessModes: + - ReadWriteOnce + # Bind an existing PVC. The other values (size, storageClassName, accessModes, + # annotations) are then ignored. existingClaim: "" annotations: {} uploads: size: 1Gi storageClassName: "" + # Access modes of the claim; ReadWriteMany lets other pods read or add uploads. + accessModes: + - ReadWriteOnce # Specify an existing PVC to bind. The other values are then ignored. existingClaim: "" annotations: {} diff --git a/client/.gitignore b/client/.gitignore index 63f406cb5..03c1acfae 100644 --- a/client/.gitignore +++ b/client/.gitignore @@ -7,3 +7,7 @@ playwright/.cache/ # vite-plugin-pwa dev output (devOptions.enabled) dev-dist/ e2e/help/media.env + +# The native apps' address screen (npm run build:native), copied into +# android/ and ios/ by `cap sync` +native-dist/ diff --git a/client/CLAUDE.md b/client/CLAUDE.md index fc1284c65..f76ebe5bc 100644 --- a/client/CLAUDE.md +++ b/client/CLAUDE.md @@ -6,7 +6,7 @@ Scope: the **`@trek/client`** workspace (React 19 + Vite + Zustand + Tailwind PW ```bash npm run dev # Vite dev server; proxies the API/ws/uploads/MCP/OAuth paths → http://localhost:3001 -npm run build # prebuild generates PWA icons, then vite build +npm run build # prebuild generates PWA icons, then vite build; postbuild writes a Brotli copy beside each hashed asset for the server to hand out npm run typecheck # tsc --noEmit (CI) npm run lint:strict # tsc over tsconfig.strict.json (strictNullChecks + noImplicitAny): errors per file may only shrink against scripts/strict-baseline.json, a new file starts at zero (CI gate; --list shows them, --update lowers it) npm run lint # eslint . (CI runs lint:warnings instead, which fails on the same errors) diff --git a/client/android/.gitignore b/client/android/.gitignore new file mode 100644 index 000000000..82f691d36 --- /dev/null +++ b/client/android/.gitignore @@ -0,0 +1,111 @@ +# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore + +# Built application files +*.apk +*.aar +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +# Uncomment the following line in case you need and you don't have the release build type files in your app +# release/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/assetWizardSettings.xml +.idea/dictionaries +.idea/libraries +# Android Studio 3 in .gitignore file. +.idea/caches +.idea/modules.xml +# Comment next line if keeping position of elements in Navigation Editor is relevant for you +.idea/navEditor.xml + +# Keystore files and store credentials. The upload key and the Play service +# account live only in the release workflow's secrets and in the owner's +# offline backup, never in the repository. +*.jks +*.keystore +keystore.properties +*service-account*.json + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild +.cxx/ + +# Google Services (e.g. APIs or Firebase) +# Push is not wired up and the build does not apply the google-services plugin, +# so no CI secret is needed. Kept ignored so a stray Firebase config never lands +# in the repository. +google-services.json +app/google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output +fastlane/readme.md + +# Version control +vcs.xml + +# lint +lint/intermediates/ +lint/generated/ +lint/outputs/ +lint/tmp/ +# lint/reports/ + +# Android Profiling +*.hprof + +# Cordova plugins for Capacitor +capacitor-cordova-android-plugins + +# Copied web assets +app/src/main/assets/public + +# Generated Config files +app/src/main/assets/capacitor.config.json +app/src/main/assets/capacitor.plugins.json +app/src/main/res/xml/config.xml + +# Kotlin compiler caches +.kotlin/ diff --git a/client/android/app/.gitignore b/client/android/app/.gitignore new file mode 100644 index 000000000..043df802a --- /dev/null +++ b/client/android/app/.gitignore @@ -0,0 +1,2 @@ +/build/* +!/build/.npmkeep diff --git a/client/android/app/build.gradle b/client/android/app/build.gradle new file mode 100644 index 000000000..1a29303e7 --- /dev/null +++ b/client/android/app/build.gradle @@ -0,0 +1,116 @@ +apply plugin: 'com.android.application' +apply plugin: 'org.jetbrains.kotlin.android' +apply plugin: 'org.jetbrains.kotlin.plugin.compose' + +android { + namespace = "com.liketrek.trek" + compileSdk = rootProject.ext.compileSdkVersion + defaultConfig { + applicationId "com.liketrek.trek" + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + // The release workflow (.github/workflows/native-release.yml) passes both: + // the version from client/package.json and a build number that only grows. + // Local and PR builds fall back to these placeholders. + versionCode((project.findProperty('trekVersionCode') ?: '1') as Integer) + versionName(project.findProperty('trekVersionName') ?: '0.0.0-dev') + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + aaptOptions { + // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. + // Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61 + ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~' + } + } + // The upload key only exists in the release workflow, which decodes it from a + // secret and passes its path and passwords as Gradle properties. Every other + // build (local, fork, PR) stays unsigned and needs no secret. + signingConfigs { + release { + if (project.hasProperty('trekKeystore')) { + storeFile file(project.property('trekKeystore')) + storePassword project.property('trekKeystorePassword') + keyAlias project.property('trekKeyAlias') + keyPassword project.property('trekKeyPassword') + } + } + } + // java.time in the widgets and the travel-day notification, back to Android 7. + compileOptions { + coreLibraryDesugaringEnabled true + } + buildFeatures { + compose = true + buildConfig = true + } + // The app's languages, for the system's per-app language setting (Android 13+): + // generated from the values-* folders, so a language added there is offered too. + androidResources { + generateLocaleConfig = true + } + testOptions { + unitTests { + includeAndroidResources = true + returnDefaultValues = true + } + } + buildTypes { + release { + if (project.hasProperty('trekKeystore')) { + signingConfig signingConfigs.release + } + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } +} + +repositories { + flatDir{ + dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs' + } +} + +dependencies { + implementation fileTree(include: ['*.jar'], dir: 'libs') + implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" + implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" + implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" + implementation "androidx.browser:browser:$androidxBrowserVersion" + implementation "androidx.biometric:biometric:1.1.0" + implementation "androidx.core:core-ktx:$androidxCoreVersion" + coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:2.1.5" + // Home-screen widgets. + implementation "androidx.glance:glance-appwidget:$glanceVersion" + implementation "androidx.glance:glance-material3:$glanceVersion" + // The share sheet and the widget's trip picker. + implementation platform("androidx.compose:compose-bom:$composeBomVersion") + implementation "androidx.compose.material3:material3" + implementation "androidx.compose.material:material-icons-extended" + implementation "androidx.compose.ui:ui-tooling-preview" + debugImplementation "androidx.compose.ui:ui-tooling" + implementation "androidx.activity:activity-compose:$androidxActivityVersion" + // A foldable's posture and hinge, and the window's size, for the UI. + implementation "androidx.window:window:1.4.0" + // Ranks the trip shortcuts in the share sheet on Android 10 and earlier. + implementation "androidx.sharetarget:sharetarget:1.2.0" + // TREK Cloud subscriptions through Google Play, the counterpart of StoreKit. + implementation "com.android.billingclient:billing:$playBillingVersion" + // Push through liketrek's relay. No google-services plugin: Firebase reads + // its project from res/values/firebase.xml, the strings the plugin would generate. + implementation "com.google.firebase:firebase-messaging:24.1.2" + implementation project(':capacitor-android') + testImplementation "junit:junit:$junitVersion" + testImplementation "org.json:json:20250517" + androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" + implementation project(':capacitor-cordova-android-plugins') +} + +apply from: 'capacitor.build.gradle' + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21 + } +} diff --git a/client/android/app/capacitor.build.gradle b/client/android/app/capacitor.build.gradle new file mode 100644 index 000000000..da95d6401 --- /dev/null +++ b/client/android/app/capacitor.build.gradle @@ -0,0 +1,27 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN + +android { + compileOptions { + sourceCompatibility JavaVersion.VERSION_21 + targetCompatibility JavaVersion.VERSION_21 + } +} + +apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle" +dependencies { + implementation project(':capacitor-action-sheet') + implementation project(':capacitor-app') + implementation project(':capacitor-dialog') + implementation project(':capacitor-filesystem') + implementation project(':capacitor-haptics') + implementation project(':capacitor-keyboard') + implementation project(':capacitor-share') + implementation project(':capacitor-splash-screen') + implementation project(':capacitor-status-bar') + +} + + +if (hasProperty('postBuildExtras')) { + postBuildExtras() +} diff --git a/client/android/app/proguard-rules.pro b/client/android/app/proguard-rules.pro new file mode 100644 index 000000000..7ddd3a89f --- /dev/null +++ b/client/android/app/proguard-rules.pro @@ -0,0 +1,47 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile + +# TREK's own classes: TrekShellPlugin is reached from JavaScript by name and its +# methods through reflection, so R8 must neither rename nor drop them. +-keep class com.liketrek.trek.** { *; } + +# Every Capacitor plugin: the bridge finds plugins by their annotation and calls +# the annotated methods reflectively. +-keep @com.getcapacitor.annotation.CapacitorPlugin public class * { + @com.getcapacitor.PluginMethod public ; +} + +# The WebView bridge: Capacitor's message handler is called from JavaScript +# through @JavascriptInterface, and every plugin class is instantiated by name. +-keepclassmembers class * { + @android.webkit.JavascriptInterface ; +} +-keep public class * extends com.getcapacitor.Plugin + +# The stored copy of the server's UI gets Capacitor's bridge the way the +# server's own page does (TrekOfflineShell.withBridge reads it by reflection). +-keepclassmembers class com.getcapacitor.Bridge { + private com.getcapacitor.JSInjector getJSInjector(); +} +-keep class com.getcapacitor.JSInjector { + public java.io.InputStream getInjectedStream(java.io.InputStream); +} diff --git a/client/android/app/src/debug/AndroidManifest.xml b/client/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 000000000..7a510d7af --- /dev/null +++ b/client/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + + diff --git a/client/android/app/src/debug/java/com/liketrek/trek/debug/WidgetGalleryActivity.kt b/client/android/app/src/debug/java/com/liketrek/trek/debug/WidgetGalleryActivity.kt new file mode 100644 index 000000000..3c851d4d7 --- /dev/null +++ b/client/android/app/src/debug/java/com/liketrek/trek/debug/WidgetGalleryActivity.kt @@ -0,0 +1,127 @@ +package com.liketrek.trek.debug + +import android.app.Activity +import android.content.res.Configuration +import android.graphics.Color +import android.os.Bundle +import android.util.TypedValue +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import androidx.glance.appwidget.ExperimentalGlanceRemoteViewsApi +import androidx.glance.appwidget.GlanceRemoteViews +import com.liketrek.trek.tripday.TripDayNotification +import com.liketrek.trek.widget.AtlasWidget +import com.liketrek.trek.widget.BookingsWidget +import com.liketrek.trek.widget.FlightWidget +import com.liketrek.trek.widget.CollabWidget +import com.liketrek.trek.widget.PackingWidget +import com.liketrek.trek.widget.TodayWidget +import com.liketrek.trek.widget.TodosWidget +import com.liketrek.trek.widget.TrekSizes +import com.liketrek.trek.widget.TrekWidget +import com.liketrek.trek.widget.TrekWidgetTheme +import com.liketrek.trek.widget.TripWidget +import com.liketrek.trek.widget.WidgetSamples +import com.liketrek.trek.widget.WidgetStore +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch + +/** + * Debug builds only: every widget at every size, drawn by the real Glance code + * into real RemoteViews, so they can be looked at and screenshot without placing + * each on a home screen. + * + * adb shell am start -n com.liketrek.trek/.debug.WidgetGalleryActivity --es widget trip --ez running true --ez dark false + * + * --es seed sample also writes the sample trip as the app's snapshot, so the + * placed widgets, the share sheet and the shortcuts have a trip to show; and + * --ez tripday true posts the travel day's Live Update from the sample. + */ +@OptIn(ExperimentalGlanceRemoteViewsApi::class) +class WidgetGalleryActivity : Activity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val running = intent.getBooleanExtra("running", true) + val dark = intent.getBooleanExtra("dark", false) + val only = intent.getStringExtra("widget") + if (intent.getStringExtra("seed") == "sample") seed() + if (intent.getBooleanExtra("tripday", false)) { + TripDayNotification.show( + this, + TripDayNotification.State( + "Autumn in Kyoto", "/trips/1", "Day 3 of 9", "Kiyomizu-dera", "13:30", 810, 2, 5, + listOf("#D6273B", "#E8A13A", "#2FA37A", "#4A7DDB", "#8E6CD9"), + ), + ) + } + + val config = Configuration(resources.configuration).apply { + uiMode = (uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()) or if (dark) Configuration.UI_MODE_NIGHT_YES else Configuration.UI_MODE_NIGHT_NO + } + val themed = createConfigurationContext(config) + val list = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(px(16), px(if (intent.getBooleanExtra("bare", false)) 96 else 32), px(16), px(32)) + val bg = intent.getStringExtra("bg") + setBackgroundColor(if (bg != null) Color.parseColor("#$bg") else if (dark) Color.rgb(28, 27, 31) else Color.rgb(222, 226, 236)) + } + setContentView(ScrollView(this).apply { addView(list) }) + + val widgets: List> = listOf( + "trip" to TripWidget(), + "today" to TodayWidget(), + "bookings" to BookingsWidget(), + "flight" to FlightWidget(), + "todos" to TodosWidget(), + "packing" to PackingWidget(), + "atlas" to AtlasWidget(), + "collab" to CollabWidget(), + ).filter { only == null || it.first == only } + // --ez store true draws what the app really wrote, instead of the sample trip. + val snapshot = if (intent.getBooleanExtra("store", false)) WidgetStore.load(this) else WidgetSamples.snapshot(running) + CoroutineScope(Dispatchers.Main).launch { + for ((name, widget) in widgets) { + if (!intent.getBooleanExtra("bare", false)) list.addView(TextView(this@WidgetGalleryActivity).apply { + text = name + setTextColor(if (dark) Color.WHITE else Color.DKGRAY) + setPadding(0, px(12), 0, px(6)) + }) + val onlySize = intent.getStringExtra("size") + val sizes = listOf("small" to TrekSizes.SMALL, "wide" to TrekSizes.WIDE, "large" to TrekSizes.LARGE) + for ((sizeName, size) in sizes) { + if (onlySize != null && onlySize != sizeName) continue + val result = GlanceRemoteViews().compose(themed, size) { + TrekWidgetTheme.Themed { widget.Content(snapshot) } + } + val host = FrameLayout(this@WidgetGalleryActivity) + host.addView(result.remoteViews.apply(themed, host), FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + list.addView(host, LinearLayout.LayoutParams(px(size.width.value), px(size.height.value)).apply { bottomMargin = px(12) }) + } + } + } + } + + private fun seed() { + WidgetStore.write(this, "snapshot", WidgetSamples.json(running = true)) + WidgetStore.write(this, "trip.1", WidgetSamples.json(running = true)) + WidgetStore.write(this, "trip.2", WidgetSamples.json(running = false).replace("Autumn in Kyoto", "Lisbon long weekend")) + WidgetStore.write( + this, + "trips", + """[{"id":1,"title":"Autumn in Kyoto","start":"${java.time.LocalDate.now().minusDays(2)}","end":"${java.time.LocalDate.now().plusDays(6)}"}, + {"id":2,"title":"Lisbon long weekend","start":"${java.time.LocalDate.now().plusDays(12)}","end":"${java.time.LocalDate.now().plusDays(15)}"}, + {"id":3,"title":"Norway by train","start":"2026-06-02","end":"2026-06-12"}]""", + ) + com.liketrek.trek.widget.TrekWidgetUpdater.refreshAll(this) + com.liketrek.trek.share.TrekShortcuts.publish(this) + } + + private fun px(dp: Float): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics).toInt() + + private fun px(dp: Int): Int = px(dp.toFloat()) + +} diff --git a/client/android/app/src/main/AndroidManifest.xml b/client/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..21f307838 --- /dev/null +++ b/client/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java b/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java new file mode 100644 index 000000000..e284ee944 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/MainActivity.java @@ -0,0 +1,248 @@ +package com.liketrek.trek; + +import android.content.Intent; +import android.graphics.drawable.GradientDrawable; +import android.os.Bundle; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.KeyboardShortcutGroup; +import android.view.Menu; +import android.view.View; +import android.view.ViewGroup; +import android.webkit.CookieManager; +import android.widget.Button; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; +import com.getcapacitor.BridgeActivity; +import com.liketrek.trek.screen.TrekKeyCommands; +import com.liketrek.trek.tiles.TrekTileStore; +import com.liketrek.trek.widget.TrekWidgetUpdater; +import java.util.List; + +public class MainActivity extends BridgeActivity { + + /** The share sheet (share/ShareActivity.kt) left an item for the import. */ + public static final String ACTION_SHARE_HANDOFF = "com.liketrek.trek.SHARE_HANDOFF"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + registerPlugin(TrekShellPlugin.class); + TrekTileStore.INSTANCE.init(this); + // With a server picked, the WebView loads that server instead of the + // bundled address screen, so the UI arrives in the version the server + // runs and on its own origin. BridgeActivity reads `config` while it + // builds the bridge inside super.onCreate(). + boolean restarting = TrekServerStore.consumeRestart(this); + // Without a network the server cannot answer: with a copy of its UI the + // app starts on that at once (TrekOfflineShell), as it does when the + // address screen found the server out of reach. The check an update asks + // for waits for a launch that can reach the server. + boolean offlineStart = TrekServerStore.consumeOfflineStart(this) + || (!TrekOfflineShell.hasNetwork(this) && TrekOfflineShell.hasCopy(this, TrekServerStore.getUrlOrPrevious(this))); + if (offlineStart && TrekOfflineShell.hasCopy(this, TrekServerStore.getUrlOrPrevious(this))) { + TrekServerStore.restoreForOffline(this); + TrekOfflineShell.activate(TrekServerStore.getUrl(this)); + } else { + TrekOfflineShell.deactivate(); + TrekServerStore.recheckAfterUpdate(this); + } + String server = TrekServerStore.getUrl(this); + boolean onServer = server != null && !TrekServerStore.consumeShellOnce(this); + config = TrekServerStore.configFor(this, onServer ? server : null, restarting); + super.onCreate(savedInstanceState); + if (bridge == null) return; + // The UI asks for no overscroll effect (overscroll-behavior: none on html) + // and Chrome honours that, but the WebView draws the stretch on its root + // scroller natively. It scales the whole view, top bar and bottom dock included. + bridge.getWebView().setOverScrollMode(View.OVER_SCROLL_NEVER); + // Set before any WebView callback can run: they are posted to this thread. + if (onServer) { + bridge.setWebViewClient( + new TrekWebViewClient( + bridge, + this::showAddressScreen, + this::showSignInBar, + this::showErrorPageBar, + TrekServerStore.getSignInHosts(this) + ) + ); + } + TrekSharedFiles.receive(this, getIntent()); + // Android 15's widget picker draws the widgets live from a sample trip. + TrekWidgetUpdater.publishPreviews(this); + } + + /** + * A hardware keyboard's shortcut runs the UI's command (TrekKeyCommands), + * wherever the focus is; everything else goes on to the WebView as usual. + */ + @Override + public boolean dispatchKeyEvent(KeyEvent event) { + if (TrekKeyCommands.INSTANCE.dispatch(event)) return true; + return super.dispatchKeyEvent(event); + } + + /** The UI's shortcuts in the system's list (Meta + /), under their names. */ + @Override + public void onProvideKeyboardShortcuts(List data, Menu menu, int deviceId) { + super.onProvideKeyboardShortcuts(data, menu, deviceId); + KeyboardShortcutGroup group = TrekKeyCommands.INSTANCE.shortcutGroup(getString(R.string.app_name)); + if (group != null) data.add(group); + } + + /** + * The web view keeps new cookies in memory and writes them to disk on its + * own schedule, about half a minute later. An app Android ends in that time + * (swiped away, or reclaimed for memory) forgets the sign-in it just had, so + * the session is written down whenever the app leaves the screen. + */ + @Override + public void onPause() { + super.onPause(); + CookieManager.getInstance().flush(); + } + + @Override + public void onNewIntent(Intent intent) { + super.onNewIntent(intent); + TrekSharedFiles.receive(this, intent); + } + + private boolean leavingServer; + + private View signInBar; + /** Whether the page is a proxy's sign-in page, and whether the keyboard is up over it. */ + private boolean onSignInPage; + /** Whether the page is an error page in place of the server's (TrekWebViewClient.onReceivedHttpError). */ + private boolean onErrorPage; + private boolean keyboardUp; + private TextView signInHint; + + /** + * Over a proxy's sign-in page (Pangolin, authentik, ...): the server's UI is + * not there, so nothing else would lead back to the address screen, and a + * passkey cannot work in a web view for a domain the app is not tied to. + * The bar says so and offers to change the server. + */ + private void showSignInBar(boolean show) { + runOnUiThread(() -> { + onSignInPage = show; + if (show && signInBar == null) signInBar = buildSignInBar(); + updateSignInBar(); + }); + } + + /** The same bar over an error page in place of the server's, with words for that. */ + private void showErrorPageBar(boolean show) { + runOnUiThread(() -> { + onErrorPage = show; + if (show && signInBar == null) signInBar = buildSignInBar(); + updateSignInBar(); + }); + } + + /** Out of the way while the keyboard is up: the form needs the room, and the bar is there again once it closes. */ + private void updateSignInBar() { + if (signInBar == null) return; + if (signInHint != null) { + signInHint.setText(onSignInPage ? TrekServerStore.signInHintLabel(this) : TrekServerStore.errorPageHintLabel(this)); + } + signInBar.setVisibility((onSignInPage || onErrorPage) && !keyboardUp ? View.VISIBLE : View.GONE); + } + + private View buildSignInBar() { + float dp = getResources().getDisplayMetrics().density; + LinearLayout bar = new LinearLayout(this); + bar.setOrientation(LinearLayout.HORIZONTAL); + bar.setGravity(Gravity.CENTER_VERTICAL); + bar.setPaddingRelative(Math.round(16 * dp), Math.round(10 * dp), Math.round(10 * dp), Math.round(10 * dp)); + // The look of the app's own first screens: a white card with a sand edge, + // warm grey text and a dark button, over whatever page the proxy shows. + GradientDrawable background = new GradientDrawable(); + background.setColor(0xF7FFFFFF); + background.setCornerRadius(18 * dp); + background.setStroke(Math.max(1, Math.round(dp)), 0xFFEFE4D8); + bar.setBackground(background); + bar.setElevation(8 * dp); + + TextView hint = new TextView(this); + signInHint = hint; + hint.setText(TrekServerStore.signInHintLabel(this)); + hint.setTextColor(0xFF6B5F57); + hint.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12.5f); + bar.addView(hint, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)); + + Button change = new Button(this, null, android.R.attr.borderlessButtonStyle); + change.setText(TrekServerStore.changeServerLabel(this)); + change.setAllCaps(false); + change.setTextColor(0xFFFFFFFF); + GradientDrawable pill = new GradientDrawable(); + pill.setColor(0xFF111827); + pill.setCornerRadius(12 * dp); + change.setBackground(pill); + change.setMinHeight(0); + change.setMinimumHeight(0); + change.setPaddingRelative(Math.round(14 * dp), Math.round(9 * dp), Math.round(14 * dp), Math.round(9 * dp)); + LinearLayout.LayoutParams changeParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + changeParams.setMarginStart(Math.round(10 * dp)); + change.setOnClickListener((v) -> { + TrekServerStore.setUrl(this, null); + TrekServerStore.markRestart(this); + recreate(); + }); + bar.addView(change, changeParams); + + int margin = Math.round(12 * dp); + FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + Gravity.BOTTOM + ); + params.setMargins(margin, 0, margin, margin); + FrameLayout root = findViewById(android.R.id.content); + root.addView(bar, params); + // Above the gesture bar, and above the keyboard while it is up. + bar.setOnApplyWindowInsetsListener((v, insets) -> { + // Read off the window's own insets: Capacitor hands the views below the + // decor a copy with the system bars zeroed, and before Android 11 that + // takes the keyboard with it. + androidx.core.view.WindowInsetsCompat window = androidx.core.view.ViewCompat.getRootWindowInsets(getWindow().getDecorView()); + int bottom = window != null + ? window.getInsets(androidx.core.view.WindowInsetsCompat.Type.navigationBars()).bottom + : insets.getStableInsetBottom(); + boolean imeVisible = window != null && window.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()); + if (imeVisible != keyboardUp) { + keyboardUp = imeVisible; + updateSignInBar(); + } + FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) v.getLayoutParams(); + if (p.bottomMargin != margin + bottom) { + p.bottomMargin = margin + bottom; + v.setLayoutParams(p); + } + return insets; + }); + bar.requestApplyInsets(); + return bar; + } + + /** + * The server did not load: back to the address screen, which offers retry + * and change. A fresh task rather than recreate(), because this usually + * happens during launch, while the system splash is still up, and a + * recreated activity leaves that splash lying over the new page. + */ + private void showAddressScreen() { + // A failed page can report more than one error; restart only once. + if (leavingServer) return; + leavingServer = true; + TrekServerStore.showShellOnce(this); + TrekServerStore.markRestart(this); + runOnUiThread(() -> { + startActivity(new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)); + overridePendingTransition(0, 0); + }); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/SignInRedirect.java b/client/android/app/src/main/java/com/liketrek/trek/SignInRedirect.java new file mode 100644 index 000000000..5c764187a --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/SignInRedirect.java @@ -0,0 +1,57 @@ +package com.liketrek.trek; + +import java.net.URI; +import java.util.Locale; + +/** + * A sign-in page in front of the server that the address screen never saw. + * A proxy can let the app's check through (an Authelia or Authentik rule that + * bypasses /api) and still send the page itself to its sign-in. Handed to the + * browser, that sign-in leaves its session there and the app stays blank on + * every launch. So a redirect away from the server, while the server's first + * page is still loading, is taken as the proxy's sign-in: it loads in the web + * view and its host is kept, the way the address screen keeps the ones it saw. + * A link the user follows is no redirect, and once a page of the server has + * shown, nothing is learned any more. + */ +final class SignInRedirect { + + private SignInRedirect() {} + + /** The host (host:port with an explicit port) to keep as a sign-in host, or null. */ + static String learnedHost(String server, String target, boolean mainFrame, boolean redirect, boolean serverShown) { + if (!mainFrame || !redirect || serverShown || server == null || target == null) return null; + URI from; + URI to; + try { + from = new URI(server); + to = new URI(target); + } catch (Exception e) { + return null; + } + String fromHost = lower(from.getHost()); + String toHost = lower(to.getHost()); + String toScheme = lower(to.getScheme()); + if (fromHost == null || toHost == null) return null; + if (!"https".equals(toScheme) && !"http".equals(toScheme)) return null; + // Never from https down to plain http: the sign-in would send a password in the clear. + if ("https".equals(lower(from.getScheme())) && !"https".equals(toScheme)) return null; + if (toHost.equals(fromHost)) return null; + return to.getPort() == -1 ? toHost : toHost + ":" + to.getPort(); + } + + /** Whether `url` is on the server's host, where the app's own pages come from. */ + static boolean onServer(String server, String url) { + if (server == null || url == null) return false; + try { + String serverHost = lower(new URI(server).getHost()); + return serverHost != null && serverHost.equals(lower(new URI(url).getHost())); + } catch (Exception e) { + return false; + } + } + + private static String lower(String value) { + return value == null ? null : value.toLowerCase(Locale.ROOT); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekOfflineShell.java b/client/android/app/src/main/java/com/liketrek/trek/TrekOfflineShell.java new file mode 100644 index 000000000..821d143ef --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekOfflineShell.java @@ -0,0 +1,330 @@ +package com.liketrek.trek; + +import android.content.Context; +import android.net.ConnectivityManager; +import android.net.Network; +import android.net.NetworkCapabilities; +import android.net.Uri; +import android.util.Log; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import com.getcapacitor.Bridge; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * The server's UI kept on the device, so the app starts without its server: on + * a trip without reception, or away from home with a server on the home + * network. The web view runs no service worker on a plain-http server, the + * usual address of a server at home, so the app keeps the start page and every + * file of the build itself (refreshed by native/offlineShell.ts while the + * server is reachable) and serves them under the server's own origin while it + * is not. The data comes from the UI's own offline store; the API is tried as + * usual and answers again once the server is back. + */ +final class TrekOfflineShell { + + private static final String DIR = "offline-shell"; + private static final String PAGE = "index.html"; + private static final String STAMP = "server.txt"; + private static final String FILES = "files"; + /** A path of the build: no "..", no query, nothing outside the copy's folder. */ + private static final Pattern SAFE_PATH = Pattern.compile("^[A-Za-z0-9._@\\-]+(?:/[A-Za-z0-9._@\\-]+)*$"); + private static final Map TYPES = new HashMap<>(); + + static { + TYPES.put("js", "text/javascript"); + TYPES.put("mjs", "text/javascript"); + TYPES.put("css", "text/css"); + TYPES.put("json", "application/json"); + TYPES.put("webmanifest", "application/manifest+json"); + TYPES.put("svg", "image/svg+xml"); + TYPES.put("png", "image/png"); + TYPES.put("jpg", "image/jpeg"); + TYPES.put("jpeg", "image/jpeg"); + TYPES.put("webp", "image/webp"); + TYPES.put("ico", "image/x-icon"); + TYPES.put("woff", "font/woff"); + TYPES.put("woff2", "font/woff2"); + TYPES.put("ttf", "font/ttf"); + TYPES.put("wasm", "application/wasm"); + TYPES.put("html", "text/html"); + } + + /** + * The server whose copy the UI comes from in this run: it did not answer + * when the app started. Null while the UI comes from the server itself. + * Bound to the server, so a copy never answers for another one. + */ + private static volatile String activeServer; + /** Capacitor's JSInjector (package-private there) and its getInjectedStream, found once. */ + private static volatile Object injector; + private static volatile Method injectMethod; + private static volatile boolean injectorLooked; + + private TrekOfflineShell() {} + + static boolean isActive() { + return activeServer != null; + } + + static void activate(String server) { + activeServer = server; + } + + /** + * A start that goes to the server. The flag lives in the process, and + * restart() recreates the activity in that same process (another server + * picked, the address screen, a reload once the server is back), so each + * start sets it anew instead of keeping the last run's copy in front. + */ + static void deactivate() { + activeServer = null; + } + + /** Whether the copy stands in for this server in this run. */ + static boolean isActiveFor(String server) { + String current = activeServer; + return current != null && current.equals(server); + } + + private static File root(Context context) { + return new File(context.getFilesDir(), DIR); + } + + /** Whether there is a copy of this server's UI to start from. */ + static boolean hasCopy(Context context, String server) { + return hasCopy(root(context), server); + } + + static boolean hasCopy(File root, String server) { + if (server == null) return false; + File page = new File(root, PAGE); + return page.isFile() && server.equals(readStamp(root)); + } + + /** Whether the device has a network at all; with none, the server cannot answer and the copy starts at once. */ + static boolean hasNetwork(Context context) { + try { + ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + if (cm == null) return true; + Network network = cm.getActiveNetwork(); + if (network == null) return false; + NetworkCapabilities caps = cm.getNetworkCapabilities(network); + return caps != null && caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); + } catch (RuntimeException e) { + return true; + } + } + + /** + * Before a refresh fetches the files of a build: a copy of another server + * is thrown away, one of this server stays as it is until savePage. + */ + static boolean beginRefresh(Context context, String server) { + return beginRefresh(root(context), server); + } + + static boolean beginRefresh(File root, String server) { + if (!server.equals(readStamp(root))) deleteTree(root); + return root.isDirectory() || root.mkdirs(); + } + + /** + * Keeps the start page, and only once every file it names is stored: the + * page points at the build's files by their hashes, so a refresh cut off + * halfway (no reception, the app ended) keeps the previous page with its + * complete build instead of a new page whose scripts are missing. + */ + static boolean savePage(Context context, String server, byte[] html) { + return savePage(root(context), server, html); + } + + static boolean savePage(File root, String server, byte[] html) { + if (!root.isDirectory() && !root.mkdirs()) return false; + return write(new File(root, STAMP), server.getBytes(StandardCharsets.UTF_8)) && write(new File(root, PAGE), html); + } + + static boolean hasFile(Context context, String path) { + return hasFile(root(context), path); + } + + static boolean hasFile(File root, String path) { + File file = fileFor(root, path); + return file != null && file.isFile(); + } + + static boolean saveFile(Context context, String path, byte[] data) { + return saveFile(root(context), path, data); + } + + static boolean saveFile(File root, String path, byte[] data) { + File file = fileFor(root, path); + if (file == null) return false; + File parent = file.getParentFile(); + if (parent != null && !parent.isDirectory() && !parent.mkdirs()) return false; + return write(file, data); + } + + /** Drops the files of older builds once the current one is complete. */ + static void prune(Context context, Set keep) { + prune(root(context), keep); + } + + static void prune(File root, Set keep) { + File base = new File(root, FILES); + pruneDir(base, base, keep); + } + + /** + * The copy's answer for a request of the server's UI while it is active: + * the start page for any page of the app (it routes itself), with + * Capacitor's bridge injected as into the server's own page, and a file of + * the build by its path. Null for anything else, which goes on as usual. + */ + static WebResourceResponse serve(Context context, Bridge bridge, String server, WebResourceRequest request) { + if (!isActiveFor(server) || !"GET".equalsIgnoreCase(request.getMethod())) return null; + Uri url = request.getUrl(); + Uri origin = Uri.parse(server); + if (!sameOrigin(url, origin)) return null; + try { + if (request.isForMainFrame()) { + File page = new File(root(context), PAGE); + if (!page.isFile()) return null; + InputStream html = withBridge(bridge, new FileInputStream(page)); + return response("text/html", html); + } + String path = url.getPath(); + if (path == null) return null; + File file = fileFor(root(context), path); + if (file == null || !file.isFile()) return null; + return response(typeOf(path), new FileInputStream(file)); + } catch (IOException e) { + Log.w("TrekShell", "Offline copy could not answer " + url, e); + return null; + } + } + + private static WebResourceResponse response(String type, InputStream body) { + Map headers = new HashMap<>(); + headers.put("Cache-Control", "no-store"); + String charset = type.startsWith("text/") || type.endsWith("json") ? "utf-8" : null; + return new WebResourceResponse(type, charset, 200, "OK", headers, body); + } + + /** + * Capacitor injects its bridge into the server's page as it passes through; + * the copy gets the same script. Its builder is internal to Capacitor, hence + * the reflection on both (kept in proguard-rules.pro). Without it the UI still runs, + * as it would in a browser, just without the app's native parts. + */ + private static InputStream withBridge(Bridge bridge, InputStream html) { + if (!injectorLooked) { + injectorLooked = true; + try { + Method method = Bridge.class.getDeclaredMethod("getJSInjector"); + method.setAccessible(true); + Object built = method.invoke(bridge); + if (built != null) { + Method inject = built.getClass().getDeclaredMethod("getInjectedStream", InputStream.class); + inject.setAccessible(true); + injectMethod = inject; + injector = built; + } + } catch (ReflectiveOperationException | RuntimeException e) { + Log.w("TrekShell", "No bridge for the offline copy", e); + } + } + Object current = injector; + Method inject = injectMethod; + if (current == null || inject == null) return html; + try { + Object injected = inject.invoke(current, html); + return injected instanceof InputStream ? (InputStream) injected : html; + } catch (ReflectiveOperationException | RuntimeException e) { + Log.w("TrekShell", "Bridge not injected into the offline copy", e); + return html; + } + } + + private static boolean sameOrigin(Uri a, Uri b) { + if (a.getScheme() == null || b.getScheme() == null || a.getHost() == null || b.getHost() == null) return false; + return a.getScheme().equalsIgnoreCase(b.getScheme()) + && a.getHost().equalsIgnoreCase(b.getHost()) + && port(a) == port(b); + } + + private static int port(Uri uri) { + if (uri.getPort() != -1) return uri.getPort(); + return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80; + } + + private static File fileFor(File root, String path) { + String clean = path.startsWith("/") ? path.substring(1) : path; + if (clean.isEmpty() || clean.contains("..") || !SAFE_PATH.matcher(clean).matches()) return null; + return new File(new File(root, FILES), clean); + } + + private static String typeOf(String path) { + int dot = path.lastIndexOf('.'); + String ext = dot < 0 ? "" : path.substring(dot + 1).toLowerCase(Locale.ROOT); + String type = TYPES.get(ext); + return type == null ? "application/octet-stream" : type; + } + + private static String readStamp(File root) { + File stamp = new File(root, STAMP); + if (!stamp.isFile()) return null; + try (FileInputStream in = new FileInputStream(stamp)) { + byte[] data = new byte[(int) Math.min(stamp.length(), 4096)]; + int read = in.read(data); + return read <= 0 ? null : new String(data, 0, read, StandardCharsets.UTF_8); + } catch (IOException e) { + return null; + } + } + + /** Written beside the target and moved over it, so a cut-off write never leaves half a file. */ + private static boolean write(File target, byte[] data) { + File temp = new File(target.getPath() + ".part"); + try (FileOutputStream out = new FileOutputStream(temp)) { + out.write(data); + out.getFD().sync(); + } catch (IOException e) { + temp.delete(); + return false; + } + return temp.renameTo(target); + } + + private static void pruneDir(File base, File dir, Set keep) { + File[] children = dir.listFiles(); + if (children == null) return; + for (File child : children) { + if (child.isDirectory()) { + pruneDir(base, child, keep); + String[] left = child.list(); + if (left != null && left.length == 0) child.delete(); + } else { + String relative = base.toURI().relativize(child.toURI()).getPath(); + if (!keep.contains(relative)) child.delete(); + } + } + } + + private static void deleteTree(File file) { + File[] children = file.listFiles(); + if (children != null) for (File child : children) deleteTree(child); + file.delete(); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekPushKeys.java b/client/android/app/src/main/java/com/liketrek/trek/TrekPushKeys.java new file mode 100644 index 000000000..6882da9ec --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekPushKeys.java @@ -0,0 +1,139 @@ +package com.liketrek.trek; + +import android.content.Context; +import android.content.SharedPreferences; +import android.security.keystore.KeyGenParameterSpec; +import android.security.keystore.KeyProperties; +import android.util.Base64; +import java.math.BigInteger; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.spec.ECGenParameterSpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.SecureRandom; +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; + +/** + * The device's Web Push key pair (P-256) and auth secret (RFC 8291). The server + * encrypts every notification for these, and TrekPushService decrypts with + * them. They are kept in the app's preferences, sealed with an AES key that + * never leaves the Android Keystore, so a copy of the preferences alone opens + * nothing. + */ +final class TrekPushKeys { + + private static final String PREFS = "trek_push"; + private static final String WRAP_ALIAS = "trek_push_wrap"; + private static final String PRIVATE = "private"; + private static final String PUBLIC = "public"; + private static final String AUTH = "auth"; + + final ECPrivateKey privateKey; + /** Uncompressed point, 65 bytes, as the server reads p256dh. */ + final byte[] publicKey; + final byte[] auth; + + TrekPushKeys(ECPrivateKey privateKey, byte[] publicKey, byte[] auth) { + this.privateKey = privateKey; + this.publicKey = publicKey; + this.auth = auth; + } + + /** The stored keys, or null when the app never subscribed. */ + static synchronized TrekPushKeys load(Context context) throws Exception { + SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + String sealedPrivate = prefs.getString(PRIVATE, null); + String publicKey = prefs.getString(PUBLIC, null); + String sealedAuth = prefs.getString(AUTH, null); + if (sealedPrivate == null || publicKey == null || sealedAuth == null) return null; + byte[] pkcs8 = unseal(sealedPrivate); + ECPrivateKey key = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(pkcs8)); + return new TrekPushKeys(key, Base64.decode(publicKey, Base64.NO_WRAP), unseal(sealedAuth)); + } + + static synchronized TrekPushKeys loadOrCreate(Context context) throws Exception { + TrekPushKeys existing; + try { + existing = load(context); + } catch (Exception unreadable) { + // The Keystore key is gone (backup restored to another device, data + // cleared): start over, the next subscription carries the new keys. + existing = null; + } + if (existing != null) return existing; + + KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); + generator.initialize(new ECGenParameterSpec("secp256r1")); + KeyPair pair = generator.generateKeyPair(); + byte[] publicKey = uncompressed((ECPublicKey) pair.getPublic()); + byte[] auth = new byte[16]; + new SecureRandom().nextBytes(auth); + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + .edit() + .putString(PRIVATE, seal(pair.getPrivate().getEncoded())) + .putString(PUBLIC, Base64.encodeToString(publicKey, Base64.NO_WRAP)) + .putString(AUTH, seal(auth)) + .apply(); + return new TrekPushKeys((ECPrivateKey) pair.getPrivate(), publicKey, auth); + } + + static String base64url(byte[] data) { + return Base64.encodeToString(data, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING); + } + + static byte[] uncompressed(ECPublicKey key) { + byte[] out = new byte[65]; + out[0] = 0x04; + copyFixed(key.getW().getAffineX(), out, 1); + copyFixed(key.getW().getAffineY(), out, 33); + return out; + } + + /** A coordinate as exactly 32 bytes: BigInteger adds a sign byte or drops leading zeros. */ + private static void copyFixed(BigInteger value, byte[] out, int offset) { + byte[] raw = value.toByteArray(); + int start = Math.max(0, raw.length - 32); + int length = raw.length - start; + System.arraycopy(raw, start, out, offset + 32 - length, length); + } + + private static SecretKey wrapKey() throws Exception { + KeyStore store = KeyStore.getInstance("AndroidKeyStore"); + store.load(null); + if (store.containsAlias(WRAP_ALIAS)) return ((KeyStore.SecretKeyEntry) store.getEntry(WRAP_ALIAS, null)).getSecretKey(); + KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); + generator.init( + new KeyGenParameterSpec.Builder(WRAP_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build() + ); + return generator.generateKey(); + } + + private static String seal(byte[] plain) throws Exception { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, wrapKey()); + byte[] iv = cipher.getIV(); + byte[] sealed = cipher.doFinal(plain); + byte[] out = new byte[iv.length + sealed.length]; + System.arraycopy(iv, 0, out, 0, iv.length); + System.arraycopy(sealed, 0, out, iv.length, sealed.length); + return Base64.encodeToString(out, Base64.NO_WRAP); + } + + private static byte[] unseal(String value) throws Exception { + byte[] in = Base64.decode(value, Base64.NO_WRAP); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, wrapKey(), new GCMParameterSpec(128, in, 0, 12)); + return cipher.doFinal(in, 12, in.length - 12); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekPushService.java b/client/android/app/src/main/java/com/liketrek/trek/TrekPushService.java new file mode 100644 index 000000000..695bd9fa9 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekPushService.java @@ -0,0 +1,160 @@ +package com.liketrek.trek; + +import android.Manifest; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Build; +import android.util.Base64; +import androidx.annotation.NonNull; +import androidx.core.app.NotificationCompat; +import androidx.core.app.NotificationManagerCompat; +import androidx.core.content.ContextCompat; +import com.google.firebase.messaging.FirebaseMessagingService; +import com.google.firebase.messaging.RemoteMessage; +import java.nio.charset.StandardCharsets; +import org.json.JSONObject; + +/** + * Receives the relay's data messages ({enc}: the server's encrypted Web Push + * record), decrypts them with the device's keys and shows the notification. + * Without the keys, or when the record does not open, it shows the same + * neutral text the iOS extension falls back to, never the ciphertext. + */ +public class TrekPushService extends FirebaseMessagingService { + + static final String CHANNEL = "trek"; + static final String EXTRA_URL = "trek.pushUrl"; + + @Override + public void onMessageReceived(@NonNull RemoteMessage message) { + String enc = message.getData().get("enc"); + if (enc == null) return; + String title = getString(R.string.push_fallback_title); + String body = getString(R.string.push_fallback_body); + String url = null; + String tag = null; + String event = null; + try { + TrekPushKeys keys = TrekPushKeys.load(this); + if (keys != null) { + byte[] plain = TrekWebPush.decrypt(Base64.decode(enc, Base64.DEFAULT), keys); + JSONObject payload = new JSONObject(new String(plain, StandardCharsets.UTF_8)); + if (!payload.optString("title").isEmpty()) title = payload.optString("title"); + body = payload.optString("body", body); + url = payload.optString("url", null); + tag = payload.optString("tag", null); + event = payload.optString("event", null); + } + } catch (Exception unreadable) { + // Shown with the neutral text: the tap still opens the app. + } + show(this, title, body, url, tag, event); + } + + /** A new token means a new endpoint; the UI re-registers on its next start (resyncPushSubscription). */ + @Override + public void onNewToken(@NonNull String token) {} + + /** The channels, so each kind can be silenced, raised or kept on its own in the system settings. */ + static final String CHANNEL_CHAT = "chat"; + static final String CHANNEL_TRIPS = "trips"; + static final String CHANNEL_INVITES = "invites"; + + /** + * The channel of a notification by the event the server names (PushPayload.event, + * notification-events.ts). A server too old to send one lands in the general channel. + */ + static String channelFor(String event) { + if (event == null) return CHANNEL; + switch (event) { + case "collab_message": + return CHANNEL_CHAT; + case "booking_change": + case "trip_reminder": + case "todo_due": + case "packing_tagged": + return CHANNEL_TRIPS; + case "trip_invite": + case "vacay_invite": + case "vacay_share": + case "collection_invite": + case "photos_shared": + return CHANNEL_INVITES; + default: + return CHANNEL; + } + } + + static void ensureChannel(Context context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return; + NotificationManager manager = context.getSystemService(NotificationManager.class); + if (manager == null) return; + create(manager, CHANNEL_CHAT, context.getString(R.string.push_channel_chat), NotificationManager.IMPORTANCE_HIGH); + create(manager, CHANNEL_TRIPS, context.getString(R.string.push_channel_trips), NotificationManager.IMPORTANCE_DEFAULT); + create(manager, CHANNEL_INVITES, context.getString(R.string.push_channel_invites), NotificationManager.IMPORTANCE_DEFAULT); + create(manager, CHANNEL, context.getString(R.string.push_channel_name), NotificationManager.IMPORTANCE_DEFAULT); + com.liketrek.trek.tripday.TripDayNotification.INSTANCE.ensureChannel(context); + } + + @androidx.annotation.RequiresApi(Build.VERSION_CODES.O) + private static void create(NotificationManager manager, String id, String name, int importance) { + NotificationChannel existing = manager.getNotificationChannel(id); + if (existing != null) { + // Only the name follows the app's language; what the user set stays theirs. + if (!name.contentEquals(existing.getName())) { + existing.setName(name); + manager.createNotificationChannel(existing); + } + return; + } + manager.createNotificationChannel(new NotificationChannel(id, name, importance)); + } + + private static void show(Context context, String title, String body, String url, String tag, String event) { + ensureChannel(context); + Intent open = new Intent(context, MainActivity.class) + .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); + if (url != null) open.putExtra(EXTRA_URL, url); + int id = tag != null ? tag.hashCode() : (int) (System.currentTimeMillis() & 0x7fffffff); + PendingIntent tap = PendingIntent.getActivity( + context, + id, + open, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE + ); + String channel = channelFor(event); + NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel) + .setSmallIcon(R.drawable.ic_stat_trek) + .setContentTitle(title) + .setContentText(body) + .setStyle(new NotificationCompat.BigTextStyle().bigText(body)) + .setAutoCancel(true) + .setColor(ContextCompat.getColor(context, R.color.notification_accent)) + .setCategory(CHANNEL_CHAT.equals(channel) ? NotificationCompat.CATEGORY_MESSAGE : NotificationCompat.CATEGORY_EVENT) + // One stack per kind in the shade, rather than a loose pile. + .setGroup("trek." + channel) + .setContentIntent(tap); + if (Build.VERSION.SDK_INT >= 33 + && ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { + return; + } + try { + NotificationManagerCompat.from(context).notify(tag, id, builder.build()); + // The stack's head: the system folds the group under it from two notifications on. + NotificationCompat.Builder summary = new NotificationCompat.Builder(context, channel) + .setSmallIcon(R.drawable.ic_stat_trek) + .setColor(ContextCompat.getColor(context, R.color.notification_accent)) + .setGroup("trek." + channel) + .setGroupSummary(true) + .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN) + .setAutoCancel(true); + NotificationManagerCompat.from(context).notify("trek.summary", channel.hashCode(), summary.build()); + } catch (SecurityException notAllowed) { + // Notifications switched off for the app since it subscribed. + } + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekServerStore.java b/client/android/app/src/main/java/com/liketrek/trek/TrekServerStore.java new file mode 100644 index 000000000..84ce945c0 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekServerStore.java @@ -0,0 +1,290 @@ +package com.liketrek.trek; + +import android.content.Context; +import android.content.SharedPreferences; +import com.getcapacitor.CapConfig; +import com.getcapacitor.Logger; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import org.json.JSONException; +import org.json.JSONObject; + +/** The server the user picked, and the Capacitor configuration that loads it. */ +final class TrekServerStore { + + private static final String PREFS = "trek_shell"; + private static final String KEY_URL = "server_url"; + private static final String KEY_PREVIOUS_URL = "previous_server_url"; + private static final String KEY_SERVER_CHECK = "server_check"; + private static final String KEY_LABEL_SIGN_IN_HINT = "label_sign_in_hint"; + private static final String KEY_LABEL_CHANGE_SERVER = "label_change_server"; + private static final String KEY_LABEL_ERROR_PAGE_HINT = "label_error_page_hint"; + + /** + * The server API this build needs (MIN_NATIVE_API in serverAddress.ts). A + * server remembered under a lower value is checked once more: the first + * launch after an update that raised it puts the address screen back up, + * filled in with that server (getPreviousUrl). Raise both together. + */ + private static final int SERVER_CHECK = 3; + private static final String KEY_SIGN_IN_HOSTS = "sign_in_hosts"; + private static final String KEY_SHELL_ONCE = "shell_once"; + private static final String KEY_RESTART = "restart"; + private static final String KEY_OFFLINE_START = "offline_start"; + private static final String KEY_WELCOME = "welcome"; + private static final String CONFIG_DIR = "trek-server-config"; + + private TrekServerStore() {} + + /** + * The one-time code of a TREK Cloud purchase (setServer's `welcome`). The + * server's first page opens its welcome page with it once, which signs the + * buyer in (TrekWebViewClient). Kept only until the restart has loaded. + */ + static void setWelcome(Context context, String code) { + SharedPreferences.Editor editor = prefs(context).edit(); + if (code == null) editor.remove(KEY_WELCOME); + else editor.putString(KEY_WELCOME, code); + editor.commit(); + } + + /** The welcome page for the pending code, handed out once; null when there is none. */ + static String takeWelcomeUrl(Context context) { + String code = prefs(context).getString(KEY_WELCOME, null); + String server = getUrl(context); + if (code == null) return null; + prefs(context).edit().remove(KEY_WELCOME).commit(); + if (server == null) return null; + return (server.endsWith("/") ? server : server + "/") + "api/managed/welcome#" + code; + } + + static String getUrl(Context context) { + return prefs(context).getString(KEY_URL, null); + } + + /** Runs before the bridge is built, so a server picked under an older minimum is not loaded unchecked. */ + static void recheckAfterUpdate(Context context) { + SharedPreferences prefs = prefs(context); + if (prefs.getInt(KEY_SERVER_CHECK, 0) >= SERVER_CHECK) return; + String server = getUrl(context); + SharedPreferences.Editor editor = prefs.edit().putInt(KEY_SERVER_CHECK, SERVER_CHECK); + if (server != null) editor.remove(KEY_URL).remove(KEY_SIGN_IN_HOSTS).putString(KEY_PREVIOUS_URL, server); + editor.commit(); + } + + /** + * The words of the bar over a proxy's sign-in page, in the user's language, + * as the address screen passed them (setServer's `labels`): the server's UI + * is not there to say them. Null keeps the English fallback. + */ + static void setLabels(Context context, String signInHint, String changeServer, String errorPageHint) { + SharedPreferences.Editor editor = prefs(context).edit(); + if (signInHint != null) editor.putString(KEY_LABEL_SIGN_IN_HINT, signInHint); + if (changeServer != null) editor.putString(KEY_LABEL_CHANGE_SERVER, changeServer); + if (errorPageHint != null) editor.putString(KEY_LABEL_ERROR_PAGE_HINT, errorPageHint); + editor.commit(); + } + + static String errorPageHintLabel(Context context) { + return prefs(context).getString( + KEY_LABEL_ERROR_PAGE_HINT, + "This page is not from TREK: the server or a proxy in front of it refused the app. Check your proxy or certificate, or change the server." + ); + } + + static String signInHintLabel(Context context) { + return prefs(context).getString( + KEY_LABEL_SIGN_IN_HINT, + "Passkeys and security keys do not work on this page in the app. Sign in with a password, or let the app through your proxy." + ); + } + + static String changeServerLabel(Context context) { + return prefs(context).getString(KEY_LABEL_CHANGE_SERVER, "Change server"); + } + + /** The server an update asked to check again, until a server is set. */ + static String getPreviousUrl(Context context) { + return prefs(context).getString(KEY_PREVIOUS_URL, null); + } + + /** Remembers the server; its sign-in hosts go with it and are replaced or dropped too. */ + static void setUrl(Context context, String url) { + setServer(context, url, null); + } + + static void setServer(Context context, String url, Set signInHosts) { + SharedPreferences.Editor editor = prefs(context).edit(); + if (url == null) { + editor.remove(KEY_URL); + } else { + editor.putString(KEY_URL, url).remove(KEY_PREVIOUS_URL); + } + if (signInHosts == null || signInHosts.isEmpty()) { + editor.remove(KEY_SIGN_IN_HOSTS); + } else { + Set lower = new HashSet<>(); + for (String host : signInHosts) lower.add(host.toLowerCase(Locale.ROOT)); + editor.putStringSet(KEY_SIGN_IN_HOSTS, lower); + } + editor.commit(); + } + + /** + * The hosts of a sign-in page that stands in front of the server (a proxy + * such as Cloudflare Access or Pangolin), as the address screen found them. + * Only these may load inside the web view besides the server itself, so + * the proxy's session lands where the app can use it (TrekWebViewClient). + */ + static Set getSignInHosts(Context context) { + Set hosts = prefs(context).getStringSet(KEY_SIGN_IN_HOSTS, null); + return hosts == null ? Collections.emptySet() : Collections.unmodifiableSet(new HashSet<>(hosts)); + } + + /** Keeps one more sign-in host for the remembered server, as the web view met it (SignInRedirect). */ + static void addSignInHost(Context context, String host) { + Set hosts = new HashSet<>(getSignInHosts(context)); + if (!hosts.add(host.toLowerCase(Locale.ROOT))) return; + prefs(context).edit().putStringSet(KEY_SIGN_IN_HOSTS, hosts).commit(); + } + + /** Start the next launch on the bundled address screen, even with a server remembered. */ + private static final String KEY_FAILURE = "last_failure"; + + /** + * Why the server's page did not load, in the WebView's own terms + * ("net::ERR_NAME_NOT_RESOLVED (-2)", "HTTP 503"): the address screen shows + * it small under its message, so a report carries the cause. + */ + static void setFailure(Context context, String failure) { + prefs(context).edit().putString(KEY_FAILURE, failure).commit(); + } + + /** The failure behind this address screen, once. */ + static String takeFailure(Context context) { + String failure = prefs(context).getString(KEY_FAILURE, null); + if (failure != null) prefs(context).edit().remove(KEY_FAILURE).commit(); + return failure; + } + + static void showShellOnce(Context context) { + prefs(context).edit().putBoolean(KEY_SHELL_ONCE, true).commit(); + } + + static boolean consumeShellOnce(Context context) { + return consume(context, KEY_SHELL_ONCE); + } + + /** The next onCreate is the app restarting itself, not a launch. */ + static void markRestart(Context context) { + prefs(context).edit().putBoolean(KEY_RESTART, true).commit(); + } + + static boolean consumeRestart(Context context) { + return consume(context, KEY_RESTART); + } + + /** The next onCreate starts on the stored copy of the server's UI (TrekOfflineShell). */ + static void markOfflineStart(Context context) { + prefs(context).edit().putBoolean(KEY_OFFLINE_START, true).commit(); + } + + static boolean consumeOfflineStart(Context context) { + return consume(context, KEY_OFFLINE_START); + } + + /** + * The remembered server, or the one an update asked to check again: the + * server the stored copy of the UI belongs to. + */ + static String getUrlOrPrevious(Context context) { + String url = getUrl(context); + return url != null ? url : getPreviousUrl(context); + } + + /** + * Starting on the stored copy while the check an update asked for could not + * run: the server goes back in place, unchecked for now, and the check runs + * again on the next launch, which reaches the server. + */ + static void restoreForOffline(Context context) { + SharedPreferences prefs = prefs(context); + if (prefs.getString(KEY_URL, null) != null) return; + String previous = prefs.getString(KEY_PREVIOUS_URL, null); + if (previous == null) return; + prefs.edit().putString(KEY_URL, previous).remove(KEY_PREVIOUS_URL).putInt(KEY_SERVER_CHECK, 0).commit(); + } + + private static boolean consume(Context context, String key) { + boolean set = prefs(context).getBoolean(key, false); + if (set) prefs(context).edit().remove(key).commit(); + return set; + } + + /** + * The bundled capacitor.config.json, adjusted for this start. Capacitor only + * takes these settings from a config file, so this writes a copy into the + * app's private storage and loads that; null means the bundled one as it is. + * + * With a server: server.url set, and server.errorPath dropped, because that + * page would have no bridge on the server's origin (TrekWebViewClient + * handles a failed load instead). + * + * On a restart: no launch splash. The splash plugin shows it again after + * recreate() but cannot take it down when the page hides it early, which + * left it covering a fully rendered page. A restart has no launch to cover. + */ + static CapConfig configFor(Context context, String url, boolean restarting) { + if (url == null && !restarting) return null; + try { + JSONObject json = new JSONObject(readAsset(context, "capacitor.config.json")); + if (url != null) { + JSONObject server = child(json, "server"); + server.put("url", url); + server.remove("errorPath"); + } + if (restarting) { + child(child(json, "plugins"), "SplashScreen").put("launchShowDuration", 0); + } + + File dir = new File(context.getFilesDir(), CONFIG_DIR); + if (!dir.isDirectory() && !dir.mkdirs()) throw new IOException("Cannot create " + dir); + try (FileOutputStream out = new FileOutputStream(new File(dir, "capacitor.config.json"))) { + out.write(json.toString().getBytes(StandardCharsets.UTF_8)); + } + return CapConfig.loadFromFile(context, dir.getAbsolutePath()); + } catch (IOException | JSONException ex) { + Logger.error("TrekShell", "Could not adjust the app config for " + url, ex); + return null; + } + } + + private static JSONObject child(JSONObject parent, String key) throws JSONException { + JSONObject existing = parent.optJSONObject(key); + if (existing != null) return existing; + JSONObject created = new JSONObject(); + parent.put(key, created); + return created; + } + + private static String readAsset(Context context, String name) throws IOException { + try (InputStream in = context.getAssets().open(name); ByteArrayOutputStream out = new ByteArrayOutputStream()) { + byte[] buffer = new byte[8192]; + int read; + while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read); + return out.toString("UTF-8"); + } + } + + private static SharedPreferences prefs(Context context) { + return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekSharedFiles.java b/client/android/app/src/main/java/com/liketrek/trek/TrekSharedFiles.java new file mode 100644 index 000000000..26b9a171d --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekSharedFiles.java @@ -0,0 +1,105 @@ +package com.liketrek.trek; + +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; +import android.provider.OpenableColumns; +import android.util.Base64; +import com.getcapacitor.JSObject; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; + +/** + * Booking documents shared to TREK (open with / share), held until the UI takes + * them (TrekShell.takeSharedFile) and announced if it is already running. + */ +final class TrekSharedFiles { + /** Above this the file is not a booking confirmation. */ + private static final int MAX_BYTES = 15 * 1024 * 1024; + + interface Listener { + void onFile(JSObject file); + } + + private static JSObject pending; + private static Listener listener; + + private TrekSharedFiles() {} + + static void setListener(Listener l) { + listener = l; + } + + static JSObject take() { + JSObject file = pending; + pending = null; + return file; + } + + static void receive(Context context, Intent intent) { + if (intent == null) return; + if (MainActivity.ACTION_SHARE_HANDOFF.equals(intent.getAction())) { + receiveHandoff(context); + return; + } + Uri uri = null; + // A view intent also brings sign-in callbacks and widget links; only a file is a document. + if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null + && "content".equals(intent.getData().getScheme())) { + uri = intent.getData(); + } + else if (Intent.ACTION_SEND.equals(intent.getAction())) uri = intent.getParcelableExtra(Intent.EXTRA_STREAM); + // content:// only: a file:// path would be read with TREK's own rights. + if (uri == null || !"content".equals(uri.getScheme())) return; + try (InputStream in = context.getContentResolver().openInputStream(uri)) { + if (in == null) return; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[16384]; + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + if (out.size() > MAX_BYTES) return; + } + JSObject file = new JSObject(); + file.put("name", displayName(context, uri)); + String type = context.getContentResolver().getType(uri); + file.put("mimeType", type == null ? intent.getType() : type); + file.put("data", Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP)); + pending = file; + if (listener != null) listener.onFile(file); + } catch (Exception ignored) { + // Unreadable or gone: nothing to import. + } + } + + /** The item the share sheet left (share/ShareHandoff.kt), with the trip picked for it there. */ + static void receiveHandoff(Context context) { + kotlin.Pair item = com.liketrek.trek.share.ShareHandoff.INSTANCE.take(context); + if (item == null || item.getSecond().length > MAX_BYTES) return; + org.json.JSONObject meta = item.getFirst(); + JSObject file = new JSObject(); + file.put("name", meta.optString("name", "booking")); + file.put("mimeType", meta.optString("mimeType", "application/octet-stream")); + file.put("data", Base64.encodeToString(item.getSecond(), Base64.NO_WRAP)); + if (meta.has("tripId")) file.put("tripId", meta.optLong("tripId")); + // A page or a link: where it came from, so the UI can keep it among the trip's links. + String url = meta.optString("url", ""); + if (url.startsWith("https://") || url.startsWith("http://")) { + file.put("url", url); + file.put("title", meta.optString("title", url)); + } + pending = file; + if (listener != null) listener.onFile(file); + } + + private static String displayName(Context context, Uri uri) { + try (Cursor cursor = context.getContentResolver().query(uri, new String[] { OpenableColumns.DISPLAY_NAME }, null, null, null)) { + if (cursor != null && cursor.moveToFirst()) return cursor.getString(0); + } catch (Exception ignored) { + // Fall through to the path. + } + String last = uri.getLastPathSegment(); + return last == null ? "booking" : last; + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java new file mode 100644 index 000000000..9d609a081 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java @@ -0,0 +1,994 @@ +package com.liketrek.trek; + +import android.Manifest; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.util.Log; +import androidx.activity.result.ActivityResult; +import com.liketrek.trek.clientcert.ClientCertActions; +import com.liketrek.trek.clientcert.TrekClientIdentity; +import androidx.browser.customtabs.CustomTabsIntent; +import androidx.core.app.NotificationManagerCompat; +import com.getcapacitor.JSArray; +import com.getcapacitor.JSObject; +import com.getcapacitor.PermissionState; +import com.getcapacitor.Plugin; +import com.getcapacitor.PluginCall; +import com.getcapacitor.PluginMethod; +import com.getcapacitor.annotation.ActivityCallback; +import com.getcapacitor.annotation.CapacitorPlugin; +import com.getcapacitor.annotation.Permission; +import com.getcapacitor.annotation.PermissionCallback; +import com.google.firebase.messaging.FirebaseMessaging; +import java.util.HashSet; +import java.util.Set; +import org.json.JSONObject; + +/** The native half of client/src/native/trekShell.ts. */ +@CapacitorPlugin( + name = "TrekShell", + permissions = { + @Permission(strings = { Manifest.permission.POST_NOTIFICATIONS }, alias = "notifications"), + @Permission(strings = { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }, alias = "location"), + } +) +public class TrekShellPlugin extends Plugin { + + private static final String TAG = "TrekShell"; + + /** How long to wait after returning from the browser for the redirect to land. */ + private static final long CANCEL_GRACE_MS = 600; + + private String authCallId; + private String authScheme; + private boolean authBrowserOpen; + private final Handler handler = new Handler(Looper.getMainLooper()); + + /** + * What this binary offers the server's UI, raised with every native feature + * an older binary lacks. The UI asks before it calls (native/capabilities.ts), + * and a server can require a minimum (minNativeShellApi in /api/health/features). + */ + static final int SHELL_API = 2; + /** The native features by name, so the UI can turn each on by itself. */ + static final String[] FEATURES = { + "capabilities", + "biometricLock", + "sharedFiles", + "nativePush", + "geolocation", + "tileCache", + "widgets", + "widgetTrips", + "liveActivity", + "shareSheet", + "playBilling", + "googleWallet", + "keyCommands", + "windowLayout", + "clientCertificate", + "filePreview", + }; + + /** liketrek's push relay: the endpoint for this device's FCM token (trek-hosted push-relay.ts). */ + static final String PUSH_RELAY = "https://push.liketrek.com/v1/fcm/"; + + /** The notification the app was started from, until the UI asks for it. */ + private String openedPushUrl; + + @PluginMethod + public void getCapabilities(PluginCall call) { + JSObject result = new JSObject(); + result.put("shellApi", SHELL_API); + result.put("platform", "android"); + String version = ""; + String build = ""; + try { + android.content.pm.PackageInfo info = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0); + version = info.versionName == null ? "" : info.versionName; + build = String.valueOf(androidx.core.content.pm.PackageInfoCompat.getLongVersionCode(info)); + } catch (android.content.pm.PackageManager.NameNotFoundException ignored) { + // Our own package is always there; the fields simply stay empty. + } + result.put("appVersion", version); + result.put("build", build); + com.getcapacitor.JSArray features = new com.getcapacitor.JSArray(); + for (String feature : FEATURES) features.put(feature); + result.put("features", features); + call.resolve(result); + } + + // ---- Shared booking documents ---- + + @Override + public void load() { + TrekSharedFiles.setListener(file -> notifyListeners("sharedFile", file)); + // A reloaded page starts without a stream; whatever the old one ran is stopped. + if (location != null) location.stop(); + locationActive = false; + // A pending purchase that cleared while the shell runs: redeemed like a restore. + com.liketrek.trek.billing.TrekBilling.INSTANCE.setOnTransaction(receipt -> { + notifyListeners("storeTransaction", receipt); + return kotlin.Unit.INSTANCE; + }); + com.liketrek.trek.screen.TrekKeyCommands.INSTANCE.setOnPress(id -> { + JSObject pressed = new JSObject(); + pressed.put("id", id); + notifyListeners("keyCommand", pressed); + return kotlin.Unit.INSTANCE; + }); + if (getActivity() != null) { + com.liketrek.trek.screen.TrekWindowLayout.INSTANCE.observe(getActivity(), layout -> { + notifyListeners("windowLayout", layout); + return kotlin.Unit.INSTANCE; + }); + } + if (getActivity() != null && getActivity().getIntent() != null) { + openedPushUrl = getActivity().getIntent().getStringExtra(TrekPushService.EXTRA_URL); + getActivity().getIntent().removeExtra(TrekPushService.EXTRA_URL); + } + } + + // ---- Push ---- + + /** + * Permission, the FCM token and the device keys, as the Web Push subscription + * the server stores (native/push.ts). Rejects with DENIED when the user + * refuses notifications, as on iOS. + */ + @PluginMethod + public void registerPush(PluginCall call) { + if (Build.VERSION.SDK_INT >= 33 && getPermissionState("notifications") != PermissionState.GRANTED) { + requestPermissionForAlias("notifications", call, "pushPermissionAnswered"); + return; + } + subscribePush(call); + } + + @PermissionCallback + private void pushPermissionAnswered(PluginCall call) { + if (getPermissionState("notifications") != PermissionState.GRANTED) { + call.reject("Notifications are not allowed", "DENIED"); + return; + } + subscribePush(call); + } + + private void subscribePush(PluginCall call) { + if (!NotificationManagerCompat.from(getContext()).areNotificationsEnabled()) { + call.reject("Notifications are not allowed", "DENIED"); + return; + } + TrekPushService.ensureChannel(getContext()); + final TrekPushKeys keys; + try { + keys = TrekPushKeys.loadOrCreate(getContext()); + } catch (Exception e) { + call.reject("Could not create the push keys", e); + return; + } + FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> { + if (!task.isSuccessful() || task.getResult() == null) { + call.reject("Could not get a push token", task.getException()); + return; + } + JSObject subscription = new JSObject(); + subscription.put("endpoint", PUSH_RELAY + task.getResult()); + JSObject keyObject = new JSObject(); + keyObject.put("p256dh", TrekPushKeys.base64url(keys.publicKey)); + keyObject.put("auth", TrekPushKeys.base64url(keys.auth)); + subscription.put("keys", keyObject); + call.resolve(subscription); + }); + } + + @PluginMethod + public void takeOpenedPush(PluginCall call) { + JSObject result = new JSObject(); + result.put("url", openedPushUrl == null ? JSONObject.NULL : openedPushUrl); + openedPushUrl = null; + call.resolve(result); + } + + /** The document shared to TREK before the UI was there to hear of it. */ + @PluginMethod + public void takeSharedFile(PluginCall call) { + JSObject result = new JSObject(); + JSObject file = TrekSharedFiles.take(); + result.put("file", file == null ? JSONObject.NULL : file); + call.resolve(result); + } + + // ---- App lock ---- + + private static final int AUTHENTICATORS = + androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_WEAK + | androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL; + + /** Which biometry the device offers for the app lock, if any. */ + @PluginMethod + public void biometryInfo(PluginCall call) { + int status = androidx.biometric.BiometricManager.from(getContext()).canAuthenticate(AUTHENTICATORS); + JSObject result = new JSObject(); + result.put("available", status == androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS); + result.put("type", "biometric"); + call.resolve(result); + } + + /** The system biometric prompt with the screen lock as the way out. */ + @PluginMethod + public void authenticateBiometric(PluginCall call) { + String reason = call.getString("reason", "Unlock TREK"); + getActivity().runOnUiThread(() -> { + androidx.fragment.app.FragmentActivity activity = (androidx.fragment.app.FragmentActivity) getActivity(); + androidx.biometric.BiometricPrompt prompt = new androidx.biometric.BiometricPrompt( + activity, + androidx.core.content.ContextCompat.getMainExecutor(getContext()), + new androidx.biometric.BiometricPrompt.AuthenticationCallback() { + @Override + public void onAuthenticationSucceeded(androidx.biometric.BiometricPrompt.AuthenticationResult result) { + JSObject ok = new JSObject(); + ok.put("ok", true); + call.resolve(ok); + } + + @Override + public void onAuthenticationError(int code, CharSequence message) { + boolean cancelled = code == androidx.biometric.BiometricPrompt.ERROR_USER_CANCELED + || code == androidx.biometric.BiometricPrompt.ERROR_NEGATIVE_BUTTON + || code == androidx.biometric.BiometricPrompt.ERROR_CANCELED; + call.reject(message.toString(), cancelled ? "CANCELLED" : "FAILED"); + } + } + ); + androidx.biometric.BiometricPrompt.PromptInfo info = new androidx.biometric.BiometricPrompt.PromptInfo.Builder() + .setTitle(reason) + .setAllowedAuthenticators(AUTHENTICATORS) + .build(); + prompt.authenticate(info); + }); + } + + /** While on, the recent-apps screen shows no snapshot of the app. */ + @PluginMethod + public void setPrivacyCover(PluginCall call) { + boolean enabled = Boolean.TRUE.equals(call.getBoolean("enabled", false)); + getActivity().runOnUiThread(() -> { + if (android.os.Build.VERSION.SDK_INT >= 33) { + getActivity().setRecentsScreenshotEnabled(!enabled); + } else if (enabled) { + getActivity().getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE); + } else { + getActivity().getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE); + } + }); + call.resolve(); + } + + /** + * Opens a file the UI wrote to the cache in the app that views it, a PDF in + * the system's PDF viewer, instead of the share sheet. "unsupported" where no + * app on the device views the type; the UI then hands it to the share sheet. + */ + @PluginMethod + public void previewFile(PluginCall call) { + String path = call.getString("path"); + Uri parsed = path == null ? null : Uri.parse(path); + java.io.File file = parsed != null && "file".equals(parsed.getScheme()) && parsed.getPath() != null ? new java.io.File(parsed.getPath()) : null; + java.io.File cache = getContext().getCacheDir(); + boolean inCache; + try { + inCache = file != null && file.getCanonicalPath().startsWith(cache.getCanonicalPath() + java.io.File.separator); + } catch (java.io.IOException e) { + inCache = false; + } + if (!inCache || !file.isFile()) { + call.reject("a file in the app's cache is required", "INVALID"); + return; + } + String type = call.getString("mimeType", "application/octet-stream"); + Uri content = androidx.core.content.FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", file); + Intent view = new Intent(Intent.ACTION_VIEW) + .setDataAndType(content, type) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK); + getActivity().runOnUiThread(() -> { + JSObject result = new JSObject(); + try { + getActivity().startActivity(view); + result.put("result", "shown"); + } catch (ActivityNotFoundException e) { + result.put("result", "unsupported"); + } + call.resolve(result); + }); + } + + @PluginMethod + public void getServer(PluginCall call) { + String url = TrekServerStore.getUrl(getContext()); + String previous = TrekServerStore.getPreviousUrl(getContext()); + JSObject result = new JSObject(); + result.put("url", url == null ? JSONObject.NULL : url); + result.put("previousUrl", previous == null ? JSONObject.NULL : previous); + String failure = TrekServerStore.takeFailure(getContext()); + result.put("failure", failure == null ? JSONObject.NULL : failure); + call.resolve(result); + } + + @PluginMethod + public void setServer(PluginCall call) { + String url = call.getString("url"); + Uri parsed = url == null ? null : Uri.parse(url); + if (parsed == null || parsed.getHost() == null || !("https".equals(parsed.getScheme()) || "http".equals(parsed.getScheme()))) { + call.reject("A http(s) URL is required"); + return; + } + TrekServerStore.setServer(getContext(), url, signInHostsOf(call)); + JSObject labels = call.getObject("labels"); + if (labels != null) { + TrekServerStore.setLabels( + getContext(), + labels.getString("signInHint"), + labels.getString("changeServer"), + labels.getString("errorPageHint") + ); + } + // A TREK Cloud purchase: the code that signs the buyer in, opened once after the first page. + String welcome = call.getString("welcome"); + TrekServerStore.setWelcome(getContext(), welcome != null && welcome.matches("[A-Za-z0-9_-]{43}") ? welcome : null); + call.resolve(); + restart(); + } + + /** The sign-in hosts the address screen passes along, plain host names only. */ + private static Set signInHostsOf(PluginCall call) { + Set hosts = new HashSet<>(); + JSArray list = call.getArray("signInHosts"); + if (list == null) return hosts; + for (int i = 0; i < list.length(); i++) { + String host = list.optString(i, ""); + if (host.matches("[A-Za-z0-9.-]+(:[0-9]+)?")) hosts.add(host); + } + return hosts; + } + + @PluginMethod + public void resetServer(PluginCall call) { + TrekServerStore.setUrl(getContext(), null); + call.resolve(); + restart(); + } + + @PluginMethod + public void reload(PluginCall call) { + call.resolve(); + restart(); + } + + /** The server URL is part of the bridge's configuration, so it takes a new activity. */ + private void restart() { + locationActive = false; + if (location != null) location.stop(); + TrekServerStore.markRestart(getContext()); + getActivity().runOnUiThread(() -> getActivity().recreate()); + } + + @PluginMethod + public void authenticate(PluginCall call) { + String url = call.getString("url"); + String scheme = call.getString("callbackScheme"); + if (url == null || scheme == null) { + call.reject("url and callbackScheme are required"); + return; + } + rejectPendingAuth("Superseded by a new sign-in"); + call.setKeepAlive(true); + getBridge().saveCall(call); + authCallId = call.getCallbackId(); + authScheme = scheme; + authBrowserOpen = true; + // A Custom Tab shares the browser's cookies, so a running SSO session at + // the identity provider carries over. The redirect back to the app's + // scheme arrives through the intent-filter in AndroidManifest.xml. + Uri target = Uri.parse(url); + getActivity().runOnUiThread(() -> openSignIn(target)); + } + + /** + * Opens the sign-in in a Custom Tab, or in the browser itself where no + * Custom Tab can come up. Launched on the UI thread: some devices dropped a + * launch from the bridge's thread without a word, and the sign-in then + * looked cancelled. A browser that cannot open at all is reported as such. + */ + private void openSignIn(Uri target) { + try { + new CustomTabsIntent.Builder().build().launchUrl(getActivity(), target); + return; + } catch (RuntimeException tabFailed) { + Log.w(TAG, "No Custom Tab for the sign-in, trying the browser", tabFailed); + } + try { + getActivity().startActivity(new Intent(Intent.ACTION_VIEW, target).addCategory(Intent.CATEGORY_BROWSABLE)); + } catch (RuntimeException browserFailed) { + Log.w(TAG, "No browser for the sign-in", browserFailed); + PluginCall call = pendingAuthCall(); + if (call == null) return; + call.reject("No browser could open the sign-in", "NO_BROWSER"); + finishAuth(call); + } + } + + @Override + protected void handleOnNewIntent(Intent intent) { + super.handleOnNewIntent(intent); + String pushUrl = intent.getStringExtra(TrekPushService.EXTRA_URL); + if (pushUrl != null) { + intent.removeExtra(TrekPushService.EXTRA_URL); + JSObject opened = new JSObject(); + opened.put("url", pushUrl); + notifyListeners("pushOpened", opened); + return; + } + Uri data = intent.getData(); + PluginCall call = pendingAuthCall(); + if (call == null) { + keepOrphanAuthReturn(intent); + return; + } + if (data == null || !authScheme.equals(data.getScheme())) return; + JSObject result = new JSObject(); + result.put("url", data.toString()); + call.resolve(result); + finishAuth(call); + } + + /** + * Back in the app without a redirect means the user closed the browser. + * onNewIntent runs before onResume when the redirect did arrive, so the + * grace period only covers devices that deliver the two out of order. + */ + @Override + protected void handleOnResume() { + super.handleOnResume(); + if (locationActive && location != null && locationAllowed()) location.start(locationHighAccuracy); + if (!authBrowserOpen) return; + authBrowserOpen = false; + handler.postDelayed(() -> { + PluginCall call = pendingAuthCall(); + if (call == null) return; + call.reject("Sign-in cancelled", "CANCELLED"); + finishAuth(call); + }, CANCEL_GRACE_MS); + } + + private static final String AUTH_PREFS = "trek_auth_return"; + /** As long as the server keeps the code it carries (NATIVE_HANDOFF_CODE_TTL_MS), with room to spare. */ + private static final long ORPHAN_AUTH_TTL_MS = 2 * 60 * 1000; + + /** + * A return to the sign-in scheme with no call waiting for it: Android ended + * the app while the browser was in front, and the browser's return started + * it anew (the launch intent comes through here as well). Kept on disk, as + * the process may be new too, until the sign-in page takes it. The return + * is then taken off the activity's intent: Capacitor hands the launch intent + * in again whenever the activity is created, and Android does as well when + * it rebuilds the task from the recent apps. + */ + private void keepOrphanAuthReturn(Intent intent) { + Uri data = intent.getData(); + if (data == null || !"auth".equals(data.getHost())) return; + if (!getContext().getString(R.string.custom_url_scheme).equals(data.getScheme())) return; + if (getActivity() != null && getActivity().getIntent() != null && getActivity().getIntent().getData() != null + && data.equals(getActivity().getIntent().getData())) { + getActivity().setIntent(new Intent(getActivity().getIntent()).setData(null)); + } + if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) return; + getContext().getSharedPreferences(AUTH_PREFS, Context.MODE_PRIVATE) + .edit() + .putString("url", data.toString()) + .putLong("at", System.currentTimeMillis()) + .commit(); + } + + /** The kept return of a sign-in (keepOrphanAuthReturn), once and while fresh; null otherwise. */ + @PluginMethod + public void takeAuthCallback(PluginCall call) { + android.content.SharedPreferences prefs = getContext().getSharedPreferences(AUTH_PREFS, Context.MODE_PRIVATE); + String url = prefs.getString("url", null); + long at = prefs.getLong("at", 0); + prefs.edit().clear().commit(); + boolean fresh = url != null && System.currentTimeMillis() - at <= ORPHAN_AUTH_TTL_MS; + JSObject result = new JSObject(); + result.put("url", fresh ? url : JSONObject.NULL); + call.resolve(result); + } + + private PluginCall pendingAuthCall() { + return authCallId == null ? null : getBridge().getSavedCall(authCallId); + } + + private void rejectPendingAuth(String message) { + PluginCall call = pendingAuthCall(); + if (call == null) return; + call.reject(message, "CANCELLED"); + finishAuth(call); + } + + private void finishAuth(PluginCall call) { + getBridge().releaseCall(call); + authCallId = null; + authScheme = null; + authBrowserOpen = false; + } + + /** + * Keeps the server's UI on the device for a start without the server + * (TrekOfflineShell): the start page, and each file of the build that + * native/offlineShell.ts lists from the server's manifest and the copy does + * not hold yet. Once all of them are there, files of older builds go. A web + * view runs no service worker on a plain-http server, the usual address of a + * server at home, so without this the app could not start away from it. + */ + @PluginMethod + public void refreshOfflineCopy(PluginCall call) { + Context context = getContext(); + String server = TrekServerStore.getUrl(context); + JSArray listed = call.getArray("files"); + if (server == null || TrekOfflineShell.isActive()) { + JSObject result = new JSObject(); + result.put("saved", false); + call.resolve(result); + return; + } + new Thread(() -> { + JSObject result = new JSObject(); + byte[] page = download(server, "", "text/html"); + boolean complete = page != null && TrekOfflineShell.beginRefresh(context, server); + Set keep = new HashSet<>(); + if (complete && listed != null) { + for (int i = 0; i < listed.length(); i++) { + String path = listed.optString(i, null); + if (path == null || path.isEmpty()) continue; + String clean = path.startsWith("/") ? path.substring(1) : path; + keep.add(clean); + if (TrekOfflineShell.hasFile(context, clean)) continue; + byte[] data = download(server, clean, null); + if (data == null || !TrekOfflineShell.saveFile(context, clean, data)) complete = false; + } + } + // The new page goes in last: until all its files are there the + // stored page stays the previous one, whose build is still whole. + boolean saved = complete && TrekOfflineShell.savePage(context, server, page); + complete = saved; + if (saved && listed != null) TrekOfflineShell.prune(context, keep); + result.put("saved", saved); + result.put("complete", complete); + call.resolve(result); + }).start(); + } + + /** A file of the server's UI, or null: only a 200 counts, and the page only as HTML. */ + private static byte[] download(String server, String path, String wantType) { + java.net.HttpURLConnection connection = null; + try { + java.net.URL base = new java.net.URL(server.endsWith("/") ? server : server + "/"); + java.net.URL url = new java.net.URL(base, path); + connection = (java.net.HttpURLConnection) url.openConnection(); + connection.setConnectTimeout(15000); + connection.setReadTimeout(30000); + connection.setInstanceFollowRedirects(true); + if (wantType != null) connection.setRequestProperty("Accept", wantType); + if (connection.getResponseCode() != 200) return null; + String type = connection.getContentType(); + if (wantType != null && (type == null || !type.startsWith(wantType))) return null; + try (java.io.InputStream in = connection.getInputStream()) { + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + byte[] buffer = new byte[16384]; + for (int n = in.read(buffer); n > 0; n = in.read(buffer)) out.write(buffer, 0, n); + return out.toByteArray(); + } + } catch (java.io.IOException | RuntimeException e) { + return null; + } finally { + if (connection != null) connection.disconnect(); + } + } + + /** + * The address screen found the server out of reach: with a copy of its UI + * the app restarts on that instead (TrekOfflineShell), the same way it + * leaves the server for the address screen. Also for the server an update + * asked to check again, whose check then waits for the next launch. + */ + @PluginMethod + public void openOfflineCopy(PluginCall call) { + Context context = getContext(); + JSObject result = new JSObject(); + if (!TrekOfflineShell.hasCopy(context, TrekServerStore.getUrlOrPrevious(context)) || getActivity() == null) { + result.put("opened", false); + call.resolve(result); + return; + } + TrekServerStore.markOfflineStart(context); + result.put("opened", true); + call.resolve(result); + restart(); + } + + // ---- Widgets, shortcuts and the travel day ---- + + /** + * What the home-screen widgets show (native/widgets.ts), as JSON: "snapshot" + * (the dashboard's), "trip." or "trips" (the list a widget and the share + * sheet pick from). The widgets redraw, and a new trip list rebuilds the + * trip shortcuts. + */ + @PluginMethod + public void setWidgetSnapshot(PluginCall call) { + String json = call.getString("json"); + String key = call.getString("key", "snapshot"); + if (json == null) { + call.reject("json is required"); + return; + } + if (!com.liketrek.trek.widget.WidgetStore.INSTANCE.isValidKey(key)) { + call.reject("key must be snapshot, trips or trip."); + return; + } + android.content.Context context = getContext().getApplicationContext(); + try { + com.liketrek.trek.widget.WidgetStore.INSTANCE.write(context, key, json); + } catch (Exception e) { + call.reject("Could not store the widget snapshot", e); + return; + } + if ("trips".equals(key)) { + new Thread(() -> com.liketrek.trek.share.TrekShortcuts.INSTANCE.publish(context)).start(); + } else { + com.liketrek.trek.widget.TrekWidgetUpdater.refreshAll(context); + } + call.resolve(); + } + + /** Starts the travel day's Live Update, or updates the one showing. */ + @PluginMethod + public void syncTripDay(PluginCall call) { + String title = call.getString("tripTitle"); + String path = call.getString("path"); + String dayLabel = call.getString("dayLabel"); + String nextName = call.getString("nextName"); + if (title == null || path == null || dayLabel == null || nextName == null) { + call.reject("tripTitle, path, dayLabel and nextName are required"); + return; + } + java.util.List colors = new java.util.ArrayList<>(); + com.getcapacitor.JSArray raw = call.getArray("colors"); + if (raw != null) { + for (int i = 0; i < raw.length(); i++) colors.add(raw.isNull(i) ? null : raw.optString(i, null)); + } + com.liketrek.trek.tripday.TripDayNotification.State state = new com.liketrek.trek.tripday.TripDayNotification.State( + title, + path, + dayLabel, + nextName, + call.getString("nextTime"), + call.getInt("nextMinutes"), + call.getInt("done", 0), + call.getInt("total", 0), + colors + ); + boolean running = com.liketrek.trek.tripday.TripDayNotification.INSTANCE.show(getContext(), state); + JSObject result = new JSObject(); + result.put("running", running); + call.resolve(result); + } + + @PluginMethod + public void endTripDay(PluginCall call) { + com.liketrek.trek.tripday.TripDayNotification.INSTANCE.end(getContext()); + call.resolve(); + } + + // ---- Location ---- + + private com.liketrek.trek.location.TrekLocation location; + private boolean locationHighAccuracy; + + private com.liketrek.trek.location.TrekLocation location() { + if (location == null) { + location = new com.liketrek.trek.location.TrekLocation(getContext(), payload -> { + notifyListeners("location", payload); + return kotlin.Unit.INSTANCE; + }); + } + return location; + } + + /** Whether the app may know where the device is: precisely, or "Approximate" only. */ + private boolean locationAllowed() { + return androidx.core.content.ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) + == android.content.pm.PackageManager.PERMISSION_GRANTED + || androidx.core.content.ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) + == android.content.pm.PackageManager.PERMISSION_GRANTED; + } + + /** True while the UI has a stream running, so it resumes after the app was in the background. */ + private boolean locationActive; + + /** + * One location stream for the UI's navigator.geolocation, asking for the + * permission the first time. "Approximate" counts as allowed; the stream then + * runs on the coarse fixes Android gives. + */ + @PluginMethod + public void startLocation(PluginCall call) { + locationHighAccuracy = Boolean.TRUE.equals(call.getBoolean("highAccuracy", false)); + if (!locationAllowed()) { + requestPermissionForAlias("location", call, "locationPermissionAnswered"); + return; + } + locationActive = true; + location().start(locationHighAccuracy); + call.resolve(); + } + + @PermissionCallback + private void locationPermissionAnswered(PluginCall call) { + if (!locationAllowed()) { + location().emitError(1, "Location permission denied"); + } else { + locationActive = true; + location().start(locationHighAccuracy); + } + call.resolve(); + } + + @PluginMethod + public void stopLocation(PluginCall call) { + locationActive = false; + if (location != null) location.stop(); + call.resolve(); + } + + /** No location in the background, as in a browser: paused with the app, resumed with it. */ + @Override + protected void handleOnPause() { + super.handleOnPause(); + if (location != null) location.stop(); + } + + /** The page and the activity are gone: nothing can stop the stream any more but this. */ + @Override + protected void handleOnDestroy() { + locationActive = false; + if (location != null) location.stop(); + super.handleOnDestroy(); + } + + // ---- Map tile store ---- + + @PluginMethod + public void getTileCacheUsage(PluginCall call) { + new Thread(() -> { + JSObject result = new JSObject(); + result.put("bytes", com.liketrek.trek.tiles.TrekTileStore.INSTANCE.usage()); + result.put("limit", com.liketrek.trek.tiles.TrekTileStore.MAX_BYTES); + call.resolve(result); + }).start(); + } + + @PluginMethod + public void clearTileCache(PluginCall call) { + new Thread(() -> { + com.liketrek.trek.tiles.TrekTileStore.INSTANCE.clear(); + call.resolve(); + }).start(); + } + + // ---- Google Play Billing (the StoreKit methods' Android side) ---- + + @PluginMethod + public void storeProducts(PluginCall call) { + com.liketrek.trek.billing.TrekBilling.INSTANCE.products(getContext(), call); + } + + @PluginMethod + public void storePurchase(PluginCall call) { + com.liketrek.trek.billing.TrekBilling.INSTANCE.purchase(getActivity(), call); + } + + @PluginMethod + public void storeFinish(PluginCall call) { + com.liketrek.trek.billing.TrekBilling.INSTANCE.finish(getContext(), call); + } + + @PluginMethod + public void storeRestore(PluginCall call) { + com.liketrek.trek.billing.TrekBilling.INSTANCE.restore(getContext(), call); + } + + /** Whether this Google account already holds a delivered cloud subscription. */ + @PluginMethod + public void storeHeld(PluginCall call) { + com.liketrek.trek.billing.TrekBilling.INSTANCE.held(getContext(), call); + } + + /** A paid subscription never delivered (it cleared while the app was closed), for the shell to redeem. */ + @PluginMethod + public void storeUnfinished(PluginCall call) { + com.liketrek.trek.billing.TrekBilling.INSTANCE.unfinished(getContext(), call); + } + + // ---- Google Wallet ---- + + /** The only links this hands on: Google Wallet's save-to-wallet page. */ + static final String GOOGLE_WALLET_SAVE = "https://pay.google.com/gp/v/save/"; + + /** + * Feature googleWallet: a booking's pass, by the save link the TREK services + * signed, into Google Wallet. The Wallet app takes the link where it is + * installed, the browser otherwise. + */ + @PluginMethod + public void addToGoogleWallet(PluginCall call) { + String url = call.getString("url"); + if (url == null || !url.startsWith(GOOGLE_WALLET_SAVE)) { + call.reject("not a Google Wallet save link", "INVALID"); + return; + } + try { + getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).addCategory(Intent.CATEGORY_BROWSABLE)); + JSObject result = new JSObject(); + result.put("result", "opened"); + call.resolve(result); + } catch (android.content.ActivityNotFoundException e) { + call.reject("Nothing can open Google Wallet", "UNAVAILABLE"); + } + } + + // ---- Large screens and keyboards ---- + + /** Feature keyCommands: the UI's keyboard shortcuts for the screen it shows. */ + @PluginMethod + public void setKeyCommands(PluginCall call) { + com.liketrek.trek.screen.TrekKeyCommands.INSTANCE.set(call.getArray("commands")); + call.resolve(); + } + + /** Feature windowLayout: the window's size classes and a foldable's posture and hinge. */ + @PluginMethod + public void getWindowLayout(PluginCall call) { + // The last layout WindowManager reported, posture and hinge included; the bare window before the first. + getActivity().runOnUiThread(() -> call.resolve(com.liketrek.trek.screen.TrekWindowLayout.INSTANCE.current(getActivity()))); + } + + // ---- Client certificates (mutual TLS) ---- + + /** + * The address screen's check of a server, made natively so it notices + * whether the server asks for a client certificate and can show the stored + * one (clientcert/ClientCertActions.request). + */ + @PluginMethod + public void requestServer(PluginCall call) { + String url = call.getString("url"); + Uri parsed = url == null ? null : Uri.parse(url); + if (parsed == null || parsed.getHost() == null || !("https".equals(parsed.getScheme()) || "http".equals(parsed.getScheme()))) { + call.reject("A http(s) URL is required"); + return; + } + int timeout = Math.max(1000, Math.min(call.getInt("timeoutMs", 10000), 30000)); + new Thread(() -> { + try { + call.resolve(ClientCertActions.request(getContext(), url, timeout)); + } catch (Exception e) { + call.reject(e.getMessage() == null ? "request failed" : e.getMessage()); + } + }, "trek-request-server").start(); + } + + /** The stored certificate's details, or none. */ + @PluginMethod + public void clientCertificate(PluginCall call) { + TrekClientIdentity.Info info = TrekClientIdentity.info(getContext()); + JSObject result = new JSObject(); + result.put("certificate", info == null ? JSONObject.NULL : ClientCertActions.infoObject(info)); + TrekClientIdentity.Request asked = TrekClientIdentity.INSTANCE.getLastRequest(); + if (asked != null) { + JSObject request = new JSObject(); + request.put("host", asked.getHost()); + request.put("port", asked.getPort()); + request.put("served", asked.getServed()); + result.put("request", request); + } + call.resolve(result); + } + + @PluginMethod + public void removeClientCertificate(PluginCall call) { + TrekClientIdentity.remove(getContext()); + forgetCertificateAnswers(); + call.resolve(); + } + + /** The WebView keeps its answer to a certificate request per host; a changed certificate needs a fresh one. */ + private void forgetCertificateAnswers() { + com.liketrek.trek.clientcert.ClientCertWatch.reset(); + getActivity().runOnUiThread(() -> android.webkit.WebView.clearClientCertPreferences(null)); + } + + /** + * Picks a .p12/.pfx file, asks for its password until it opens or the user + * gives up, and keeps it for the server at host and port. Resolves with + * result "imported" (and the certificate), "cancelled", or "failed" and why. + */ + @PluginMethod + public void importClientCertificate(PluginCall call) { + String host = call.getString("host"); + if (host == null || !host.matches("[A-Za-z0-9.-]+")) { + call.reject("A host is required"); + return; + } + Intent pick = new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*"); + pick.putExtra(Intent.EXTRA_MIME_TYPES, new String[] { "application/x-pkcs12", "application/pkcs12", "application/octet-stream" }); + startActivityForResult(call, pick, "clientCertificatePicked"); + } + + @ActivityCallback + private void clientCertificatePicked(PluginCall call, ActivityResult picked) { + if (call == null) return; + Uri uri = picked.getData() == null ? null : picked.getData().getData(); + if (picked.getResultCode() != android.app.Activity.RESULT_OK || uri == null) { + resolveImport(call, "cancelled", null); + return; + } + new Thread(() -> { + byte[] bytes = ClientCertActions.readFile(getContext(), uri); + if (bytes == null) resolveImport(call, "failed", TrekClientIdentity.Failure.FORMAT.name()); + else askPasswordFor(call, bytes, false); + }, "trek-client-cert").start(); + } + + private void askPasswordFor(PluginCall call, byte[] bytes, boolean wrong) { + JSObject labels = call.getObject("labels", new JSObject()); + ClientCertActions.askPassword(getActivity(), labels, wrong, password -> { + if (password == null) { + resolveImport(call, "cancelled", null); + return kotlin.Unit.INSTANCE; + } + new Thread(() -> openWith(call, bytes, password), "trek-client-cert").start(); + return kotlin.Unit.INSTANCE; + }); + } + + private void openWith(PluginCall call, byte[] bytes, char[] password) { + try { + TrekClientIdentity.Identity identity = TrekClientIdentity.read(bytes, password); + TrekClientIdentity.save(getContext(), identity, call.getString("host"), call.getInt("port", 443)); + forgetCertificateAnswers(); + resolveImport(call, "imported", null); + } catch (TrekClientIdentity.ImportException e) { + if (e.getReason() == TrekClientIdentity.Failure.PASSWORD) askPasswordFor(call, bytes, true); + else resolveImport(call, "failed", e.getReason().name()); + } catch (Exception e) { + Log.w(TAG, "client certificate not kept", e); + resolveImport(call, "failed", "STORE"); + } finally { + java.util.Arrays.fill(password, '\0'); + } + } + + private void resolveImport(PluginCall call, String result, String failure) { + JSObject out = new JSObject(); + out.put("result", result); + if (failure != null) out.put("failure", failure.toLowerCase(java.util.Locale.ROOT)); + TrekClientIdentity.Info info = TrekClientIdentity.info(getContext()); + if ("imported".equals(result) && info != null) out.put("certificate", ClientCertActions.infoObject(info)); + call.resolve(out); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekWebPush.java b/client/android/app/src/main/java/com/liketrek/trek/TrekWebPush.java new file mode 100644 index 000000000..759231eaa --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekWebPush.java @@ -0,0 +1,84 @@ +package com.liketrek.trek; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.spec.ECPoint; +import java.security.spec.ECPublicKeySpec; +import java.util.Arrays; +import javax.crypto.Cipher; +import javax.crypto.KeyAgreement; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +/** + * Decrypts a Web Push record (RFC 8291, aes128gcm content coding of RFC 8188): + * the same thing a browser does, and the counterpart of the iOS notification + * extension's WebPushRecord. One record, as TREK's server always sends. + */ +final class TrekWebPush { + + private TrekWebPush() {} + + static byte[] decrypt(byte[] record, TrekPushKeys keys) throws Exception { + if (record.length < 21) throw new IllegalArgumentException("record too short"); + byte[] salt = Arrays.copyOfRange(record, 0, 16); + int idLength = record[20] & 0xff; + if (idLength != 65 || record.length < 21 + idLength + 17) throw new IllegalArgumentException("unexpected header"); + byte[] senderKey = Arrays.copyOfRange(record, 21, 21 + idLength); + byte[] ciphertext = Arrays.copyOfRange(record, 21 + idLength, record.length); + + KeyAgreement agreement = KeyAgreement.getInstance("ECDH"); + agreement.init(keys.privateKey); + agreement.doPhase(publicKeyFrom(senderKey, keys.privateKey), true); + byte[] shared = agreement.generateSecret(); + + byte[] keyInfo = concat("WebPush: info\0".getBytes(StandardCharsets.US_ASCII), keys.publicKey, senderKey); + byte[] ikm = hkdf(keys.auth, shared, keyInfo, 32); + byte[] cek = hkdf(salt, ikm, "Content-Encoding: aes128gcm\0".getBytes(StandardCharsets.US_ASCII), 16); + byte[] nonce = hkdf(salt, ikm, "Content-Encoding: nonce\0".getBytes(StandardCharsets.US_ASCII), 12); + + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(cek, "AES"), new GCMParameterSpec(128, nonce)); + byte[] padded = cipher.doFinal(ciphertext); + + // Padding: the content, one delimiter (2 for the last record), then zeros. + int end = padded.length - 1; + while (end >= 0 && padded[end] == 0) end--; + if (end < 0 || padded[end] != 2) throw new IllegalArgumentException("bad padding"); + return Arrays.copyOf(padded, end); + } + + private static ECPublicKey publicKeyFrom(byte[] point, ECPrivateKey onCurve) throws Exception { + if (point[0] != 0x04) throw new IllegalArgumentException("compressed key"); + BigInteger x = new BigInteger(1, Arrays.copyOfRange(point, 1, 33)); + BigInteger y = new BigInteger(1, Arrays.copyOfRange(point, 33, 65)); + return (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(x, y), onCurve.getParams())); + } + + /** HKDF-SHA256 (RFC 5869) for outputs of at most one block. */ + private static byte[] hkdf(byte[] salt, byte[] ikm, byte[] info, int length) throws Exception { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(salt, "HmacSHA256")); + byte[] prk = mac.doFinal(ikm); + mac.init(new SecretKeySpec(prk, "HmacSHA256")); + mac.update(info); + mac.update((byte) 1); + return Arrays.copyOf(mac.doFinal(), length); + } + + private static byte[] concat(byte[]... parts) { + int length = 0; + for (byte[] part : parts) length += part.length; + byte[] out = new byte[length]; + int offset = 0; + for (byte[] part : parts) { + System.arraycopy(part, 0, out, offset, part.length); + offset += part.length; + } + return out; + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java b/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java new file mode 100644 index 000000000..e7e7031d0 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/TrekWebViewClient.java @@ -0,0 +1,233 @@ +package com.liketrek.trek; + +import android.net.Uri; +import android.util.Log; +import android.webkit.ClientCertRequest; +import android.webkit.WebResourceError; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import com.getcapacitor.Bridge; +import com.getcapacitor.BridgeWebViewClient; +import com.liketrek.trek.clientcert.TrekClientIdentity; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import java.util.function.Consumer; + +/** + * Used while the WebView shows the user's server. When that server cannot be + * loaded, Capacitor would show server.errorPath, but on Android it injects + * its bridge only into the server's origin, so that local page could neither + * retry nor change the server and stayed blank. Instead the app restarts on + * the bundled address screen, where the bridge is present and the screen + * offers exactly those two things. + */ +class TrekWebViewClient extends BridgeWebViewClient { + + private final Runnable onUnreachable; + /** Told whether the page now shown is a proxy's sign-in page, for the bar with the way out. */ + private final Consumer onSignInPage; + /** Told whether the page now shown is an error page in place of the server's, for the same bar. */ + private final Consumer onErrorPage; + /** The main-frame address that last came back as a 4xx page nobody else handled. */ + private String errorPageUrl; + private final Set signInHosts; + /** A page of the server has shown since launch; from then on no sign-in host is learned (SignInRedirect). */ + private boolean serverShown; + /** The page itself failed on the network once already; the next failure goes to the address screen. */ + private boolean retriedMainFrame; + /** The page loaded again after a network error, until that load starts: its error page counts for nothing. */ + private String retryUrl; + private final Bridge bridge; + + TrekWebViewClient( + Bridge bridge, + Runnable onUnreachable, + Consumer onSignInPage, + Consumer onErrorPage, + Set signInHosts + ) { + super(bridge); + this.bridge = bridge; + this.onUnreachable = onUnreachable; + this.onSignInPage = onSignInPage; + this.onErrorPage = onErrorPage; + this.signInHosts = new HashSet<>(signInHosts); + } + + /** + * The sign-in page of a proxy in front of the server loads here rather than + * in the browser, so its session cookie is the web view's and every request + * of the app carries it, as in a browser. Only the hosts the address screen + * saw that proxy send it to (TrekServerStore.getSignInHosts), and only as a + * page: Capacitor injects its bridge into the server's origin alone, so the + * proxy's page gets no access to the app. Everything else goes on to + * Capacitor, which opens a foreign page in the browser. + */ + @Override + public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { + if (request.isForMainFrame() && isSignInHost(request.getUrl())) return false; + String learned = SignInRedirect.learnedHost( + TrekServerStore.getUrl(view.getContext()), + request.getUrl().toString(), + request.isForMainFrame(), + request.isRedirect(), + serverShown + ); + if (learned != null) { + signInHosts.add(learned); + TrekServerStore.addSignInHost(view.getContext(), learned); + return false; + } + return super.shouldOverrideUrlLoading(view, request); + } + + /** Every page the main frame shows, pushState included: is it a proxy's sign-in page? */ + @Override + public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { + super.doUpdateVisitedHistory(view, url, isReload); + if (retryUrl != null) return; + onSignInPage.accept(url != null && isSignInHost(Uri.parse(url))); + // The 4xx answer arrives before this commit or after it; either way the + // flag is read once here, so the next page clears the bar again. + boolean error = url != null && url.equals(errorPageUrl); + errorPageUrl = null; + onErrorPage.accept(error); + } + + /** After the server's first page, a pending welcome code opens the welcome page once (TrekServerStore.takeWelcomeUrl). */ + @Override + public void onPageFinished(WebView view, String url) { + super.onPageFinished(view, url); + // The error page of a load that is about to be retried: not the server's + // first page, so no welcome page and no learning of sign-in hosts yet. + if (retryUrl != null) return; + if (SignInRedirect.onServer(TrekServerStore.getUrl(view.getContext()), url)) serverShown = true; + String welcome = TrekServerStore.takeWelcomeUrl(view.getContext()); + if (welcome != null) view.loadUrl(welcome); + } + + private boolean isSignInHost(Uri url) { + String scheme = url.getScheme(); + String host = url.getHost(); + if (host == null || !("https".equals(scheme) || "http".equals(scheme))) return false; + String key = host.toLowerCase(Locale.ROOT); + return signInHosts.contains(key) || (url.getPort() != -1 && signInHosts.contains(key + ":" + url.getPort())); + } + + /** + * Mapbox's map resources go through the app's own store (tiles/TrekTileStore.kt), + * and while the server is out of reach the UI comes from its stored copy + * (TrekOfflineShell). + */ + @Override + public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { + WebResourceResponse copy = TrekOfflineShell.serve(view.getContext(), bridge, TrekServerStore.getUrl(view.getContext()), request); + if (copy != null) return copy; + if (com.liketrek.trek.tiles.TrekTileStore.INSTANCE.handles(request)) { + WebResourceResponse stored = com.liketrek.trek.tiles.TrekTileStore.INSTANCE.serve(request); + if (stored != null) return stored; + } + return super.shouldInterceptRequest(view, request); + } + + /** + * A proxy in front of the server asks for a client certificate (mutual TLS). + * The stored one goes only to the host and port it was imported for; every + * other site that asks is told there is none, as a browser without a + * matching certificate would. The WebView remembers either answer for the + * host until the app restarts, which a new certificate always brings along. + */ + @Override + public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) { + TrekClientIdentity.Identity identity = TrekClientIdentity.identityFor(view.getContext(), request.getHost(), request.getPort()); + TrekClientIdentity.noteRequest(request.getHost(), request.getPort(), identity != null); + if (identity != null) request.proceed(identity.getKey(), identity.getChain()); + else request.ignore(); + // The page may still come from the service worker's cache while every + // request fails: check natively whether the server lets the app in. + String server = TrekServerStore.getUrl(view.getContext()); + Uri serverUri = server == null ? null : Uri.parse(server); + if (serverUri != null && TrekClientIdentity.matches(String.valueOf(serverUri.getHost()), serverUri.getPort() > 0 ? serverUri.getPort() : 443, request.getHost(), request.getPort())) { + com.liketrek.trek.clientcert.ClientCertWatch.serverAsked(view.getContext(), server, () -> { + TrekServerStore.setFailure(view.getContext(), "client certificate requested"); + onUnreachable.run(); + }); + } + } + + /** + * A page that failed on the network is loaded once more before the app says + * the server is unreachable. Started from the background, as when the + * browser hands a sign-in back to an app Android had ended, a Samsung phone + * may hold its network back for a moment, and the first load fails with the + * server there all along. The error is logged, as a report has nothing else. + */ + @Override + public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { + if (request.isForMainFrame()) { + Log.w("TrekShell", "Page failed: " + error.getErrorCode() + " " + error.getDescription()); + if (!retriedMainFrame && isNetworkError(error.getErrorCode())) { + retriedMainFrame = true; + retryUrl = request.getUrl().toString(); + view.postDelayed(() -> { + String url = retryUrl; + retryUrl = null; + view.loadUrl(url); + }, 1500); + return; + } + // Out of reach for good (a trip without reception, a server at home): + // the stored copy of the UI takes over, with the app's own offline data. + String server = TrekServerStore.getUrl(view.getContext()); + if (isNetworkError(error.getErrorCode()) && !TrekOfflineShell.isActive() && TrekOfflineShell.hasCopy(view.getContext(), server)) { + TrekOfflineShell.activate(server); + String url = request.getUrl().toString(); + view.post(() -> view.loadUrl(url)); + return; + } + TrekServerStore.setFailure(view.getContext(), error.getDescription() + " (" + error.getErrorCode() + ")"); + onUnreachable.run(); + return; + } + super.onReceivedError(view, request, error); + } + + /** + * Only a 5xx on the page itself means the server is down (a proxy's 502 or + * 503 while TREK restarts). A 4xx page is not TREK's, which serves its UI for + * every path: a proxy that asked this page for a client certificate and got + * none, as Cloudflare does with a 403, sends the app to the address screen, + * which says so and offers to add one. Any other 4xx page (a proxy's block + * page, a certificate it refused) stays up with the bar and its way out, so + * the app is never stuck on a page without TREK's UI. + */ + @Override + public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { + int status = errorResponse.getStatusCode(); + if (!request.isForMainFrame()) { + super.onReceivedHttpError(view, request, errorResponse); + } else if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) { + TrekServerStore.setFailure(view.getContext(), "HTTP " + status); + onUnreachable.run(); + } else if (status >= 400) { + errorPageUrl = request.getUrl().toString(); + onErrorPage.accept(true); + } + } + + private static boolean isNetworkError(int code) { + return code == WebViewClient.ERROR_HOST_LOOKUP + || code == WebViewClient.ERROR_CONNECT + || code == WebViewClient.ERROR_TIMEOUT + || code == WebViewClient.ERROR_IO + || code == WebViewClient.ERROR_UNKNOWN; + } + + private static boolean wantedCertificate(Uri url) { + TrekClientIdentity.Request asked = TrekClientIdentity.INSTANCE.getLastRequest(); + return asked != null && !asked.getServed() && TrekClientIdentity.matches(asked.getHost(), asked.getPort(), url.getHost(), url.getPort()); + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/billing/TrekBilling.kt b/client/android/app/src/main/java/com/liketrek/trek/billing/TrekBilling.kt new file mode 100644 index 000000000..4b2276139 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/billing/TrekBilling.kt @@ -0,0 +1,282 @@ +package com.liketrek.trek.billing + +import android.app.Activity +import android.content.Context +import com.android.billingclient.api.AcknowledgePurchaseParams +import com.android.billingclient.api.BillingClient +import com.android.billingclient.api.BillingClientStateListener +import com.android.billingclient.api.BillingFlowParams +import com.android.billingclient.api.BillingResult +import com.android.billingclient.api.PendingPurchasesParams +import com.android.billingclient.api.ProductDetails +import com.android.billingclient.api.Purchase +import com.android.billingclient.api.PurchasesUpdatedListener +import com.android.billingclient.api.QueryProductDetailsParams +import com.android.billingclient.api.QueryPurchasesParams +import com.getcapacitor.JSArray +import com.getcapacitor.JSObject +import com.getcapacitor.PluginCall +import com.liketrek.trek.BuildConfig + +/** + * TREK Cloud subscriptions through Google Play Billing, the counterpart of the + * iOS app's StoreKit 2 (TrekShellPlugin.swift, feature storeKit). The UI drives + * it through the same TrekShell methods (storeProducts, storePurchase, + * storeFinish, storeRestore) behind native/iap.ts's IapClient, so the shell's + * plan screens work unchanged; a purchase's token is the receipt the control + * plane verifies with Google (iap-google.ts in trek-hosted). + * + * Products are subscriptions with the ids `cloud..monthly|yearly`, one base + * plan each. A purchase stays unacknowledged until storeFinish, after the + * instance exists, so a purchase whose redeem never happened is offered again + * by a restore rather than lost (Play refunds what is not acknowledged within + * three days, and the control plane acknowledges too once it has verified). + */ +object TrekBilling { + private var client: BillingClient? = null + private var pendingPurchase: PluginCall? = null + private var pendingProduct: String? = null + private val waiting = mutableListOf<(Boolean) -> Unit>() + private var connecting = false + + private val listener = PurchasesUpdatedListener { result, purchases -> onPurchasesUpdated(result, purchases) } + + /** + * Told of a purchase that went through outside a purchase sheet: a payment + * that was pending (cash, some carrier billing) and cleared later. The shell + * redeems it like a restore (the "storeTransaction" event), since Play refunds + * what is not acknowledged within three days. + */ + var onTransaction: ((JSObject) -> Unit)? = null + + private fun client(context: Context): BillingClient = client ?: BillingClient.newBuilder(context.applicationContext) + .setListener(listener) + .enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().enablePrepaidPlans().build()) + .enableAutoServiceReconnection() + .build() + .also { client = it } + + /** Runs [then] once connected; false when Play is not there (no Play Store, a sideloaded device). */ + private fun ready(context: Context, then: (Boolean) -> Unit) { + val billing = client(context) + if (billing.isReady) return then(true) + synchronized(waiting) { + waiting += then + if (connecting) return + connecting = true + } + billing.startConnection(object : BillingClientStateListener { + override fun onBillingSetupFinished(result: BillingResult) = flush(result.responseCode == BillingClient.BillingResponseCode.OK) + + override fun onBillingServiceDisconnected() = flush(false) + }) + } + + private fun flush(ok: Boolean) { + val callbacks = synchronized(waiting) { + connecting = false + waiting.toList().also { waiting.clear() } + } + callbacks.forEach { it(ok) } + } + + private fun details(context: Context, ids: List, done: (List) -> Unit) { + if (ids.isEmpty()) return done(emptyList()) + val params = QueryProductDetailsParams.newBuilder() + .setProductList(ids.map { QueryProductDetailsParams.Product.newBuilder().setProductId(it).setProductType(BillingClient.ProductType.SUBS).build() }) + .build() + client(context).queryProductDetailsAsync(params) { result, found -> + done(if (result.responseCode == BillingClient.BillingResponseCode.OK) found.productDetailsList else emptyList()) + } + } + + /** The recurring price of a subscription's base plan, as Play formats it for the buyer. */ + internal fun displayPrice(product: ProductDetails): String? { + val offer = baseOffer(product) ?: return null + return offer.pricingPhases.pricingPhaseList.lastOrNull()?.formattedPrice + } + + /** The base plan's own offer: the one without an offer id (free trials and promotions carry one). */ + private fun baseOffer(product: ProductDetails): ProductDetails.SubscriptionOfferDetails? { + val offers = product.subscriptionOfferDetails ?: return null + return offers.firstOrNull { it.offerId == null } ?: offers.firstOrNull() + } + + fun products(context: Context, call: PluginCall) { + val ids = call.getArray("ids")?.toList().orEmpty() + ready(context) { ok -> + val result = JSObject().put("sandbox", BuildConfig.DEBUG) + if (!ok) return@ready call.resolve(result.put("products", JSArray())) + details(context, ids) { found -> + val list = JSArray() + for (product in found) displayPrice(product)?.let { list.put(JSObject().put("id", product.productId).put("displayPrice", it)) } + call.resolve(result.put("products", list)) + } + } + } + + fun purchase(activity: Activity, call: PluginCall) { + val id = call.getString("productId") ?: return call.reject("productId is required") + ready(activity) { ok -> + if (!ok) return@ready call.resolve(JSObject().put("kind", "failed")) + // One subscription per Google account: a second plan would run beside the first. + // A delivered one stops the purchase here; one that was paid but never set up is + // handed back as bought, so its instance is set up now. + val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build() + client(activity).queryPurchasesAsync(params) { result, purchases -> + val held = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null + when { + held == null -> launchPurchase(activity, call, id) + held.isAcknowledged -> call.resolve(JSObject().put("kind", "subscribed")) + else -> call.resolve(receipt(held).put("kind", "bought")) + } + } + } + } + + private fun launchPurchase(activity: Activity, call: PluginCall, id: String) { + details(activity, listOf(id)) { found -> + val product = found.firstOrNull() + val offer = product?.let(::baseOffer) + if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed")) + pendingPurchase?.resolve(JSObject().put("kind", "cancelled")) + pendingPurchase = call + pendingProduct = id + val params = BillingFlowParams.newBuilder() + .setProductDetailsParamsList( + listOf(BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(product).setOfferToken(offer.offerToken).build()), + ) + .build() + activity.runOnUiThread { + val launch = client(activity).launchBillingFlow(activity, params) + if (launch.responseCode != BillingClient.BillingResponseCode.OK) { + settle(if (launch.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) "cancelled" else "failed", null) + } + } + } + } + + private fun onPurchasesUpdated(result: BillingResult, purchases: List?) { + if (pendingPurchase == null) { + // No sheet waiting: a pending purchase that cleared, or a renewal. Only an + // undelivered one matters; renewals are acknowledged already. + if (result.responseCode == BillingClient.BillingResponseCode.OK) { + undelivered(purchases.orEmpty(), PREFIX)?.let { onTransaction?.invoke(receipt(it)) } + } + return + } + when (result.responseCode) { + BillingClient.BillingResponseCode.OK -> { + val purchase = purchases?.firstOrNull { pendingProduct in it.products } ?: purchases?.firstOrNull() + when (purchase?.purchaseState) { + Purchase.PurchaseState.PURCHASED -> settle("bought", purchase) + Purchase.PurchaseState.PENDING -> settle("pending", null) + else -> settle("failed", null) + } + } + BillingClient.BillingResponseCode.USER_CANCELED -> settle("cancelled", null) + // Already subscribed on this Google account (a reinstall, another phone, a + // redeem that never happened): that subscription is the purchase, and the + // shell redeems it as it would a new one. + BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED -> settleOwned() + else -> settle("failed", null) + } + } + + private fun settleOwned() { + val call = pendingPurchase ?: return + val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build() + client?.queryPurchasesAsync(params) { result, purchases -> + val owned = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null + if (pendingPurchase !== call) return@queryPurchasesAsync + settle(if (owned != null) "bought" else "failed", owned) + } ?: settle("failed", null) + } + + private fun receipt(purchase: Purchase): JSObject = JSObject() + .put("purchaseToken", purchase.purchaseToken) + .put("transactionId", purchase.purchaseToken) + .put("productId", purchase.products.firstOrNull { it.startsWith(PREFIX) } ?: purchase.products.firstOrNull()) + + private fun settle(kind: String, purchase: Purchase?) { + val call = pendingPurchase ?: return + pendingPurchase = null + val product = pendingProduct + pendingProduct = null + val out = JSObject().put("kind", kind) + if (purchase != null) { + out.put("purchaseToken", purchase.purchaseToken) + out.put("transactionId", purchase.purchaseToken) + out.put("productId", purchase.products.firstOrNull() ?: product) + purchase.orderId?.let { out.put("orderId", it) } + } + call.resolve(out) + } + + /** Marks the purchase delivered, once its instance exists: acknowledged with Play. */ + fun finish(context: Context, call: PluginCall) { + val token = call.getString("transactionId") ?: return call.reject("transactionId is required") + ready(context) { ok -> + if (!ok) return@ready call.resolve() + val params = AcknowledgePurchaseParams.newBuilder().setPurchaseToken(token).build() + client(context).acknowledgePurchase(params) { call.resolve() } + } + } + + /** Whether this Google account holds a delivered subscription under `prefix`; while one runs, the shell offers no purchase. */ + fun held(context: Context, call: PluginCall) { + val prefix = call.getString("prefix") ?: PREFIX + ready(context) { ok -> + if (!ok) return@ready call.resolve(JSObject().put("held", false)) + val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build() + client(context).queryPurchasesAsync(params) { result, purchases -> + val found = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, prefix) else null + call.resolve(JSObject().put("held", found?.isAcknowledged == true)) + } + } + } + + /** The newest active subscription under `prefix` on this Google account, if any. */ + fun restore(context: Context, call: PluginCall) { + val prefix = call.getString("prefix") ?: "cloud." + ready(context) { ok -> + if (!ok) return@ready call.resolve(JSObject()) + val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build() + client(context).queryPurchasesAsync(params) { result, purchases -> + val found = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, prefix) else null + if (found == null) return@queryPurchasesAsync call.resolve(JSObject()) + call.resolve( + JSObject() + .put("purchaseToken", found.purchaseToken) + .put("transactionId", found.purchaseToken) + .put("productId", found.products.first { it.startsWith(prefix) }), + ) + } + } + } + + /** + * A paid cloud purchase that was never delivered (not acknowledged), for the + * shell to redeem at its start: one that cleared while the app was closed. + */ + fun unfinished(context: Context, call: PluginCall) { + val prefix = call.getString("prefix") ?: PREFIX + ready(context) { ok -> + if (!ok) return@ready call.resolve(JSObject()) + val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build() + client(context).queryPurchasesAsync(params) { result, purchases -> + val found = if (result.responseCode == BillingClient.BillingResponseCode.OK) undelivered(purchases, prefix) else null + call.resolve(found?.let(::receipt) ?: JSObject()) + } + } + } + + internal fun undelivered(purchases: List, prefix: String): Purchase? = + newest(purchases.filter { !it.isAcknowledged }, prefix) + + private const val PREFIX = "cloud." + + internal fun newest(purchases: List, prefix: String): Purchase? = purchases + .filter { p -> p.purchaseState == Purchase.PurchaseState.PURCHASED && p.products.any { it.startsWith(prefix) } } + .maxByOrNull { it.purchaseTime } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/clientcert/ClientCertActions.kt b/client/android/app/src/main/java/com/liketrek/trek/clientcert/ClientCertActions.kt new file mode 100644 index 000000000..3a04ca2fa --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/clientcert/ClientCertActions.kt @@ -0,0 +1,151 @@ +package com.liketrek.trek.clientcert + +import android.app.Activity +import android.app.AlertDialog +import android.content.Context +import android.net.Uri +import android.text.InputType +import android.view.ViewGroup +import android.widget.EditText +import android.widget.FrameLayout +import com.getcapacitor.JSObject +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URL +import javax.net.ssl.HttpsURLConnection + +/** + * What TrekShellPlugin does for client certificates (TrekClientIdentity): + * check a server while noticing whether it asks for one, read a picked file, + * and ask for its password. + */ +object ClientCertActions { + + private const val MAX_BODY_BYTES = 512 * 1024 + private const val MAX_FILE_BYTES = 256 * 1024 + private const val MAX_REDIRECTS = 5 + + /** + * A GET against the user's server for the address screen: status, body, final + * URL and headers, plus whether the server asked for a client certificate and + * whether one was shown. A failed connection answers status 0 instead of + * throwing, so a handshake the server broke off for want of a certificate + * still reports that it asked. + */ + @JvmStatic + fun request(context: Context, url: String, timeoutMs: Int): JSObject { + var asked: Triple? = null + val factory = TrekClientIdentity.socketFactory(context) { host, port, served -> asked = Triple(host, port, served) } + val result = JSObject() + var current = URL(url) + try { + for (hop in 0..MAX_REDIRECTS) { + val connection = current.openConnection() as HttpURLConnection + if (connection is HttpsURLConnection) connection.sslSocketFactory = factory + connection.instanceFollowRedirects = false + connection.connectTimeout = timeoutMs + connection.readTimeout = timeoutMs + connection.setRequestProperty("Accept", "application/json, text/html;q=0.9, */*;q=0.8") + try { + val status = connection.responseCode + val location = connection.getHeaderField("Location") + if (status in 300..399 && location != null && hop < MAX_REDIRECTS) { + current = URL(current, location) + continue + } + val stream = if (status >= 400) connection.errorStream else connection.inputStream + result.put("status", status) + result.put("data", stream?.use { readCapped(it, MAX_BODY_BYTES) }?.toString(Charsets.UTF_8) ?: "") + result.put("url", current.toString()) + val headers = JSObject() + for ((name, values) in connection.headerFields) if (name != null && values.isNotEmpty()) headers.put(name, values.first()) + result.put("headers", headers) + } finally { + connection.disconnect() + } + break + } + } catch (e: IOException) { + result.put("status", 0) + result.put("data", "") + result.put("url", current.toString()) + result.put("error", e.javaClass.simpleName) + } + val seen = asked + result.put("certRequested", seen != null) + result.put("certSent", seen?.third == true) + if (seen != null) result.put("certHost", "${seen.first}:${seen.second}") + return result + } + + /** The bytes of a picked file, or null when it cannot be read or is far too big for a certificate. */ + @JvmStatic + fun readFile(context: Context, uri: Uri): ByteArray? = try { + context.contentResolver.openInputStream(uri)?.use { readCapped(it, MAX_FILE_BYTES + 1) }?.takeIf { it.size <= MAX_FILE_BYTES } + } catch (e: Exception) { + null + } + + /** + * The password prompt, with the UI's own words (`labels`: title, message, + * placeholder, ok, cancel, wrongPassword). `wrong` shows that the last try + * did not open the file. `done` gets the password, or null when cancelled. + */ + @JvmStatic + fun askPassword(activity: Activity, labels: JSObject, wrong: Boolean, done: (CharArray?) -> Unit) { + activity.runOnUiThread { + val input = EditText(activity).apply { + inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD + hint = labels.getString("placeholder") ?: "" + } + val frame = FrameLayout(activity).apply { + val pad = (20 * activity.resources.displayMetrics.density).toInt() + setPadding(pad, pad / 2, pad, 0) + addView(input, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + } + val message = if (wrong) labels.getString("wrongPassword") else labels.getString("message") + var answered = false + val dialog = AlertDialog.Builder(activity) + .setTitle(labels.getString("title")) + .setMessage(message) + .setView(frame) + .setPositiveButton(labels.getString("ok") ?: "OK") { _, _ -> + answered = true + val text = input.text + val password = CharArray(text.length) { text[it] } + done(password) + } + .setNegativeButton(labels.getString("cancel") ?: "Cancel") { _, _ -> + answered = true + done(null) + } + .setOnDismissListener { if (!answered) done(null) } + .create() + dialog.show() + input.requestFocus() + } + } + + /** The settings' view of the stored certificate. */ + @JvmStatic + fun infoObject(info: TrekClientIdentity.Info): JSObject = JSObject().apply { + put("host", info.host) + put("port", info.port) + put("subject", info.subject) + put("issuer", info.issuer) + put("notAfter", info.notAfter) + } + + private fun readCapped(stream: InputStream, max: Int): ByteArray { + val out = ByteArrayOutputStream() + val buffer = ByteArray(8192) + while (out.size() < max) { + val n = stream.read(buffer, 0, minOf(buffer.size, max - out.size())) + if (n < 0) break + out.write(buffer, 0, n) + } + return out.toByteArray() + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/clientcert/ClientCertWatch.kt b/client/android/app/src/main/java/com/liketrek/trek/clientcert/ClientCertWatch.kt new file mode 100644 index 000000000..3c3287e50 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/clientcert/ClientCertWatch.kt @@ -0,0 +1,50 @@ +package com.liketrek.trek.clientcert + +import android.content.Context +import java.util.concurrent.atomic.AtomicLong + +/** + * Notices when the user's server stops letting the app in for want of a + * client certificate: one removed, expired, or no longer trusted by the proxy. + * + * The page alone does not show it. The service worker serves TREK's start page + * from its cache, so the page loads and only its requests fail, and the UI + * reports a server it cannot reach with no way to add a certificate. So when + * the server asks for one, the app checks once natively whether TREK answers + * with what it holds. Only a check that fails at the certificate (the handshake + * broke off, or the proxy answered with its own 4xx) sends the app to the + * address screen, which says so and offers to add one. A server that merely + * asks and lets everyone in answers TREK's 200, and nothing happens. + */ +object ClientCertWatch { + + private const val MIN_INTERVAL_MS = 60_000L + private const val FEATURES_PATH = "/api/health/features" + private const val TIMEOUT_MS = 8000 + + private val lastCheck = AtomicLong(0) + + /** Called where the server asked for a certificate; `onRefused` runs at most once a minute, on a background thread. */ + @JvmStatic + fun serverAsked(context: Context, serverUrl: String?, onRefused: Runnable) { + if (serverUrl == null) return + val now = System.currentTimeMillis() + val last = lastCheck.get() + if (now - last < MIN_INTERVAL_MS || !lastCheck.compareAndSet(last, now)) return + val appContext = context.applicationContext + Thread({ + val result = ClientCertActions.request(appContext, serverUrl.trimEnd('/') + FEATURES_PATH, TIMEOUT_MS) + if (refused(result.optBoolean("certRequested"), result.optInt("status"))) onRefused.run() + }, "trek-client-cert-watch").start() + } + + /** A new or removed certificate is worth a check of its own, whenever the last one ran. */ + @JvmStatic + fun reset() { + lastCheck.set(0) + } + + /** The server asked for a certificate and did not answer with TREK. */ + @JvmStatic + fun refused(certRequested: Boolean, status: Int): Boolean = certRequested && (status == 0 || status in 400..499) +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/clientcert/TrekClientIdentity.kt b/client/android/app/src/main/java/com/liketrek/trek/clientcert/TrekClientIdentity.kt new file mode 100644 index 000000000..ef857a65a --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/clientcert/TrekClientIdentity.kt @@ -0,0 +1,261 @@ +package com.liketrek.trek.clientcert + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import java.io.ByteArrayInputStream +import java.io.IOException +import java.net.Socket +import java.security.KeyFactory +import java.security.KeyStore +import java.security.Principal +import java.security.PrivateKey +import java.security.UnrecoverableKeyException +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import java.security.spec.PKCS8EncodedKeySpec +import java.util.Date +import java.util.Locale +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec +import javax.net.ssl.SSLContext +import javax.net.ssl.SSLEngine +import javax.net.ssl.SSLSocket +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509ExtendedKeyManager + +/** + * The client certificate a user's TREK server asks for (mutual TLS): a proxy + * such as Cloudflare, nginx, Caddy or Traefik in front of TREK lets through only + * devices that show one. The app holds at most one, for one server. + * + * It comes in as a PKCS#12 file (.p12, .pfx) and its password. Neither is kept: + * the private key is sealed with an AES key of the Android keystore, which + * never leaves it, and stored with the certificate chain in the app's private + * preferences. In memory the key is an ordinary one, which TLS 1.2 and 1.3 and + * the WebView all take, whatever its kind; a key imported into the keystore + * itself would be refused by some of them for its padding or digest rules. + * + * Only the host and port it was imported for ever see it (`identityFor`), so a + * login page, a map tile provider or liketrek.com never learns of it. + */ +object TrekClientIdentity { + + private const val PREFS = "trek_client_identity" + private const val WRAP_ALIAS = "trek-client-identity-wrap" + private const val KEYMANAGER_ALIAS = "trek-client-identity" + private const val GCM_TAG_BITS = 128 + + /** Why a file could not be taken. */ + enum class Failure { PASSWORD, FORMAT, NO_KEY, EXPIRED, NOT_YET_VALID } + + class ImportException(val reason: Failure) : Exception(reason.name) + + class Identity(val key: PrivateKey, val chain: Array) + + /** What the settings show: who the certificate names, who issued it, until when, and for which server. */ + data class Info(val host: String, val port: Int, val subject: String, val issuer: String, val notAfter: Long) + + /** The opened identity, with the sealed key text it was opened from: opened once, not per request. */ + @Volatile private var cached: Pair? = null + + /** The last time a server asked for a certificate while the app showed it: for the address screen. */ + @Volatile var lastRequest: Request? = null + private set + + data class Request(val host: String, val port: Int, val served: Boolean) + + private class Stored(val host: String, val port: Int, val algorithm: String, val sealedText: String, val iv: ByteArray, val chain: List) + + /** + * Reads a PKCS#12 file: the first entry that holds a private key, with its chain. + * Throws ImportException naming what is wrong with it. + */ + @JvmStatic + @JvmOverloads + @Throws(ImportException::class) + fun read(bytes: ByteArray, password: CharArray, now: Date = Date()): Identity { + val store = KeyStore.getInstance("PKCS12") + try { + store.load(ByteArrayInputStream(bytes), password) + } catch (e: IOException) { + throw ImportException(if (isPasswordFailure(e)) Failure.PASSWORD else Failure.FORMAT) + } catch (e: Exception) { + throw ImportException(Failure.FORMAT) + } + val alias = store.aliases().toList().firstOrNull { store.isKeyEntry(it) } ?: throw ImportException(Failure.NO_KEY) + val key = try { + store.getKey(alias, password) as? PrivateKey + } catch (e: UnrecoverableKeyException) { + throw ImportException(Failure.PASSWORD) + } ?: throw ImportException(Failure.NO_KEY) + val chain = store.getCertificateChain(alias)?.mapNotNull { it as? X509Certificate }?.toTypedArray() + if (chain.isNullOrEmpty()) throw ImportException(Failure.NO_KEY) + val leaf = chain[0] + if (now.after(leaf.notAfter)) throw ImportException(Failure.EXPIRED) + if (now.before(leaf.notBefore)) throw ImportException(Failure.NOT_YET_VALID) + return Identity(key, chain) + } + + /** A wrong password shows up as a failed MAC check or an unrecoverable key, wrapped in an IOException. */ + private fun isPasswordFailure(e: Throwable): Boolean { + var cause: Throwable? = e + while (cause != null) { + if (cause is UnrecoverableKeyException || cause is javax.crypto.BadPaddingException) return true + if (cause.message?.lowercase(Locale.ROOT)?.contains("password") == true) return true + cause = cause.cause + } + return false + } + + /** Keeps the identity for this host and port, replacing any other. */ + @JvmStatic + fun save(context: Context, identity: Identity, host: String, port: Int) { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, wrapKey()) + val sealed = cipher.doFinal(identity.key.encoded) + prefs(context).edit() + .putString("host", host.lowercase(Locale.ROOT)) + .putInt("port", port) + .putString("algorithm", identity.key.algorithm) + .putString("key", encode(sealed)) + .putString("iv", encode(cipher.iv)) + .putString("chain", identity.chain.joinToString(",") { encode(it.encoded) }) + .apply() + cached = null + } + + @JvmStatic + fun remove(context: Context) { + prefs(context).edit().clear().apply() + cached = null + } + + @JvmStatic + fun info(context: Context): Info? { + val stored = stored(context) ?: return null + val leaf = runCatching { certificate(stored.chain.first()) }.getOrNull() ?: return null + return Info(stored.host, stored.port, commonName(leaf.subjectX500Principal), commonName(leaf.issuerX500Principal), leaf.notAfter.time) + } + + /** The identity for a server at this host and port, or null when there is none for it. */ + @JvmStatic + fun identityFor(context: Context, host: String?, port: Int): Identity? { + val stored = stored(context) ?: return null + if (!matches(stored.host, stored.port, host, port)) return null + return opened(stored) + } + + private fun opened(stored: Stored): Identity? { + cached?.let { (from, identity) -> if (from == stored.sealedText) return identity } + val identity = runCatching { open(stored) }.getOrNull() ?: return null + cached = stored.sealedText to identity + return identity + } + + /** Whether a request to host and port (-1 or 0 for the scheme's default) goes to the server the identity is for. */ + @JvmStatic + fun matches(storedHost: String, storedPort: Int, host: String?, port: Int): Boolean { + if (host == null || !host.equals(storedHost, ignoreCase = true)) return false + val effective = if (port <= 0) 443 else port + return effective == storedPort + } + + /** Called where a server asked for a certificate, so the address screen can offer one. */ + @JvmStatic + fun noteRequest(host: String?, port: Int, served: Boolean) { + if (host == null) return + lastRequest = Request(host.lowercase(Locale.ROOT), if (port <= 0) 443 else port, served) + } + + /** + * A socket factory for the app's own requests (the server check, map tiles). + * It offers the identity only when the server it is talking to asks for one + * and is the one the identity is for, and tells `onAsked` about every ask. + */ + @JvmStatic + fun socketFactory(context: Context, onAsked: ((host: String, port: Int, served: Boolean) -> Unit)? = null): SSLSocketFactory { + val appContext = context.applicationContext + val manager = object : X509ExtendedKeyManager() { + // Decided per handshake in choose(); the key and chain are then read for + // the one alias, so parallel connections never see each other's choice. + private fun choose(host: String?, port: Int): String? { + val identity = identityFor(appContext, host, port) + if (host != null) { + noteRequest(host, port, identity != null) + onAsked?.invoke(host.lowercase(Locale.ROOT), if (port <= 0) 443 else port, identity != null) + } + return if (identity != null) KEYMANAGER_ALIAS else null + } + + override fun chooseClientAlias(keyType: Array?, issuers: Array?, socket: Socket?): String? { + val session = (socket as? SSLSocket)?.handshakeSession + return choose(session?.peerHost, session?.peerPort ?: -1) + } + + override fun chooseEngineClientAlias(keyType: Array?, issuers: Array?, engine: SSLEngine?): String? = + choose(engine?.peerHost, engine?.peerPort ?: -1) + + override fun getCertificateChain(alias: String?): Array? = + if (alias == KEYMANAGER_ALIAS) stored(appContext)?.let { opened(it) }?.chain else null + override fun getPrivateKey(alias: String?): PrivateKey? = + if (alias == KEYMANAGER_ALIAS) stored(appContext)?.let { opened(it) }?.key else null + override fun getClientAliases(keyType: String?, issuers: Array?): Array? = null + override fun getServerAliases(keyType: String?, issuers: Array?): Array? = null + override fun chooseServerAlias(keyType: String?, issuers: Array?, socket: Socket?): String? = null + } + val tls = SSLContext.getInstance("TLS") + tls.init(arrayOf(manager), null, null) + return tls.socketFactory + } + + private fun open(stored: Stored): Identity { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.DECRYPT_MODE, wrapKey(), GCMParameterSpec(GCM_TAG_BITS, stored.iv)) + val key = KeyFactory.getInstance(stored.algorithm).generatePrivate(PKCS8EncodedKeySpec(cipher.doFinal(decode(stored.sealedText)))) + return Identity(key, stored.chain.map { certificate(it) }.toTypedArray()) + } + + private fun stored(context: Context): Stored? { + val p = prefs(context) + val host = p.getString("host", null) ?: return null + val algorithm = p.getString("algorithm", null) ?: return null + val key = p.getString("key", null) ?: return null + val iv = p.getString("iv", null) ?: return null + val chain = p.getString("chain", null)?.split(",")?.filter { it.isNotEmpty() }?.map { decode(it) } ?: return null + if (chain.isEmpty()) return null + return Stored(host, p.getInt("port", 443), algorithm, key, decode(iv), chain) + } + + /** The keystore's AES key that seals the private key; made once, never leaves the keystore. */ + private fun wrapKey(): SecretKey { + val keystore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (keystore.getKey(WRAP_ALIAS, null) as? SecretKey)?.let { return it } + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") + generator.init( + KeyGenParameterSpec.Builder(WRAP_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build() + ) + return generator.generateKey() + } + + private fun certificate(der: ByteArray): X509Certificate = + CertificateFactory.getInstance("X.509").generateCertificate(ByteArrayInputStream(der)) as X509Certificate + + /** The CN of a name, or the whole name when it has none. */ + @JvmStatic + fun commonName(principal: javax.security.auth.x500.X500Principal): String { + val name = principal.getName(javax.security.auth.x500.X500Principal.RFC2253) + return Regex("(?:^|,)CN=((?:\\\\.|[^,])*)").find(name)?.groupValues?.get(1)?.replace("\\", "") ?: name + } + + private fun prefs(context: Context) = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + private fun encode(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.NO_WRAP) + private fun decode(text: String) = Base64.decode(text, Base64.NO_WRAP) +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/location/TrekLocation.kt b/client/android/app/src/main/java/com/liketrek/trek/location/TrekLocation.kt new file mode 100644 index 000000000..d1afbb0cf --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/location/TrekLocation.kt @@ -0,0 +1,91 @@ +package com.liketrek.trek.location + +import android.annotation.SuppressLint +import android.content.Context +import android.location.Location +import android.location.LocationManager +import android.os.Build +import androidx.core.location.LocationListenerCompat +import androidx.core.location.LocationManagerCompat +import androidx.core.location.LocationRequestCompat +import androidx.core.content.ContextCompat +import com.getcapacitor.JSObject +import org.json.JSONObject + +/** + * One location stream for the UI's navigator.geolocation (native/geolocation.ts), + * the counterpart of TrekLocation in TrekShellPlugin.swift: the system's fused + * provider where there is one (Android 12+), GPS and network before, with + * positions and errors shaped like the Geolocation API's. Asking for the + * permission is the plugin's part; this starts once it is granted. + */ +class TrekLocation(context: Context, private val emit: (JSObject) -> Unit) { + private val manager = context.getSystemService(LocationManager::class.java) + private val executor = ContextCompat.getMainExecutor(context) + private val listeners = mutableListOf() + + @SuppressLint("MissingPermission") + fun start(highAccuracy: Boolean) { + stop() + if (manager == null || !LocationManagerCompat.isLocationEnabled(manager)) { + emitError(2, "Location services are off") + return + } + val request = LocationRequestCompat.Builder(if (highAccuracy) 2_000L else 10_000L) + .setQuality(if (highAccuracy) LocationRequestCompat.QUALITY_HIGH_ACCURACY else LocationRequestCompat.QUALITY_BALANCED_POWER_ACCURACY) + .setMinUpdateDistanceMeters(if (highAccuracy) 2f else 25f) + .build() + val providers = when { + Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && manager.hasProvider(LocationManager.FUSED_PROVIDER) -> listOf(LocationManager.FUSED_PROVIDER) + else -> listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER).filter { manager.isProviderEnabled(it) } + } + if (providers.isEmpty()) { + emitError(2, "No location provider") + return + } + // The last known fix answers getCurrentPosition at once; a fresh one follows. + providers.mapNotNull { runCatching { manager.getLastKnownLocation(it) }.getOrNull() } + .maxByOrNull { it.time } + ?.takeIf { System.currentTimeMillis() - it.time < 120_000 } + ?.let { emit(payload(it)) } + for (provider in providers) { + val listener = LocationListenerCompat { location -> emit(payload(location)) } + try { + LocationManagerCompat.requestLocationUpdates(manager, provider, request, executor, listener) + listeners += listener + } catch (e: SecurityException) { + emitError(1, "Location permission denied") + return + } + } + } + + // Removing updates needs no permission of its own; one revoked meanwhile only means there is nothing left to stop. + @SuppressLint("MissingPermission") + fun stop() { + val m = manager ?: return + for (listener in listeners) { + try { + LocationManagerCompat.removeUpdates(m, listener) + } catch (e: SecurityException) { + // Nothing to stop. + } + } + listeners.clear() + } + + fun emitError(code: Int, message: String) { + emit(JSObject().put("error", JSObject().put("code", code).put("message", message))) + } + + companion object { + fun payload(location: Location): JSObject = JSObject() + .put("latitude", location.latitude) + .put("longitude", location.longitude) + .put("accuracy", location.accuracy.toDouble()) + .put("altitude", if (location.hasAltitude()) location.altitude else JSONObject.NULL) + .put("speed", if (location.hasSpeed()) location.speed.toDouble() else JSONObject.NULL) + .put("heading", if (location.hasBearing()) location.bearing.toDouble() else JSONObject.NULL) + .put("timestamp", location.time.toDouble()) + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/screen/TrekKeyCommands.kt b/client/android/app/src/main/java/com/liketrek/trek/screen/TrekKeyCommands.kt new file mode 100644 index 000000000..925b3e191 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/screen/TrekKeyCommands.kt @@ -0,0 +1,101 @@ +package com.liketrek.trek.screen + +import android.view.KeyEvent +import android.view.KeyboardShortcutGroup +import android.view.KeyboardShortcutInfo +import org.json.JSONArray +import org.json.JSONObject + +/** + * The UI's keyboard shortcuts as the app's own (TrekShell.setKeyCommands, feature + * keyCommands), the Android side of TrekKeyCommands in the iOS shell: a hardware + * keyboard's shortcut runs the UI's command even while the focus sits outside the + * page, and the system's shortcut list (Meta + /) shows them under their names in + * the UI's language. Each screen replaces the list, so only what works here is on it. + * + * "command" is Ctrl on Android (Meta is accepted too, for keyboards made for a Mac), + * "option" is Alt. + */ +object TrekKeyCommands { + data class Command(val id: String, val title: String, val keyCode: Int, val modifiers: Int) + + @Volatile var current: List = emptyList() + private set + + var onPress: ((String) -> Unit)? = null + + fun set(raw: JSONArray?) { + current = parse(raw) + } + + fun parse(raw: JSONArray?): List { + if (raw == null) return emptyList() + return (0 until raw.length()).mapNotNull { i -> + val o: JSONObject = raw.optJSONObject(i) ?: return@mapNotNull null + val id = o.optString("id").ifEmpty { return@mapNotNull null } + val title = o.optString("title").ifEmpty { return@mapNotNull null } + val key = keyCode(o.optString("input")) ?: return@mapNotNull null + var meta = 0 + val mods = o.optJSONArray("modifiers") + for (j in 0 until (mods?.length() ?: 0)) { + meta = meta or when (mods!!.optString(j)) { + "command", "control" -> KeyEvent.META_CTRL_ON + "shift" -> KeyEvent.META_SHIFT_ON + "option" -> KeyEvent.META_ALT_ON + else -> 0 + } + } + Command(id, title, key, meta) + } + } + + /** The key a UI input names: a letter, a digit, an arrow, escape or a punctuation mark. */ + fun keyCode(input: String): Int? = when (input.lowercase()) { + "left" -> KeyEvent.KEYCODE_DPAD_LEFT + "right" -> KeyEvent.KEYCODE_DPAD_RIGHT + "up" -> KeyEvent.KEYCODE_DPAD_UP + "down" -> KeyEvent.KEYCODE_DPAD_DOWN + "escape" -> KeyEvent.KEYCODE_ESCAPE + "enter", "\r" -> KeyEvent.KEYCODE_ENTER + "," -> KeyEvent.KEYCODE_COMMA + "." -> KeyEvent.KEYCODE_PERIOD + "/" -> KeyEvent.KEYCODE_SLASH + "[" -> KeyEvent.KEYCODE_LEFT_BRACKET + "]" -> KeyEvent.KEYCODE_RIGHT_BRACKET + "-" -> KeyEvent.KEYCODE_MINUS + "=" -> KeyEvent.KEYCODE_EQUALS + " ", "space" -> KeyEvent.KEYCODE_SPACE + else -> when { + input.length == 1 && input[0].lowercaseChar() in 'a'..'z' -> KeyEvent.KEYCODE_A + (input[0].lowercaseChar() - 'a') + input.length == 1 && input[0] in '0'..'9' -> KeyEvent.KEYCODE_0 + (input[0] - '0') + else -> null + } + } + + private const val MASK = KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON or KeyEvent.META_ALT_ON + + /** The command a key press stands for, if any. Meta counts as Ctrl. */ + fun match(keyCode: Int, metaState: Int): Command? { + var state = metaState + if (state and KeyEvent.META_META_ON != 0) state = state or KeyEvent.META_CTRL_ON + val pressed = state and MASK + return current.firstOrNull { it.keyCode == keyCode && it.modifiers == pressed } + } + + /** Runs the matching command for a key going down. True when one took it. */ + fun dispatch(event: KeyEvent): Boolean { + if (event.action != KeyEvent.ACTION_DOWN || event.repeatCount > 0) return false + val command = match(event.keyCode, event.metaState) ?: return false + // A plain key (no modifier) is left to a text field that has the focus. + if (command.modifiers == 0 && event.keyCode != KeyEvent.KEYCODE_ESCAPE) return false + val press = onPress ?: return false + press(command.id) + return true + } + + /** The list the system shows for Meta + /. */ + fun shortcutGroup(label: CharSequence): KeyboardShortcutGroup? { + val items = current.map { KeyboardShortcutInfo(it.title, it.keyCode, it.modifiers) } + return if (items.isEmpty()) null else KeyboardShortcutGroup(label, items) + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/screen/TrekWindowLayout.kt b/client/android/app/src/main/java/com/liketrek/trek/screen/TrekWindowLayout.kt new file mode 100644 index 000000000..ebe57efc7 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/screen/TrekWindowLayout.kt @@ -0,0 +1,82 @@ +package com.liketrek.trek.screen + +import android.app.Activity +import android.graphics.Rect +import androidx.activity.ComponentActivity +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import androidx.window.layout.FoldingFeature +import androidx.window.layout.WindowInfoTracker +import androidx.window.layout.WindowLayoutInfo +import androidx.window.layout.WindowMetricsCalculator +import com.getcapacitor.JSObject +import kotlinx.coroutines.launch + +/** + * The window's shape for the UI (TrekShell.getWindowLayout and the + * "windowLayout" event, feature windowLayout): its size class by Android's + * breakpoints, and a foldable's posture and hinge through Jetpack WindowManager. + * + * The layouts themselves follow the CSS size classes (hooks/sizeClass.ts), which + * the WebView answers from the window like any browser; this adds what CSS cannot + * see: that a Galaxy Z Fold or Pixel Fold is half open like a laptop or a book, + * and where the hinge runs, so a layout can keep content off the fold. Lengths + * are in CSS pixels, relative to the window. + */ +object TrekWindowLayout { + /** The last WindowLayoutInfo WindowManager reported, with the fold in it. */ + @Volatile private var lastInfo: WindowLayoutInfo? = null + + /** The window now, with the posture last reported: what getWindowLayout answers. */ + fun current(activity: Activity): JSObject = describe(activity, lastInfo) + + fun observe(activity: ComponentActivity, emit: (JSObject) -> Unit) { + activity.lifecycleScope.launch { + activity.repeatOnLifecycle(Lifecycle.State.STARTED) { + WindowInfoTracker.getOrCreate(activity).windowLayoutInfo(activity).collect { info -> + lastInfo = info + emit(describe(activity, info)) + } + } + } + } + + fun describe(activity: Activity, info: WindowLayoutInfo?): JSObject { + val density = activity.resources.displayMetrics.density + val bounds = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(activity).bounds + val widthDp = bounds.width() / density + val heightDp = bounds.height() / density + val result = JSObject() + .put("width", widthDp.toInt()) + .put("height", heightDp.toInt()) + .put("widthClass", sizeClass(widthDp, 600f, 840f)) + .put("heightClass", sizeClass(heightDp, 480f, 900f)) + val fold = info?.displayFeatures?.filterIsInstance()?.firstOrNull() + if (fold == null) { + result.put("posture", "none") + } else { + val r: Rect = fold.bounds + result.put("posture", if (fold.state == FoldingFeature.State.HALF_OPENED) "halfOpened" else "flat") + .put("orientation", if (fold.orientation == FoldingFeature.Orientation.VERTICAL) "vertical" else "horizontal") + .put("separating", fold.isSeparating) + .put("occluding", fold.occlusionType == FoldingFeature.OcclusionType.FULL) + .put( + "hinge", + JSObject() + .put("left", ((r.left - bounds.left) / density).toInt()) + .put("top", ((r.top - bounds.top) / density).toInt()) + .put("right", ((r.right - bounds.left) / density).toInt()) + .put("bottom", ((r.bottom - bounds.top) / density).toInt()), + ) + } + return result + } + + /** Android's window size classes: compact, medium, expanded. */ + fun sizeClass(dp: Float, medium: Float, expanded: Float): String = when { + dp < medium -> "compact" + dp < expanded -> "medium" + else -> "expanded" + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/share/ShareActivity.kt b/client/android/app/src/main/java/com/liketrek/trek/share/ShareActivity.kt new file mode 100644 index 000000000..c149d3dcd --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/share/ShareActivity.kt @@ -0,0 +1,431 @@ +package com.liketrek.trek.share + +import android.content.Intent +import android.graphics.Bitmap +import android.os.Bundle +import android.text.format.Formatter +import android.view.HapticFeedbackConstants +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.core.spring +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.CalendarMonth +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.Description +import androidx.compose.material.icons.rounded.Email +import androidx.compose.material.icons.rounded.Image +import androidx.compose.material.icons.rounded.Language +import androidx.compose.material.icons.rounded.PictureAsPdf +import androidx.compose.material.icons.rounded.Schedule +import androidx.compose.material.icons.rounded.ShortText +import androidx.compose.material.icons.rounded.Wallet +import androidx.compose.material.icons.rounded.ErrorOutline +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.lifecycle.lifecycleScope +import com.liketrek.trek.MainActivity +import com.liketrek.trek.R +import com.liketrek.trek.ui.TrekMaterialTheme +import com.liketrek.trek.widget.WidgetArt +import java.time.LocalDate +import java.time.temporal.ChronoUnit +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * "TREK" in the system share sheet (and "Open with TREK"): a Material bottom + * sheet over the app that shared, showing what came in, the trip it goes to and + * one button, the counterpart of the iOS share extension (ShareView.swift). The + * item and the trip are left for the app (ShareHandoff) and TREK opens, where + * the booking import takes over. A direct-share shortcut of a trip + * (TrekShortcuts) arrives with that trip already picked. + */ +class ShareActivity : ComponentActivity() { + private sealed interface Phase { + data object Loading : Phase + data object Ready : Phase + data object Saving : Phase + data object Done : Phase + data class Failed(val message: Int) : Phase + } + + private var phase by mutableStateOf(Phase.Loading) + private var item by mutableStateOf(null) + private var trips by mutableStateOf>(emptyList()) + private var selected by mutableStateOf(null) + + override fun onCreate(savedInstanceState: Bundle?) { + enableEdgeToEdge() + super.onCreate(savedInstanceState) + trips = ShareHandoff.trips(this) + val shortcutTrip = intent.getStringExtra(ShortcutManagerCompat.EXTRA_SHORTCUT_ID)?.removePrefix("trip.")?.toLongOrNull() + selected = if (savedInstanceState?.containsKey(SELECTED) == true) { + // The trip picked before the system recreated the sheet; -1 is "choose later". + savedInstanceState.getLong(SELECTED).takeIf { it >= 0 } + } else { + shortcutTrip?.takeIf { id -> trips.any { it.id == id } } ?: trips.firstOrNull()?.id + } + val incoming = intent + lifecycleScope.launch { + phase = try { + item = withContext(Dispatchers.IO) { ShareLoader.load(incoming, contentResolver) } + Phase.Ready + } catch (e: ShareLoadException) { + Phase.Failed(if (e.reason == ShareLoadException.Reason.TOO_LARGE) R.string.share_too_large else R.string.share_unsupported) + } catch (e: Exception) { + Phase.Failed(R.string.share_unsupported) + } + } + setContent { + TrekMaterialTheme { + Sheet() + } + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putLong(SELECTED, selected ?: -1L) + } + + private fun add() { + val current = item ?: return + if (phase != Phase.Ready) return + phase = Phase.Saving + lifecycleScope.launch { + val stored = withContext(Dispatchers.IO) { ShareHandoff.store(this@ShareActivity, current, selected) } + if (!stored) { + window.decorView.performHapticFeedback(HapticFeedbackConstants.REJECT) + phase = Phase.Failed(R.string.share_failed) + return@launch + } + window.decorView.performHapticFeedback(HapticFeedbackConstants.CONFIRM) + phase = Phase.Done + delay(850) + startActivity( + Intent(this@ShareActivity, MainActivity::class.java) + .setAction(MainActivity.ACTION_SHARE_HANDOFF) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP), + ) + finish() + } + } + + @OptIn(ExperimentalMaterial3Api::class) + @Composable + private fun Sheet() { + val state = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val scope = rememberCoroutineScope() + val dismiss: () -> Unit = { + scope.launch { state.hide() }.invokeOnCompletion { finish() } + } + ModalBottomSheet( + onDismissRequest = { finish() }, + sheetState = state, + containerColor = MaterialTheme.colorScheme.surfaceContainerLow, + ) { + Column(modifier = Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 12.dp)) { + Header(onClose = dismiss) + Spacer(Modifier.height(16.dp)) + when (val now = phase) { + is Phase.Failed -> Failure(stringResource(now.message), onClose = dismiss) + else -> Content(now) + } + } + } + } + + @Composable + private fun Header(onClose: () -> Unit) { + Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = Modifier.size(40.dp).clip(RoundedCornerShape(12.dp)).background(MaterialTheme.colorScheme.primary), + contentAlignment = Alignment.Center, + ) { + Text("T", color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.Black, fontSize = 21.sp) + } + Spacer(Modifier.width(12.dp)) + Column(modifier = Modifier.weight(1f)) { + Text("TREK", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, letterSpacing = 2.4.sp) + Text(stringResource(R.string.share_title), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold) + } + TextButton(onClick = onClose) { Text(stringResource(R.string.share_cancel)) } + } + } + + @Composable + private fun Content(now: Phase) { + Column(verticalArrangement = Arrangement.spacedBy(18.dp)) { + ItemCard(item, Modifier.padding(horizontal = 20.dp)) + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + stringResource(R.string.share_trip).uppercase(), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontWeight = FontWeight.Bold, + letterSpacing = 1.2.sp, + modifier = Modifier.padding(horizontal = 22.dp), + ) + if (trips.isEmpty()) { + Text( + stringResource(R.string.share_no_trips), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 22.dp), + ) + } else { + TripRail() + } + } + Text( + stringResource(R.string.share_hint), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 22.dp), + ) + AddButton(now) + } + } + + @Composable + private fun ItemCard(item: ShareItem?, modifier: Modifier) { + val context = LocalContext.current + Surface( + shape = RoundedCornerShape(20.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = modifier.fillMaxWidth(), + ) { + Row(modifier = Modifier.padding(14.dp), verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = Modifier.size(46.dp).clip(RoundedCornerShape(14.dp)).background(MaterialTheme.colorScheme.secondaryContainer), + contentAlignment = Alignment.Center, + ) { + if (item == null) { + CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + } else { + Icon(kindIcon(item.kind), null, tint = MaterialTheme.colorScheme.onSecondaryContainer) + } + } + Spacer(Modifier.width(14.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + item?.title ?: stringResource(R.string.share_reading), + style = MaterialTheme.typography.titleMedium, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + if (item != null) { + val parts = listOfNotNull(stringResource(kindLabel(item.kind)), Formatter.formatShortFileSize(context, item.data.size.toLong()), item.source) + Text(parts.joinToString(", "), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1) + } + } + } + } + } + + @Composable + private fun TripRail() { + LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) { + items(trips, key = { it.id }) { trip -> + TripCard(trip, selected == trip.id) { selected = trip.id } + } + item { + FilterChip( + selected = selected == null, + onClick = { selected = null }, + label = { Text(stringResource(R.string.share_later)) }, + leadingIcon = { Icon(Icons.Rounded.Schedule, null, modifier = Modifier.size(18.dp)) }, + modifier = Modifier.height(132.dp).padding(vertical = 44.dp), + ) + } + } + } + + @Composable + private fun TripCard(trip: ShareHandoff.Trip, isSelected: Boolean, onClick: () -> Unit) { + val view = LocalView.current + val cover: Bitmap? = remember(trip.id) { WidgetArt.cover(trip.cover, 360) ?: WidgetArt.sky(trip.title, 300, 200) } + val border = if (isSelected) BorderStroke(3.dp, MaterialTheme.colorScheme.primary) else BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant) + Surface( + shape = RoundedCornerShape(20.dp), + border = border, + modifier = Modifier.width(168.dp).height(132.dp).clip(RoundedCornerShape(20.dp)).clickable { + view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) + onClick() + }, + ) { + Box { + if (cover != null) { + Image(cover.asImageBitmap(), null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) + } + Box( + modifier = Modifier.fillMaxSize().background( + Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.1f), Color.Black.copy(alpha = 0.68f))), + ), + ) + if (isSelected) { + Box( + modifier = Modifier.padding(8.dp).size(24.dp).clip(CircleShape).background(MaterialTheme.colorScheme.primary).align(Alignment.TopEnd), + contentAlignment = Alignment.Center, + ) { + Icon(Icons.Rounded.Check, null, tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(16.dp)) + } + } + Column(modifier = Modifier.align(Alignment.BottomStart).padding(12.dp)) { + Text(when_(trip), color = Color.White.copy(alpha = 0.82f), style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold) + Text(trip.title, color = Color.White, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } + } + } + + @Composable + private fun when_(trip: ShareHandoff.Trip): String { + val today = LocalDate.now() + val start = trip.start + val end = trip.end + return when { + end != null && end < today -> stringResource(R.string.share_past) + start == null || start <= today -> stringResource(R.string.share_now) + ChronoUnit.DAYS.between(today, start) == 1L -> stringResource(R.string.share_tomorrow) + else -> stringResource(R.string.share_in_days, ChronoUnit.DAYS.between(today, start).toInt()) + } + } + + @Composable + private fun AddButton(now: Phase) { + val title = trips.firstOrNull { it.id == selected }?.title + Button( + onClick = ::add, + enabled = now == Phase.Ready, + shape = RoundedCornerShape(18.dp), + colors = if (now == Phase.Done) { + ButtonDefaults.buttonColors(containerColor = Color(0xFF2FA37A), disabledContainerColor = Color(0xFF2FA37A), disabledContentColor = Color.White) + } else { + ButtonDefaults.buttonColors() + }, + contentPadding = PaddingValues(vertical = 16.dp), + modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp), + ) { + AnimatedContent( + targetState = now, + transitionSpec = { (fadeIn() + scaleIn(spring(dampingRatio = 0.6f))) togetherWith fadeOut() }, + label = "add", + ) { target -> + when (target) { + Phase.Saving, Phase.Loading -> CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp, color = MaterialTheme.colorScheme.onPrimary) + Phase.Done -> Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Rounded.Check, null) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.share_added), fontWeight = FontWeight.Bold) + } + else -> Text( + if (title != null) stringResource(R.string.share_add_to, title) else stringResource(R.string.share_add), + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } + + @Composable + private fun Failure(message: String, onClose: () -> Unit) { + Column(modifier = Modifier.fillMaxWidth().padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally) { + Icon(Icons.Rounded.ErrorOutline, null, tint = MaterialTheme.colorScheme.error, modifier = Modifier.size(40.dp)) + Spacer(Modifier.height(12.dp)) + Text(message, style = MaterialTheme.typography.bodyLarge) + Spacer(Modifier.height(16.dp)) + Button(onClick = onClose, shape = RoundedCornerShape(18.dp)) { Text(stringResource(R.string.share_close)) } + } + } + + private fun kindIcon(kind: ShareItem.Kind): ImageVector = when (kind) { + ShareItem.Kind.PASS -> Icons.Rounded.Wallet + ShareItem.Kind.PDF -> Icons.Rounded.PictureAsPdf + ShareItem.Kind.MAIL -> Icons.Rounded.Email + ShareItem.Kind.CALENDAR -> Icons.Rounded.CalendarMonth + ShareItem.Kind.PAGE -> Icons.Rounded.Language + ShareItem.Kind.TEXT -> Icons.Rounded.ShortText + ShareItem.Kind.IMAGE -> Icons.Rounded.Image + ShareItem.Kind.FILE -> Icons.Rounded.Description + } + + private fun kindLabel(kind: ShareItem.Kind): Int = when (kind) { + ShareItem.Kind.PASS -> R.string.share_kind_pass + ShareItem.Kind.PDF -> R.string.share_kind_pdf + ShareItem.Kind.MAIL -> R.string.share_kind_mail + ShareItem.Kind.CALENDAR -> R.string.share_kind_file + ShareItem.Kind.PAGE -> R.string.share_kind_page + ShareItem.Kind.TEXT -> R.string.share_kind_text + ShareItem.Kind.IMAGE -> R.string.share_kind_image + ShareItem.Kind.FILE -> R.string.share_kind_file + } + + private companion object { + const val SELECTED = "trek.share.selected" + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/share/ShareHandoff.kt b/client/android/app/src/main/java/com/liketrek/trek/share/ShareHandoff.kt new file mode 100644 index 000000000..543149dd8 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/share/ShareHandoff.kt @@ -0,0 +1,69 @@ +package com.liketrek.trek.share + +import android.content.Context +import com.liketrek.trek.widget.WidgetSnapshot +import com.liketrek.trek.widget.WidgetStore +import java.io.File +import java.time.LocalDate +import org.json.JSONObject + +/** + * The trips the share sheet offers, and the hand-over of the shared item to the + * app. The trip list is the one the app keeps for the widgets (WidgetStore, key + * "trips"); the item waits in the app's cache until MainActivity hands it to the + * UI (TrekSharedFiles.receiveHandoff), the way ShareHandoff.swift does through + * the keychain on iOS. + */ +object ShareHandoff { + data class Trip( + val id: Long, + val title: String, + val start: LocalDate?, + val end: LocalDate?, + val place: String?, + /** The small cover from the trip's widget snapshot, base64, when the app wrote one. */ + val cover: String?, + ) + + /** The trips that have not ended yet, soonest first, then the six most recent past ones. */ + fun trips(context: Context, today: LocalDate = LocalDate.now()): List { + val all = WidgetStore.trips(context).map { ref -> + val snapshot = WidgetStore.read(context, "trip.${ref.id}")?.let(WidgetSnapshot::parse) + Trip(ref.id, ref.title, WidgetSnapshot.day(ref.start), WidgetSnapshot.day(ref.end), snapshot?.trip?.place, snapshot?.trip?.cover) + } + return order(all, today) + } + + internal fun order(all: List, today: LocalDate): List { + val ahead = all.filter { (it.end ?: LocalDate.MAX) >= today }.sortedBy { it.start ?: LocalDate.MAX } + val past = all.filter { (it.end ?: LocalDate.MAX) < today }.sortedByDescending { it.end ?: LocalDate.MIN } + return ahead + past.take(6) + } + + private fun dir(context: Context) = File(context.cacheDir, "share").apply { mkdirs() } + + /** Leaves the item for the app, with the trip it goes to (null: the app asks). */ + fun store(context: Context, item: ShareItem, tripId: Long?): Boolean = runCatching { + val meta = JSONObject().put("name", item.name).put("mimeType", item.mimeType) + if (tripId != null) meta.put("tripId", tripId) + if (item.url != null) meta.put("url", item.url).put("title", item.title) + File(dir(context), "pending.data").writeBytes(item.data) + File(dir(context), "pending.json").writeText(meta.toString()) + true + }.getOrDefault(false) + + /** The item left by [store], taken once. */ + fun take(context: Context): Pair? { + val metaFile = File(dir(context), "pending.json") + val dataFile = File(dir(context), "pending.data") + if (!metaFile.exists() || !dataFile.exists()) return null + return try { + JSONObject(metaFile.readText()) to dataFile.readBytes() + } catch (e: Exception) { + null + } finally { + metaFile.delete() + dataFile.delete() + } + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/share/ShareItem.kt b/client/android/app/src/main/java/com/liketrek/trek/share/ShareItem.kt new file mode 100644 index 000000000..0b1628fcf --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/share/ShareItem.kt @@ -0,0 +1,210 @@ +package com.liketrek.trek.share + +import android.content.ContentResolver +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.provider.OpenableColumns +import java.io.ByteArrayOutputStream +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URL + +/** + * What was shared to TREK, read into a file the booking import takes: a wallet + * pass, a PDF, a mail, a calendar entry, a web page, a piece of text or a photo. + * The import in the app (BookingImportModal) decides what it can read; this only + * carries the bytes over with a name and a type, like ShareItem.swift on iOS. + */ +data class ShareItem( + val kind: Kind, + /** The file name the import sees. */ + val name: String, + val mimeType: String, + val data: ByteArray, + /** What the sheet shows: a page title, a file name, the first line of a text. */ + val title: String, + /** A host, for a page. */ + val source: String? = null, + /** + * The web address it came from, when it is a page or a link: the app offers to + * keep it among the trip's links as well as to read a booking out of it. + */ + val url: String? = null, +) { + enum class Kind { PASS, PDF, MAIL, CALENDAR, PAGE, TEXT, IMAGE, FILE } + + override fun equals(other: Any?): Boolean = other is ShareItem && other.name == name && other.data.contentEquals(data) + + override fun hashCode(): Int = name.hashCode() * 31 + data.contentHashCode() +} + +class ShareLoadException(val reason: Reason) : Exception(reason.name) { + enum class Reason { UNSUPPORTED, TOO_LARGE } +} + +object ShareLoader { + /** The same ceiling as the app's import of an opened file (TrekSharedFiles). */ + const val MAX_BYTES = 15 * 1024 * 1024 + private const val PAGE_TIMEOUT_MS = 10_000 + + /** Reads what [intent] carries. Runs on a background thread: it may read a file or fetch a page. */ + fun load(intent: Intent, resolver: ContentResolver): ShareItem { + val stream = streamOf(intent) + if (stream != null) return fromUri(stream, intent.type, resolver) + val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()?.trim() + if (!text.isNullOrEmpty()) return fromText(text, intent.getStringExtra(Intent.EXTRA_SUBJECT)) + throw ShareLoadException(ShareLoadException.Reason.UNSUPPORTED) + } + + /** + * The shared document, content:// only. The share target is open to every app, + * and a file:// path would be read with TREK's rights, its own private files + * included; every sender today shares through a content provider anyway. + */ + private fun streamOf(intent: Intent): Uri? = when (intent.action) { + Intent.ACTION_VIEW -> intent.data + Intent.ACTION_SEND -> parcelable(intent, Intent.EXTRA_STREAM) + Intent.ACTION_SEND_MULTIPLE -> parcelableList(intent)?.firstOrNull() + else -> null + }?.takeIf(::isShareable) + + internal fun isShareable(uri: Uri): Boolean = uri.scheme == ContentResolver.SCHEME_CONTENT + + @Suppress("DEPRECATION") + private fun parcelable(intent: Intent, key: String): Uri? = + if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(key, Uri::class.java) else intent.getParcelableExtra(key) + + @Suppress("DEPRECATION") + private fun parcelableList(intent: Intent): List? = + if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java) + } else { + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) + } + + private fun fromUri(uri: Uri, intentType: String?, resolver: ContentResolver): ShareItem { + val name = displayName(uri, resolver) + val size = runCatching { + resolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { if (it.moveToFirst() && !it.isNull(0)) it.getLong(0) else null } + }.getOrNull() + if (size != null && size > MAX_BYTES) throw ShareLoadException(ShareLoadException.Reason.TOO_LARGE) + val data = resolver.openInputStream(uri)?.use { readCapped(it) } ?: throw ShareLoadException(ShareLoadException.Reason.UNSUPPORTED) + val mime = resolver.getType(uri) ?: intentType ?: "application/octet-stream" + val (kind, normalized) = classify(name, mime) + return checked(ShareItem(kind, withExtension(name, kind), normalized, data, name.substringBeforeLast('.').ifBlank { name })) + } + + /** + * A link becomes the page it points at, or the bare link when the page cannot be + * read (a sign-in wall, an app-only page, no network), which the app can still + * keep among the trip's links. Anything else, a text file the import reads. + */ + internal fun fromText(text: String, subject: String?): ShareItem { + val link = firstLink(text) + if (link != null) { + runCatching { return page(link, subject) } + return linkOnly(link, subject) + } + val firstLine = text.lineSequence().firstOrNull { it.isNotBlank() }?.trim() ?: text + return checked(ShareItem(ShareItem.Kind.TEXT, "shared-text.txt", "text/plain", text.toByteArray(), (subject ?: firstLine).take(80))) + } + + /** The first http(s) link in a text, when the text is not much more than that link. */ + internal fun firstLink(text: String): String? { + val match = Regex("https?://[^\\s<>\"]+").find(text) ?: return null + // A long mail body with a link in it is the booking itself, not a pointer to one. + return if (text.length - match.value.length <= 200) match.value.trimEnd('.', ',', ')', ']') else null + } + + private fun page(link: String, subject: String?): ShareItem { + val connection = URL(link).openConnection() as HttpURLConnection + connection.connectTimeout = PAGE_TIMEOUT_MS + connection.readTimeout = PAGE_TIMEOUT_MS + connection.instanceFollowRedirects = true + connection.setRequestProperty("Accept", "text/html") + try { + val code = connection.responseCode + val type = connection.contentType.orEmpty() + if (code !in 200..299 || !type.contains("html")) throw ShareLoadException(ShareLoadException.Reason.UNSUPPORTED) + val data = connection.inputStream.use { readCapped(it) } + val html = String(data, Charsets.UTF_8) + val host = runCatching { Uri.parse(link).host }.getOrNull() + val title = pageTitle(html) ?: subject ?: host ?: "Page" + return checked(ShareItem(ShareItem.Kind.PAGE, "${slug(title)}.html", "text/html", data, title, host, link)) + } finally { + connection.disconnect() + } + } + + /** The link alone, as a text/uri-list the app recognises as nothing to read a booking from. */ + internal fun linkOnly(link: String, subject: String?): ShareItem { + // java.net.URI rather than android.net.Uri: the same host, and readable in a JVM unit test. + val host = runCatching { java.net.URI(link).host }.getOrNull() + return ShareItem(ShareItem.Kind.PAGE, "link.url", "text/uri-list", link.toByteArray(), subject ?: host ?: link, host, link) + } + + /** The kind and the MIME type the import should see, from the name when the type is vague. */ + internal fun classify(name: String, mime: String): Pair { + val ext = name.substringAfterLast('.', "").lowercase() + return when { + ext == "pkpass" || mime == "application/vnd.apple.pkpass" -> ShareItem.Kind.PASS to "application/vnd.apple.pkpass" + ext == "pdf" || mime == "application/pdf" -> ShareItem.Kind.PDF to "application/pdf" + ext == "eml" || mime == "message/rfc822" -> ShareItem.Kind.MAIL to "message/rfc822" + ext == "ics" || mime == "text/calendar" -> ShareItem.Kind.CALENDAR to "text/calendar" + ext == "html" || ext == "htm" || mime == "text/html" -> ShareItem.Kind.PAGE to "text/html" + mime.startsWith("image/") -> ShareItem.Kind.IMAGE to mime + ext == "txt" || mime == "text/plain" -> ShareItem.Kind.TEXT to "text/plain" + else -> ShareItem.Kind.FILE to mime + } + } + + private fun withExtension(name: String, kind: ShareItem.Kind): String { + val ext = when (kind) { + ShareItem.Kind.PASS -> "pkpass" + ShareItem.Kind.PDF -> "pdf" + ShareItem.Kind.MAIL -> "eml" + ShareItem.Kind.CALENDAR -> "ics" + ShareItem.Kind.PAGE -> "html" + else -> return name + } + return if (name.lowercase().endsWith(".$ext")) name else "$name.$ext" + } + + private fun displayName(uri: Uri, resolver: ContentResolver): String { + runCatching { + resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst() && !it.isNull(0)) return it.getString(0) + } + } + return uri.lastPathSegment?.substringAfterLast('/')?.ifBlank { null } ?: "booking" + } + + private fun readCapped(input: InputStream): ByteArray { + val out = ByteArrayOutputStream() + val buffer = ByteArray(16 * 1024) + while (true) { + val read = input.read(buffer) + if (read < 0) break + out.write(buffer, 0, read) + if (out.size() > MAX_BYTES) throw ShareLoadException(ShareLoadException.Reason.TOO_LARGE) + } + return out.toByteArray() + } + + private fun checked(item: ShareItem): ShareItem { + if (item.data.isEmpty()) throw ShareLoadException(ShareLoadException.Reason.UNSUPPORTED) + if (item.data.size > MAX_BYTES) throw ShareLoadException(ShareLoadException.Reason.TOO_LARGE) + return item + } + + internal fun pageTitle(html: String): String? { + val match = Regex("]*>(.*?)", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL)).find(html) ?: return null + return match.groupValues[1].trim().take(120).ifBlank { null } + } + + internal fun slug(title: String): String { + val words = title.lowercase().split(Regex("[^\\p{L}\\p{N}]+")).filter { it.isNotEmpty() } + return words.take(8).joinToString("-").ifBlank { "page" } + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/share/TrekShortcuts.kt b/client/android/app/src/main/java/com/liketrek/trek/share/TrekShortcuts.kt new file mode 100644 index 000000000..4bc8b9da3 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/share/TrekShortcuts.kt @@ -0,0 +1,66 @@ +package com.liketrek.trek.share + +import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Rect +import android.net.Uri +import androidx.core.content.pm.ShortcutInfoCompat +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.core.graphics.drawable.IconCompat +import com.liketrek.trek.MainActivity +import com.liketrek.trek.widget.WidgetArt +import com.liketrek.trek.widget.WidgetSnapshot +import com.liketrek.trek.widget.WidgetStore + +/** + * The trips as shortcuts: a long press on TREK's icon lists the coming ones and + * opens a trip straight away, and the system share sheet offers them as direct + * share targets, so a booking goes into its trip in one tap (ShareActivity + * reads the shortcut's id). Rebuilt whenever the app writes its trip list. + */ +object TrekShortcuts { + /** The category res/xml/shortcuts.xml's share-target names. */ + const val SHARE_CATEGORY = "com.liketrek.trek.category.TRIP_SHARE" + private const val MAX = 4 + + fun publish(context: Context) { + val trips = ShareHandoff.trips(context).take(MAX) + val limit = ShortcutManagerCompat.getMaxShortcutCountPerActivity(context).coerceAtLeast(1) + val shortcuts = trips.take(limit).mapIndexed { rank, trip -> + val open = Intent(Intent.ACTION_VIEW, Uri.parse(WidgetSnapshot.link("/trips/${trip.id}")), context, MainActivity::class.java) + ShortcutInfoCompat.Builder(context, "trip.${trip.id}") + .setShortLabel(trip.title.take(24)) + .setLongLabel(trip.title) + .setIcon(IconCompat.createWithAdaptiveBitmap(icon(trip))) + .setIntent(open) + .setCategories(setOf(SHARE_CATEGORY)) + .setLongLived(true) + .setRank(rank) + .build() + } + runCatching { + // Trips no longer listed lose their shortcut; pinned ones stay but are disabled by the system. + val keep = shortcuts.map { it.id }.toSet() + val stale = ShortcutManagerCompat.getDynamicShortcuts(context).map { it.id }.filter { it !in keep } + if (stale.isNotEmpty()) ShortcutManagerCompat.removeLongLivedShortcuts(context, stale) + ShortcutManagerCompat.setDynamicShortcuts(context, shortcuts) + } + } + + /** The trip's cover, else its own sky, cropped for an adaptive icon (108dp with a 72dp safe zone). */ + private fun icon(trip: ShareHandoff.Trip): Bitmap { + val size = 216 + val source = WidgetArt.cover(trip.cover, 432) ?: WidgetArt.sky(trip.title, size, size) + val out = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) + val side = minOf(source.width, source.height) + val from = Rect((source.width - side) / 2, (source.height - side) / 2, (source.width + side) / 2, (source.height + side) / 2) + Canvas(out).drawBitmap(source, from, Rect(0, 0, size, size), Paint(Paint.FILTER_BITMAP_FLAG)) + return out + } + + /** Whether there is anything to publish: the app wrote a trip list. */ + fun hasTrips(context: Context): Boolean = WidgetStore.trips(context).isNotEmpty() +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/tiles/TrekTileStore.kt b/client/android/app/src/main/java/com/liketrek/trek/tiles/TrekTileStore.kt new file mode 100644 index 000000000..7dbea3db6 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/tiles/TrekTileStore.kt @@ -0,0 +1,164 @@ +package com.liketrek.trek.tiles + +import android.content.Context +import android.net.Uri +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import java.io.ByteArrayInputStream +import java.io.File +import java.net.HttpURLConnection +import java.net.URL +import java.security.MessageDigest + +/** + * The app's own store of Mapbox map resources, the counterpart of the iOS + * TrekTileStore (TrekBridgeViewController.swift). + * + * Android's WebView runs the server's service worker, which keeps every raster + * tile the user looked at. Mapbox's vector tiles, styles, sprites and glyphs it + * may not keep, but a device cache of what was viewed is allowed for 30 days, + * so the WebView client hands those requests here (TrekWebViewClient), and a + * Mapbox map keeps working offline for the places already seen. Nothing is + * prefetched; the store is pruned to [MAX_BYTES], least recently used first. + */ +object TrekTileStore { + const val MAX_AGE_MS = 30L * 24 * 60 * 60 * 1000 + const val MAX_BYTES = 250L * 1024 * 1024 + private const val PRUNE_TARGET = 0.8 + private const val TIMEOUT_MS = 15_000 + /** One resource is a tile, a style or a sprite sheet: far below this. */ + private const val MAX_RESOURCE_BYTES = 8 * 1024 * 1024 + + private val HOST = Regex("^(api\\.mapbox\\.com|[a-z0-9-]+\\.tiles\\.mapbox\\.com)$", RegexOption.IGNORE_CASE) + /** What a map draws; telemetry, sessions and anything else go straight out. */ + private val PATHS = listOf("/v4/", "/styles/", "/fonts/", "/models/", "/rasterarrays/", "/raster/") + private val DROPPED = setOf("access_token", "sku", "key", "api_key", "apikey") + + @Volatile private var dir: File? = null + private var writesSincePrune = 0 + + fun init(context: Context) { + if (dir == null) dir = File(context.cacheDir, "tiles").apply { mkdirs() } + } + + fun handles(request: WebResourceRequest): Boolean = request.method == "GET" && handles(request.url) + + fun handles(url: Uri): Boolean = url.scheme == "https" && HOST.matches(url.host.orEmpty()) && PATHS.any { url.path.orEmpty().startsWith(it) } + + /** The key of a resource: its URL without the credentials and the billing session, which change. */ + fun key(url: Uri): String { + val builder = url.buildUpon().clearQuery() + url.queryParameterNames.filter { it.lowercase() !in DROPPED }.sorted().forEach { name -> + url.getQueryParameters(name).forEach { builder.appendQueryParameter(name, it) } + } + val digest = MessageDigest.getInstance("SHA-256").digest(builder.build().toString().toByteArray()) + return digest.joinToString("") { "%02x".format(it) } + } + + /** + * Answers a Mapbox request from the store when it is younger than 30 days, + * else from the network, keeping what came back. Null lets the WebView load + * it itself (no store, or the network failed). + */ + fun serve(request: WebResourceRequest): WebResourceResponse? { + val root = dir ?: return null + val url = request.url + val key = key(url) + val body = File(root, "$key.bin") + val meta = File(root, "$key.type") + val now = System.currentTimeMillis() + if (body.exists() && now - created(meta) < MAX_AGE_MS) { + body.setLastModified(now) + val type = runCatching { meta.readLines().getOrNull(1) }.getOrNull() ?: "application/octet-stream" + return runCatching { response(body.readBytes(), type) }.getOrNull() + } + try { + val connection = URL(url.toString()).openConnection() as HttpURLConnection + connection.connectTimeout = TIMEOUT_MS + connection.readTimeout = TIMEOUT_MS + // The WebView's own headers go along: Mapbox checks a URL-restricted token + // against the Referer, and the server's origin is what the token allows. + for ((name, value) in forwardedHeaders(request.requestHeaders)) connection.setRequestProperty(name, value) + try { + val code = connection.responseCode + if (code == 200) { + val bytes = connection.inputStream.use { it.readBytes() } + if (bytes.size <= MAX_RESOURCE_BYTES) { + val type = connection.contentType ?: "application/octet-stream" + store(body, meta, bytes, type, now) + return response(bytes, type) + } + } + // Anything but a tile (401/403 for a token, 404, a 5xx) the WebView asks for + // itself, with everything a browser sends, and the map reports what it gets. + } finally { + connection.disconnect() + } + } catch (e: Exception) { + // Offline and never seen: the map shows the gap as it would in a browser. + } + return null + } + + /** Headers that are the request's own; the connection sets the hop-by-hop ones itself. */ + private val HOP_BY_HOP = setOf("connection", "keep-alive", "transfer-encoding", "te", "upgrade", "host", "content-length", "accept-encoding") + + internal fun forwardedHeaders(headers: Map?): Map = + headers.orEmpty().filterKeys { it.lowercase() !in HOP_BY_HOP } + + /** HttpURLConnection has already undone any gzip, so no Content-Encoding goes along. */ + private fun response(bytes: ByteArray, type: String): WebResourceResponse { + val mime = type.substringBefore(';').trim() + val charset = Regex("charset=([^;]+)").find(type)?.groupValues?.get(1) + return WebResourceResponse(mime, charset, 200, "OK", cors(), ByteArrayInputStream(bytes)) + } + + /** The map fetches from the server's origin; the store's answer has to allow it as Mapbox's own does. */ + private fun cors(): MutableMap = mutableMapOf("Access-Control-Allow-Origin" to "*", "Cache-Control" to "no-store") + + private fun created(meta: File): Long = runCatching { meta.readLines().first().toLong() }.getOrDefault(0L) + + @Synchronized + private fun store(body: File, meta: File, bytes: ByteArray, type: String, now: Long) { + runCatching { + body.writeBytes(bytes) + meta.writeText("$now\n$type") + } + if (++writesSincePrune >= 200) { + writesSincePrune = 0 + prune() + } + } + + /** Drops what is past 30 days, then the least recently used while the store is over its limit. */ + @Synchronized + fun prune() { + val root = dir ?: return + val now = System.currentTimeMillis() + val bodies = root.listFiles { f -> f.name.endsWith(".bin") }?.toMutableList() ?: return + bodies.filter { now - created(File(root, it.name.removeSuffix(".bin") + ".type")) > MAX_AGE_MS }.forEach { + remove(root, it) + bodies.remove(it) + } + var total = bodies.sumOf { it.length() } + if (total <= MAX_BYTES) return + val target = (MAX_BYTES * PRUNE_TARGET).toLong() + for (file in bodies.sortedBy { it.lastModified() }) { + if (total <= target) break + total -= file.length() + remove(root, file) + } + } + + private fun remove(root: File, body: File) { + body.delete() + File(root, body.name.removeSuffix(".bin") + ".type").delete() + } + + fun usage(): Long = dir?.listFiles()?.sumOf { it.length() } ?: 0L + + @Synchronized + fun clear() { + dir?.listFiles()?.forEach { it.delete() } + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/tripday/TripDayNotification.kt b/client/android/app/src/main/java/com/liketrek/trek/tripday/TripDayNotification.kt new file mode 100644 index 000000000..6c87bb891 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/tripday/TripDayNotification.kt @@ -0,0 +1,146 @@ +package com.liketrek.trek.tripday + +import android.Manifest +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import androidx.core.graphics.drawable.IconCompat +import com.liketrek.trek.MainActivity +import com.liketrek.trek.R +import com.liketrek.trek.widget.TrekIcons +import com.liketrek.trek.widget.WidgetSnapshot +import java.time.LocalDate +import java.time.LocalTime +import java.time.ZoneId + +/** + * The travel day as a Live Update, the Android counterpart of the iOS Live + * Activity (TripDayLiveActivity.swift): an ongoing notification with the next + * stop, its time as the status-bar chip and a countdown, and the day's stops as + * a segmented progress bar. Android 16 promotes it to the top of the shade and + * the lock screen (ProgressStyle, POST_PROMOTED_NOTIFICATIONS); older versions + * show the same content as a quiet ongoing notification with a plain bar. + * + * The UI starts, updates and ends it (TrekShell.syncTripDay / endTripDay), and + * it lapses on its own at midnight, so a forgotten one never lingers. + */ +object TripDayNotification { + const val CHANNEL = "tripday" + private const val ID = 0x7d1 + + data class State( + val tripTitle: String, + val path: String, + val dayLabel: String, + val nextName: String, + val nextTime: String?, + /** Minutes after midnight of the next stop, for the countdown. */ + val nextMinutes: Int?, + val done: Int, + val total: Int, + /** #rrggbb of each stop, for the segments; may be empty. */ + val colors: List = emptyList(), + ) + + fun ensureChannel(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val manager = context.getSystemService(NotificationManager::class.java) ?: return + if (manager.getNotificationChannel(CHANNEL) != null) return + // Default importance: low would keep it out of the status bar chip and promotion. + val channel = NotificationChannel(CHANNEL, context.getString(R.string.push_channel_tripday), NotificationManager.IMPORTANCE_DEFAULT).apply { + description = context.getString(R.string.push_channel_tripday_description) + setSound(null, null) + enableVibration(false) + setShowBadge(false) + } + manager.createNotificationChannel(channel) + } + + /** Whether it can be shown at all: notifications allowed, and the channel not switched off. */ + fun allowed(context: Context): Boolean { + if (Build.VERSION.SDK_INT >= 33 && + ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED + ) { + return false + } + val manager = NotificationManagerCompat.from(context) + if (!manager.areNotificationsEnabled()) return false + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val channel = context.getSystemService(NotificationManager::class.java)?.getNotificationChannel(CHANNEL) + if (channel != null && channel.importance == NotificationManager.IMPORTANCE_NONE) return false + } + return true + } + + /** Shows the day, or updates the one showing. False when notifications are off. */ + fun show(context: Context, state: State): Boolean { + ensureChannel(context) + if (!allowed(context)) return false + try { + NotificationManagerCompat.from(context).notify(ID, build(context, state)) + } catch (e: SecurityException) { + return false + } + return true + } + + fun end(context: Context) { + NotificationManagerCompat.from(context).cancel(ID) + } + + fun build(context: Context, state: State, today: LocalDate = LocalDate.now()): android.app.Notification { + val open = Intent(Intent.ACTION_VIEW, Uri.parse(WidgetSnapshot.link(state.path)), context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) + val tap = PendingIntent.getActivity(context, ID, open, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) + val zone = ZoneId.systemDefault() + val midnight = today.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() + val remaining = (midnight - System.currentTimeMillis()).coerceAtLeast(60_000L) + + val builder = NotificationCompat.Builder(context, CHANNEL) + .setSmallIcon(R.drawable.ic_stat_trek) + .setContentTitle(state.nextName) + .setContentText(listOfNotNull(state.nextTime, state.tripTitle).joinToString(" ")) + .setSubText(state.dayLabel) + .setContentIntent(tap) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setSilent(true) + .setCategory(NotificationCompat.CATEGORY_PROGRESS) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .setTimeoutAfter(remaining) + .setRequestPromotedOngoing(true) + + state.nextTime?.let { builder.setShortCriticalText(it) } + state.nextMinutes?.let { minutes -> + val at = today.atTime(LocalTime.of((minutes / 60).coerceIn(0, 23), minutes % 60)).atZone(zone).toInstant().toEpochMilli() + if (at > System.currentTimeMillis()) { + builder.setWhen(at).setShowWhen(true).setUsesChronometer(true).setChronometerCountDown(true) + } + } + + val total = state.total.coerceAtLeast(1) + val done = state.done.coerceIn(0, total) + val style = NotificationCompat.ProgressStyle() + .setStyledByProgress(true) + .setProgressTrackerIcon(IconCompat.createWithBitmap(TrekIcons.bitmap(TrekIcons.vector("figure.walk"), 72, ContextCompat.getColor(context, R.color.notification_accent)))) + for (i in 0 until total) { + val color = state.colors.getOrNull(i)?.let(::parseColor) ?: ContextCompat.getColor(context, R.color.tripday_segment) + style.addProgressSegment(NotificationCompat.ProgressStyle.Segment(1).setColor(color)) + } + style.setProgress(done) + builder.setStyle(style) + // Before Android 16 the style falls back to nothing: the plain bar carries the progress. + if (Build.VERSION.SDK_INT < 36) builder.setProgress(total, done, false) + return builder.build() + } + + private fun parseColor(css: String): Int? = runCatching { android.graphics.Color.parseColor(css) }.getOrNull() +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/ui/TrekMaterialTheme.kt b/client/android/app/src/main/java/com/liketrek/trek/ui/TrekMaterialTheme.kt new file mode 100644 index 000000000..43252338a --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/ui/TrekMaterialTheme.kt @@ -0,0 +1,53 @@ +package com.liketrek.trek.ui + +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext + +/** + * The theme of the app's own native screens (the share sheet, the widget's trip + * picker): Material You's wallpaper colours on Android 12 and later, TREK's + * neutral palette before that, light and dark with the system. + */ +@Composable +fun TrekMaterialTheme(content: @Composable () -> Unit) { + val dark = isSystemInDarkTheme() + val context = LocalContext.current + val colors = when { + Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> if (dark) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + dark -> darkColorScheme( + primary = Color(0xFFE4E4E7), + onPrimary = Color(0xFF101013), + secondary = Color(0xFF8AAEF0), + secondaryContainer = Color(0xFF233250), + onSecondaryContainer = Color(0xFFDCE6FA), + surface = Color(0xFF0C0C0F), + surfaceContainerLow = Color(0xFF16161A), + surfaceContainer = Color(0xFF1B1B21), + surfaceContainerHigh = Color(0xFF232329), + onSurface = Color(0xFFF5F5F7), + onSurfaceVariant = Color(0xFF9C9CA3), + ) + else -> lightColorScheme( + primary = Color(0xFF111827), + onPrimary = Color(0xFFFFFFFF), + secondary = Color(0xFF4A7DDB), + secondaryContainer = Color(0xFFE4EAF7), + onSecondaryContainer = Color(0xFF1B2F57), + surface = Color(0xFFFDFCF9), + surfaceContainerLow = Color(0xFFF4F2EE), + surfaceContainer = Color(0xFFEFEDE8), + surfaceContainerHigh = Color(0xFFE9E7E1), + onSurface = Color(0xFF101013), + onSurfaceVariant = Color(0xFF68686F), + ) + } + MaterialTheme(colorScheme = colors, content = content) +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/TrekIcons.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/TrekIcons.kt new file mode 100644 index 000000000..3dec16d4a --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/TrekIcons.kt @@ -0,0 +1,209 @@ +package com.liketrek.trek.widget + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Matrix +import android.graphics.Paint +import android.graphics.Path +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.AcUnit +import androidx.compose.material.icons.rounded.AccountBalance +import androidx.compose.material.icons.rounded.Backpack +import androidx.compose.material.icons.rounded.BeachAccess +import androidx.compose.material.icons.rounded.Bed +import androidx.compose.material.icons.rounded.Bolt +import androidx.compose.material.icons.rounded.Bookmark +import androidx.compose.material.icons.rounded.CalendarMonth +import androidx.compose.material.icons.rounded.CameraAlt +import androidx.compose.material.icons.rounded.Chat +import androidx.compose.material.icons.rounded.CheckCircle +import androidx.compose.material.icons.rounded.Checklist +import androidx.compose.material.icons.rounded.Cloud +import androidx.compose.material.icons.rounded.CreditCard +import androidx.compose.material.icons.rounded.DirectionsBoat +import androidx.compose.material.icons.rounded.DirectionsBus +import androidx.compose.material.icons.rounded.DirectionsCar +import androidx.compose.material.icons.rounded.DirectionsRun +import androidx.compose.material.icons.rounded.DirectionsWalk +import androidx.compose.material.icons.rounded.Event +import androidx.compose.material.icons.rounded.Favorite +import androidx.compose.material.icons.rounded.FitnessCenter +import androidx.compose.material.icons.rounded.Flag +import androidx.compose.material.icons.rounded.Flight +import androidx.compose.material.icons.rounded.FlightTakeoff +import androidx.compose.material.icons.rounded.Dehaze +import androidx.compose.material.icons.rounded.Forest +import androidx.compose.material.icons.rounded.Grain +import androidx.compose.material.icons.rounded.Group +import androidx.compose.material.icons.rounded.Hiking +import androidx.compose.material.icons.rounded.Home +import androidx.compose.material.icons.rounded.Hotel +import androidx.compose.material.icons.rounded.Landscape +import androidx.compose.material.icons.rounded.LocalBar +import androidx.compose.material.icons.rounded.LocalCafe +import androidx.compose.material.icons.rounded.LocalHospital +import androidx.compose.material.icons.rounded.LocalLibrary +import androidx.compose.material.icons.rounded.Luggage +import androidx.compose.material.icons.rounded.Map +import androidx.compose.material.icons.rounded.MusicNote +import androidx.compose.material.icons.rounded.Navigation +import androidx.compose.material.icons.rounded.Park +import androidx.compose.material.icons.rounded.Place +import androidx.compose.material.icons.rounded.Poll +import androidx.compose.material.icons.rounded.Public +import androidx.compose.material.icons.rounded.Restaurant +import androidx.compose.material.icons.rounded.Sailing +import androidx.compose.material.icons.rounded.Schedule +import androidx.compose.material.icons.rounded.ShoppingBag +import androidx.compose.material.icons.rounded.Star +import androidx.compose.material.icons.rounded.Storefront +import androidx.compose.material.icons.rounded.Thunderstorm +import androidx.compose.material.icons.rounded.TheaterComedy +import androidx.compose.material.icons.rounded.ConfirmationNumber +import androidx.compose.material.icons.rounded.Train +import androidx.compose.material.icons.rounded.Water +import androidx.compose.material.icons.rounded.WbCloudy +import androidx.compose.material.icons.rounded.WbSunny +import androidx.compose.material.icons.rounded.Cabin +import androidx.compose.ui.graphics.asAndroidPath +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.VectorGroup +import androidx.compose.ui.graphics.vector.VectorNode +import androidx.compose.ui.graphics.vector.VectorPath +import androidx.compose.ui.graphics.vector.PathParser +import androidx.glance.ImageProvider + +/** + * The widgets' icons: the Material Symbols (rounded) counterparts of the SF + * Symbols the snapshot names, so one snapshot draws on both platforms. A widget + * is RemoteViews, which cannot draw a Compose vector, so each icon is drawn + * once into a small white bitmap and tinted by the widget's theme colour. + */ +object TrekIcons { + /** The SF Symbol names client/src/native/widgetExtras.ts and widgets.ts use, and a few of the widgets' own. */ + private val SYMBOLS: Map = mapOf( + "airplane" to Icons.Rounded.Flight, + "airplane.departure" to Icons.Rounded.FlightTakeoff, + "tram.fill" to Icons.Rounded.Train, + "bus.fill" to Icons.Rounded.DirectionsBus, + "car.fill" to Icons.Rounded.DirectionsCar, + "ferry.fill" to Icons.Rounded.DirectionsBoat, + "sailboat.fill" to Icons.Rounded.Sailing, + "bed.double.fill" to Icons.Rounded.Hotel, + "house.fill" to Icons.Rounded.Home, + "tent.fill" to Icons.Rounded.Cabin, + "fork.knife" to Icons.Rounded.Restaurant, + "cup.and.saucer.fill" to Icons.Rounded.LocalCafe, + "mug.fill" to Icons.Rounded.LocalCafe, + "wineglass.fill" to Icons.Rounded.LocalBar, + "ticket.fill" to Icons.Rounded.ConfirmationNumber, + "theatermasks.fill" to Icons.Rounded.TheaterComedy, + "music.note" to Icons.Rounded.MusicNote, + "figure.hiking" to Icons.Rounded.Hiking, + "figure.walk" to Icons.Rounded.DirectionsWalk, + "figure.run" to Icons.Rounded.DirectionsRun, + "dumbbell.fill" to Icons.Rounded.FitnessCenter, + "bookmark.fill" to Icons.Rounded.Bookmark, + "building.columns.fill" to Icons.Rounded.AccountBalance, + "building.2.fill" to Icons.Rounded.AccountBalance, + "books.vertical.fill" to Icons.Rounded.LocalLibrary, + "storefront.fill" to Icons.Rounded.Storefront, + "bag.fill" to Icons.Rounded.ShoppingBag, + "backpack.fill" to Icons.Rounded.Backpack, + "suitcase.rolling.fill" to Icons.Rounded.Luggage, + "creditcard.fill" to Icons.Rounded.CreditCard, + "cross.case.fill" to Icons.Rounded.LocalHospital, + "camera.fill" to Icons.Rounded.CameraAlt, + "camera.macro" to Icons.Rounded.Park, + "leaf.fill" to Icons.Rounded.Park, + "tree.fill" to Icons.Rounded.Forest, + "mountain.2.fill" to Icons.Rounded.Landscape, + "water.waves" to Icons.Rounded.Water, + "beach.umbrella.fill" to Icons.Rounded.BeachAccess, + "sun.max.fill" to Icons.Rounded.WbSunny, + "bolt.fill" to Icons.Rounded.Bolt, + "heart.fill" to Icons.Rounded.Favorite, + "star.fill" to Icons.Rounded.Star, + "flag.fill" to Icons.Rounded.Flag, + "map.fill" to Icons.Rounded.Map, + "safari.fill" to Icons.Rounded.Navigation, + "location.north.fill" to Icons.Rounded.Navigation, + "location.fill" to Icons.Rounded.Place, + "globe.europe.africa.fill" to Icons.Rounded.Public, + "calendar" to Icons.Rounded.CalendarMonth, + "clock" to Icons.Rounded.Schedule, + "checklist" to Icons.Rounded.Checklist, + "checkmark.circle.fill" to Icons.Rounded.CheckCircle, + "person.2.fill" to Icons.Rounded.Group, + "bubble.left.fill" to Icons.Rounded.Chat, + "chart.bar.fill" to Icons.Rounded.Poll, + "event" to Icons.Rounded.Event, + ) + + /** A booking kind's symbol and colour, the same pairs as TrekStyle.swift. */ + fun booking(kind: String): Pair = when (kind) { + "flight" -> "airplane" to 0xFF4A7DDB.toInt() + "train" -> "tram.fill" to 0xFF2FA37A.toInt() + "bus" -> "bus.fill" to 0xFF2BA6A6.toInt() + "car" -> "car.fill" to 0xFFD6673B.toInt() + "cruise", "ferry", "boat" -> "ferry.fill" to 0xFF2E8BC0.toInt() + "hotel" -> "bed.double.fill" to 0xFF8E6CD9.toInt() + "restaurant" -> "fork.knife" to 0xFFE8A13A.toInt() + "event" -> "ticket.fill" to 0xFFD6408B.toInt() + "tour" -> "figure.hiking" to 0xFF4E9F3D.toInt() + else -> "bookmark.fill" to 0xFF7A7A85.toInt() + } + + /** The provider's main weather condition as an icon. */ + fun weather(main: String): ImageVector = when (main.lowercase()) { + "clear" -> Icons.Rounded.WbSunny + "clouds" -> Icons.Rounded.WbCloudy + "rain", "drizzle" -> Icons.Rounded.Grain + "thunderstorm" -> Icons.Rounded.Thunderstorm + "snow" -> Icons.Rounded.AcUnit + "mist", "fog", "haze" -> Icons.Rounded.Dehaze + else -> Icons.Rounded.Cloud + } + + fun vector(symbol: String?): ImageVector = symbol?.let { SYMBOLS[it] } ?: Icons.Rounded.Place + + private val cache = HashMap, Bitmap>() + + /** The icon as a white bitmap of [sizePx], tinted where it is drawn. */ + @Synchronized + fun bitmap(vector: ImageVector, sizePx: Int = 48): Bitmap = cache.getOrPut(vector to sizePx) { render(vector, sizePx) } + + fun provider(symbol: String?, sizePx: Int = 48): ImageProvider = ImageProvider(bitmap(vector(symbol), sizePx)) + + fun provider(vector: ImageVector, sizePx: Int = 48): ImageProvider = ImageProvider(bitmap(vector, sizePx)) + + /** The icon in [color], for places that draw it as it is (a notification's progress tracker). */ + fun bitmap(vector: ImageVector, sizePx: Int, color: Int): Bitmap = render(vector, sizePx, color) + + private fun render(vector: ImageVector, sizePx: Int, color: Int = android.graphics.Color.WHITE): Bitmap { + val bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888) + val canvas = Canvas(bitmap) + val scale = Matrix().apply { setScale(sizePx / vector.viewportWidth, sizePx / vector.viewportHeight) } + val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + this.color = color + style = Paint.Style.FILL + } + fun draw(node: VectorNode) { + when (node) { + is VectorGroup -> node.forEach { draw(it) } + is VectorPath -> { + val path: Path = PathParser().addPathNodes(node.pathData).toPath().asAndroidPath() + path.fillType = if (node.pathFillType == androidx.compose.ui.graphics.PathFillType.EvenOdd) { + Path.FillType.EVEN_ODD + } else { + Path.FillType.WINDING + } + path.transform(scale) + canvas.drawPath(path, paint) + } + } + } + draw(vector.root) + return bitmap + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/TrekWidgetReceivers.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/TrekWidgetReceivers.kt new file mode 100644 index 000000000..01fd1de68 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/TrekWidgetReceivers.kt @@ -0,0 +1,105 @@ +package com.liketrek.trek.widget + +import android.content.Context +import android.os.Build +import androidx.glance.appwidget.GlanceAppWidget +import androidx.glance.appwidget.GlanceAppWidgetManager +import androidx.glance.appwidget.GlanceAppWidgetReceiver +import androidx.glance.appwidget.updateAll +import kotlin.reflect.KClass +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +/** The widget providers the manifest lists, one per widget in the picker. */ +abstract class TrekWidgetReceiver : GlanceAppWidgetReceiver() { + override fun onDeleted(context: Context, appWidgetIds: IntArray) { + super.onDeleted(context, appWidgetIds) + WidgetStore.forget(context, appWidgetIds) + } +} + +class TripWidgetReceiver : TrekWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = TripWidget() +} + +class TodayWidgetReceiver : TrekWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = TodayWidget() +} + +class BookingsWidgetReceiver : TrekWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = BookingsWidget() +} + +class FlightWidgetReceiver : TrekWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = FlightWidget() +} + +class TodosWidgetReceiver : TrekWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = TodosWidget() +} + +class PackingWidgetReceiver : TrekWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = PackingWidget() +} + +class AtlasWidgetReceiver : TrekWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = AtlasWidget() +} + +class CollabWidgetReceiver : TrekWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = CollabWidget() +} + +/** Redraws every placed TREK widget after the app wrote a new snapshot. */ +object TrekWidgetUpdater { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + val receivers: List> = listOf( + TripWidgetReceiver::class, + TodayWidgetReceiver::class, + BookingsWidgetReceiver::class, + FlightWidgetReceiver::class, + TodosWidgetReceiver::class, + PackingWidgetReceiver::class, + AtlasWidgetReceiver::class, + CollabWidgetReceiver::class, + ) + + /** The widget a placed widget id belongs to, by its provider. */ + fun widgetFor(context: Context, appWidgetId: Int): GlanceAppWidget? { + val provider = android.appwidget.AppWidgetManager.getInstance(context).getAppWidgetInfo(appWidgetId)?.provider?.className + ?: return null + val receiver = receivers.firstOrNull { it.java.name == provider } ?: return null + return receiver.java.getDeclaredConstructor().newInstance().glanceAppWidget + } + + fun widgets(): List = + listOf(TripWidget(), TodayWidget(), BookingsWidget(), TodosWidget(), PackingWidget(), AtlasWidget(), CollabWidget()) + + @JvmStatic + fun refreshAll(context: Context) { + val app = context.applicationContext + scope.launch { for (widget in widgets()) runCatching { widget.updateAll(app) } } + } + + /** + * Android 15's widget picker shows a live preview drawn by the widget itself + * (providePreview) instead of a static image. The system rate-limits the + * call, so it runs once per app version. + */ + @JvmStatic + fun publishPreviews(context: Context) { + if (Build.VERSION.SDK_INT < 35) return + val app = context.applicationContext + val prefs = app.getSharedPreferences("trek.widgets", Context.MODE_PRIVATE) + val version = runCatching { app.packageManager.getPackageInfo(app.packageName, 0).lastUpdateTime }.getOrDefault(0L) + if (prefs.getLong("previews", -1L) == version) return + scope.launch { + val manager = GlanceAppWidgetManager(app) + val all = receivers.all { runCatching { manager.setWidgetPreviews(it); true }.getOrDefault(false) } + if (all) prefs.edit().putLong("previews", version).apply() + } + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/TrekWidgets.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/TrekWidgets.kt new file mode 100644 index 000000000..1af7aa1e8 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/TrekWidgets.kt @@ -0,0 +1,982 @@ +package com.liketrek.trek.widget + +import android.content.Context +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.CalendarMonth +import androidx.compose.material.icons.rounded.CheckCircle +import androidx.compose.material.icons.rounded.Flight +import androidx.compose.material.icons.rounded.Group +import androidx.compose.material.icons.rounded.Luggage +import androidx.compose.material.icons.rounded.Place +import androidx.compose.material.icons.rounded.Public +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.glance.ColorFilter +import androidx.glance.GlanceId +import androidx.glance.GlanceModifier +import androidx.glance.GlanceTheme +import androidx.glance.Image +import androidx.glance.ImageProvider +import androidx.glance.LocalContext +import androidx.glance.LocalSize +import androidx.glance.action.clickable +import androidx.glance.appwidget.GlanceAppWidget +import androidx.glance.appwidget.GlanceAppWidgetManager +import androidx.glance.appwidget.SizeMode +import androidx.glance.appwidget.cornerRadius +import androidx.glance.appwidget.provideContent +import androidx.glance.background +import androidx.glance.layout.Alignment +import androidx.glance.layout.Box +import androidx.glance.layout.Column +import androidx.glance.layout.ColumnScope +import androidx.glance.layout.ContentScale +import androidx.glance.layout.Row +import androidx.glance.layout.Spacer +import androidx.glance.layout.fillMaxHeight +import androidx.glance.layout.fillMaxSize +import androidx.glance.layout.fillMaxWidth +import androidx.glance.layout.height +import androidx.glance.layout.padding +import androidx.glance.layout.size +import androidx.glance.layout.width +import androidx.glance.text.FontWeight +import androidx.glance.text.Text +import androidx.glance.text.TextAlign +import androidx.glance.text.TextStyle +import androidx.glance.unit.ColorProvider +import java.time.LocalDate + +/** The sizes every TREK widget lays itself out for (a 2x2, a 4x2 and a 4x4 cell block). */ +object TrekSizes { + val SMALL = DpSize(120.dp, 120.dp) + val WIDE = DpSize(250.dp, 120.dp) + val LARGE = DpSize(250.dp, 260.dp) + val all = setOf(SMALL, WIDE, LARGE) +} + +private val DpSize.isWide get() = width >= 220.dp +private val DpSize.isTall get() = height >= 220.dp + +/** + * A TREK widget: reads the snapshot of the trip it is set to (WidgetStore) and + * draws [Content]. The app writes the snapshot and refreshes the widgets + * (TrekWidgetUpdater); [preview] draws the same views from a sample trip for + * the widget picker and the screenshot tests. + */ +abstract class TrekWidget : GlanceAppWidget() { + override val sizeMode: SizeMode = SizeMode.Responsive(TrekSizes.all) + override val previewSizeMode = SizeMode.Responsive(TrekSizes.all) + + /** Whether the widget shows one trip, so the trip picker applies to it. */ + open val perTrip: Boolean = true + + override suspend fun provideGlance(context: Context, id: GlanceId) { + val appWidgetId = runCatching { GlanceAppWidgetManager(context).getAppWidgetId(id) }.getOrDefault(-1) + provideContent { + // Read inside the composition: a session outlives one update, and every + // write (the dashboard's, then each trip's) must reach it. + val version by WidgetStore.version.collectAsState() + val snapshot = remember(version) { + val tripId = if (perTrip && appWidgetId >= 0) WidgetStore.tripFor(context, appWidgetId) else WidgetStore.AUTO + WidgetStore.load(context, tripId) + } + TrekWidgetTheme.Themed { Content(snapshot) } + } + } + + override suspend fun providePreview(context: Context, widgetCategory: Int) { + provideContent { TrekWidgetTheme.Themed { Content(WidgetSamples.snapshot(running = false)) } } + } + + @Composable + abstract fun Content(snapshot: WidgetSnapshot?) +} + +// ---- Trip ---- + +/** The trip: a countdown on its own cover before it starts, the day and what comes next while it runs. */ +class TripWidget : TrekWidget() { + @Composable + override fun Content(snapshot: WidgetSnapshot?) { + val context = LocalContext.current + val trip = snapshot?.trip + if (snapshot == null || trip == null) { + EmptyWidget(snapshot?.labels?.noTrip ?: WidgetSamples.emptyText(context)) + return + } + val size = LocalSize.current + WidgetFrame(onClick = openPath(context, trip.path), background = TrekStatus.scrim, padding = 0.dp) { + Box(modifier = GlanceModifier.fillMaxSize()) { + Image( + provider = ImageProvider(WidgetArt.cover(trip.cover) ?: WidgetArt.sky(trip.title)), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = GlanceModifier.fillMaxSize(), + ) + Image( + provider = ImageProvider(com.liketrek.trek.R.drawable.widget_scrim), + contentDescription = null, + contentScale = ContentScale.FillBounds, + modifier = GlanceModifier.fillMaxSize(), + ) + Column(modifier = GlanceModifier.fillMaxSize().padding(14.dp)) { + val today = snapshot.today + if (today != null) Running(snapshot, trip, today, size) else Upcoming(snapshot, trip, size) + } + } + } + } + + @Composable + private fun ColumnScope.Upcoming(snapshot: WidgetSnapshot, trip: WidgetSnapshot.Trip, size: DpSize) { + val context = LocalContext.current + val labels = snapshot.labels + val days = (snapshot.daysUntilStart() ?: 0L).coerceAtLeast(0L) + if (!size.isWide) { + // Small: the number carries it, with the trip's name under it. + Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Rounded.Flight, TrekStatus.white, 16.dp) + Spacer(GlanceModifier.defaultWeight()) + snapshot.weather?.let { WeatherChip(it, onPhoto = true) } + } + Spacer(GlanceModifier.defaultWeight()) + Countdown(days, labels, ring = false) + Line(trip.title, 14.sp, TrekStatus.white, FontWeight.Bold, maxLines = 1) + return + } + Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Column(modifier = GlanceModifier.defaultWeight()) { + Eyebrow(labels.nextTrip, TrekStatus.whiteMuted) + Spacer(GlanceModifier.height(2.dp)) + Line(trip.title, if (size.isTall) 22.sp else 18.sp, TrekStatus.white, FontWeight.Bold, maxLines = 2) + trip.place?.let { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Rounded.Place, TrekStatus.whiteMuted, 12.dp) + Spacer(GlanceModifier.width(3.dp)) + Line(it, 12.sp, TrekStatus.whiteMuted, FontWeight.Medium) + } + } + if (size.isTall) { + RelativeDay.range(context, trip.start, trip.end)?.let { + Spacer(GlanceModifier.height(6.dp)) + Chip(it, TrekStatus.glass, TrekStatus.white, TrekIcons.provider(Icons.Rounded.CalendarMonth), TrekStatus.white) + } + } + } + Spacer(GlanceModifier.width(10.dp)) + Countdown(days, labels, ring = true) + } + if (size.isTall) { + Spacer(GlanceModifier.defaultWeight()) + TripFacts(snapshot, onPhoto = true) + snapshot.bookings.firstOrNull()?.let { + Spacer(GlanceModifier.height(8.dp)) + BookingRow(it, labels, onPhoto = true) + } + } + } + + /** The days to go: a big number, or today and tomorrow in words; around a ring of the last 60 days on the wide sizes. */ + @Composable + private fun Countdown(days: Long, labels: WidgetSnapshot.Labels, ring: Boolean) { + val number: @Composable () -> Unit = { + when (days) { + 0L -> Line(labels.todayShort, 26.sp, TrekStatus.white, FontWeight.Bold) + 1L -> Line(labels.tomorrow, 20.sp, TrekStatus.white, FontWeight.Bold) + else -> if (ring) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text( + text = days.toString(), + style = TextStyle(color = TrekStatus.white, fontSize = if (days > 99) 22.sp else 28.sp, fontWeight = FontWeight.Bold), + maxLines = 1, + ) + Eyebrow(labels.days, TrekStatus.whiteMuted) + } + } else { + Row(verticalAlignment = Alignment.Bottom) { + Text(days.toString(), style = TextStyle(color = TrekStatus.white, fontSize = 34.sp, fontWeight = FontWeight.Bold), maxLines = 1) + Spacer(GlanceModifier.width(4.dp)) + Line(labels.days, 13.sp, TrekStatus.whiteMuted, FontWeight.Bold, modifier = GlanceModifier.padding(bottom = 6.dp)) + } + } + } + } + if (!ring) { + number() + return + } + val progress = 1f - (days.coerceAtMost(60L).toFloat() / 60f) + Box(modifier = GlanceModifier.size(84.dp), contentAlignment = Alignment.Center) { + Image( + provider = ImageProvider(WidgetArt.ring(progress)), + contentDescription = null, + colorFilter = ColorFilter.tint(TrekStatus.white), + modifier = GlanceModifier.fillMaxSize(), + ) + number() + } + } + + @Composable + private fun ColumnScope.Running(snapshot: WidgetSnapshot, trip: WidgetSnapshot.Trip, today: WidgetSnapshot.Today, size: DpSize) { + val labels = snapshot.labels + val now = nowMinutes() + val next = today.stops.firstOrNull { (it.minutes ?: -1) >= now } ?: today.stops.lastOrNull() + val index = today.index ?: 1 + val total = today.total ?: snapshot.tripLength ?: 1 + Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Eyebrow(if (size.isWide) trip.title else today.dayLabel, TrekStatus.whiteMuted, GlanceModifier.defaultWeight()) + snapshot.weather?.let { WeatherChip(it, onPhoto = true) } + } + if (size.isWide) Line(today.dayLabel, 20.sp, TrekStatus.white, FontWeight.Bold, modifier = GlanceModifier.padding(top = 2.dp)) + Spacer(GlanceModifier.height(8.dp)) + DaySegments(index, total, TrekStatus.white) + Spacer(GlanceModifier.defaultWeight()) + if (size.isWide) { + Column(modifier = GlanceModifier.fillMaxWidth().background(TrekStatus.glass).cornerRadius(16.dp).padding(10.dp)) { + StopList(today.stops, now, limit = if (size.isTall) 5 else 1, onPhoto = true, nothing = labels.nothingPlanned, nowLabel = labels.now) + } + } else if (next != null) { + Line(next.time ?: labels.today, 26.sp, TrekStatus.white, FontWeight.Bold) + Line(next.name, 14.sp, TrekStatus.white, FontWeight.Bold, maxLines = 2) + } else { + Line(labels.nothingPlanned, 14.sp, TrekStatus.white, FontWeight.Bold, maxLines = 3) + } + } +} + +/** The trip's numbers: days, places, travellers. */ +@Composable +private fun TripFacts(snapshot: WidgetSnapshot, onPhoto: Boolean) { + val labels = snapshot.labels + val facts = listOfNotNull( + snapshot.tripLength?.let { it to labels.days }, + snapshot.trip?.placeCount?.let { it to labels.places }, + snapshot.trip?.memberCount?.let { it to labels.travellers }, + ) + Row(modifier = GlanceModifier.fillMaxWidth()) { + facts.forEachIndexed { i, (value, label) -> + Column( + modifier = GlanceModifier.defaultWeight().background(if (onPhoto) TrekStatus.glass else GlanceTheme.colors.secondaryContainer) + .cornerRadius(14.dp).padding(horizontal = 10.dp, vertical = 6.dp), + ) { + Line(value.toString(), 18.sp, if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSecondaryContainer, FontWeight.Bold) + Line(label, 11.sp, if (onPhoto) TrekStatus.whiteMuted else GlanceTheme.colors.onSecondaryContainer) + } + if (i < facts.size - 1) Spacer(GlanceModifier.width(6.dp)) + } + } +} + +// ---- Today ---- + +/** Today's plan as a timeline, with the weather and what is next. */ +class TodayWidget : TrekWidget() { + @Composable + override fun Content(snapshot: WidgetSnapshot?) { + val context = LocalContext.current + val size = LocalSize.current + val labels = snapshot?.labels + val today = snapshot?.today + val trip = snapshot?.trip + if (snapshot == null || labels == null || trip == null) { + EmptyWidget(labels?.noTrip ?: WidgetSamples.emptyText(context)) + return + } + WidgetFrame(onClick = openPath(context, trip.path)) { + Column(modifier = GlanceModifier.fillMaxSize()) { + Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Column(modifier = GlanceModifier.defaultWeight()) { + if (size.isTall) Eyebrow(if (today != null) labels.today else labels.nextTrip, GlanceTheme.colors.primary) + Line(today?.dayLabel ?: trip.title, if (size.isWide) 17.sp else 14.sp, weight = FontWeight.Bold) + } + snapshot.weather?.let { WeatherChip(it, onPhoto = false) } + } + Spacer(GlanceModifier.height(if (size.isTall) 10.dp else 6.dp)) + if (today == null || today.stops.isEmpty()) { + Spacer(GlanceModifier.defaultWeight()) + val days = snapshot.daysUntilStart() + val text = if (today == null && days != null && days > 0) labels.inDays.replace("{n}", days.toString()) else labels.nothingPlanned + Line(text, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 3) + Spacer(GlanceModifier.defaultWeight()) + } else { + val limit = when { + size.isTall -> 6 + size.isWide -> 2 + else -> 1 + } + StopList(today.stops, nowMinutes(), limit, onPhoto = false, nothing = labels.nothingPlanned, nowLabel = labels.now, compact = !size.isWide) + } + } + } + } +} + +/** The stops from the next one on, at most [limit], the next one marked. */ +@Composable +fun StopList( + stops: List, + nowMinutes: Int, + limit: Int, + onPhoto: Boolean, + nothing: String, + nowLabel: String, + compact: Boolean = false, +) { + if (stops.isEmpty()) { + Line(nothing, 13.sp, if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSurfaceVariant) + return + } + val nextIndex = stops.indexOfFirst { (it.minutes ?: -1) >= nowMinutes }.let { if (it < 0) stops.size - 1 else it } + // Keep the last done stop in view when there is room, so the day reads as a line. + val from = (nextIndex - if (limit > 3) 1 else 0).coerceIn(0, (stops.size - limit).coerceAtLeast(0)) + val shown = stops.drop(from).take(limit) + shown.forEachIndexed { i, stop -> + val index = from + i + val isNext = index == nextIndex + val done = index < nextIndex + val ink = when { + onPhoto -> if (done) TrekStatus.whiteFaint else TrekStatus.white + done -> GlanceTheme.colors.onSurfaceVariant + else -> GlanceTheme.colors.onSurface + } + Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 3.dp), verticalAlignment = Alignment.CenterVertically) { + val accent = cssColor(stop.color) ?: if (onPhoto) TrekStatus.white else GlanceTheme.colors.primary + if (compact) { + Box(modifier = GlanceModifier.size(8.dp).cornerRadius(4.dp).background(accent)) {} + } else { + IconBadge( + stop.symbol, + tint = if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSecondaryContainer, + background = if (onPhoto) TrekStatus.glass else GlanceTheme.colors.secondaryContainer, + size = 26.dp, + ) + } + Spacer(GlanceModifier.width(8.dp)) + Column(modifier = GlanceModifier.defaultWeight()) { + Line(stop.name, 13.sp, ink, if (isNext) FontWeight.Bold else FontWeight.Medium) + if (compact && stop.time != null) Line(stop.time, 11.sp, if (onPhoto) TrekStatus.whiteMuted else GlanceTheme.colors.onSurfaceVariant) + } + if (!compact) { + if (isNext && !onPhoto) { + Chip(stop.time ?: nowLabel, GlanceTheme.colors.primary, GlanceTheme.colors.onPrimary) + } else { + Line(stop.time ?: "", 12.sp, ink, if (isNext) FontWeight.Bold else FontWeight.Normal) + } + } + } + } +} + +// ---- Bookings ---- + +/** The next flights, trains, hotels and tables, and when they are due. */ +class BookingsWidget : TrekWidget() { + @Composable + override fun Content(snapshot: WidgetSnapshot?) { + val context = LocalContext.current + val size = LocalSize.current + val labels = snapshot?.labels ?: return EmptyWidget(WidgetSamples.emptyText(context)) + val bookings = snapshot.bookings + WidgetFrame(onClick = openPath(context, bookings.firstOrNull()?.path ?: snapshot.trip?.path ?: "/")) { + Column(modifier = GlanceModifier.fillMaxSize()) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Rounded.Flight, GlanceTheme.colors.primary, 14.dp) + Spacer(GlanceModifier.width(5.dp)) + Eyebrow(labels.bookings, GlanceTheme.colors.primary) + } + Spacer(GlanceModifier.height(8.dp)) + if (bookings.isEmpty()) { + Spacer(GlanceModifier.defaultWeight()) + Line(labels.noBookings, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 2) + Spacer(GlanceModifier.defaultWeight()) + } else if (!size.isWide) { + val first = bookings.first() + val (symbol, color) = TrekIcons.booking(first.kind) + IconBadge(symbol, TrekStatus.white, ColorProvider(androidx.compose.ui.graphics.Color(color)), 30.dp) + Spacer(GlanceModifier.defaultWeight()) + Line(first.title, 14.sp, weight = FontWeight.Bold, maxLines = 1) + Line( + listOfNotNull(RelativeDay.label(first.date, labels), first.time).joinToString(", "), + 12.sp, + GlanceTheme.colors.onSurfaceVariant, + ) + } else { + val limit = if (size.isTall) 4 else 1 + bookings.take(limit).forEach { booking -> + BookingRow(booking, labels, onPhoto = false) + Spacer(GlanceModifier.height(5.dp)) + } + } + } + } + } +} + +@Composable +private fun BookingRow(booking: WidgetSnapshot.Booking, labels: WidgetSnapshot.Labels, onPhoto: Boolean) { + val context = LocalContext.current + val (symbol, color) = TrekIcons.booking(booking.kind) + Row( + modifier = GlanceModifier.fillMaxWidth() + .background(if (onPhoto) TrekStatus.glass else GlanceTheme.colors.surfaceVariant) + .cornerRadius(14.dp).padding(horizontal = 8.dp, vertical = 6.dp) + .clickable(openPath(context, booking.path)), + verticalAlignment = Alignment.CenterVertically, + ) { + IconBadge(symbol, TrekStatus.white, ColorProvider(androidx.compose.ui.graphics.Color(color)), 30.dp) + Spacer(GlanceModifier.width(10.dp)) + Column(modifier = GlanceModifier.defaultWeight()) { + Line(booking.title, 13.sp, if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSurface, FontWeight.Bold) + booking.detail?.let { Line(it, 11.sp, if (onPhoto) TrekStatus.whiteMuted else GlanceTheme.colors.onSurfaceVariant) } + } + Spacer(GlanceModifier.width(6.dp)) + Column(horizontalAlignment = Alignment.End) { + RelativeDay.label(booking.date, labels)?.let { Line(it, 12.sp, if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSurface, FontWeight.Bold) } + Row(verticalAlignment = Alignment.CenterVertically) { + Box(modifier = GlanceModifier.size(6.dp).cornerRadius(3.dp).background(if (booking.confirmed) TrekStatus.confirmed else TrekStatus.pending)) {} + Spacer(GlanceModifier.width(4.dp)) + Line(booking.time ?: if (booking.confirmed) labels.confirmed else labels.pending, 11.sp, if (onPhoto) TrekStatus.whiteMuted else GlanceTheme.colors.onSurfaceVariant) + } + } + } +} + +// ---- Flight ---- + +/** + * Where a flight stands now (as FlightMoment on iOS). What the feed saw wins: a + * flight still at the gate past its planned departure is not flown along the + * arc, and it is only landed once confirmed. Only a flight the feed never heard + * of moves on by its schedule alone; a lost one stops two hours after arrival. + */ +private class FlightMoment(f: WidgetSnapshot.Flight, nowSeconds: Long) { + val start: Long = f.depActual ?: f.depExpected ?: f.dep + val end: Long = maxOf(f.arrExpected ?: f.arr, start + 60) + private val heard = f.seen != null + val landed = f.landed || (!heard && nowSeconds >= end) || nowSeconds >= end + 7200 + val airborne = !landed && (f.airborne || f.depActual != null || (!heard && nowSeconds >= start)) + val ready = !landed && !airborne && nowSeconds >= start + val progress: Float = when { + landed -> 1f + airborne -> ((nowSeconds - start).toFloat() / (end - start)).coerceIn(0f, 0.98f) + else -> 0f + } +} + +/** A duration in the app's words: "2 d 4 h", "1 h 5 min", "12 min". */ +private fun durationText(seconds: Long, labels: WidgetSnapshot.Labels): String { + val minutes = ((seconds + 59) / 60).coerceAtLeast(1) + val days = minutes / 1440 + val hours = (minutes % 1440) / 60 + val rest = minutes % 60 + return when { + days > 0 -> labels.durDaysHours.replace("{d}", "$days").replace("{h}", "$hours") + hours > 0 -> labels.durHoursMinutes.replace("{h}", "$hours").replace("{m}", "$rest") + else -> labels.durMinutes.replace("{m}", "$rest") + } +} + +/** "Departs in 2 h 10 min", "Lands in 1 h 5 min", "Landed". */ +private fun momentText(m: FlightMoment, labels: WidgetSnapshot.Labels, nowSeconds: Long): String = when { + m.landed -> labels.flightLanded + m.ready -> labels.flightReady + m.airborne -> labels.flightLands.replace("{time}", durationText(m.end - nowSeconds, labels)) + else -> labels.flightDeparts.replace("{time}", durationText(m.start - nowSeconds, labels)) +} + +/** The delay as a chip's text and colour; nothing to say without data. */ +private fun delayChip(delay: Int?, labels: WidgetSnapshot.Labels): Pair? = when { + delay == null -> null + delay > 5 -> labels.flightLate.replace("{m}", "$delay") to (if (delay >= 30) TrekStatus.danger else TrekStatus.pending) + delay < -5 -> labels.flightEarly.replace("{m}", "${-delay}") to TrekStatus.confirmed + else -> labels.flightOnTime to TrekStatus.confirmed +} + +private const val FLIGHT_BLUE = 0xFF4A7DDB.toInt() + +/** + * The trip's next flight, or the one in the air: both airports large, the + * route as an arc with the aircraft on it, the moment in words and the delay. + * The arc and the words follow the clock each time the widget is drawn. + */ +class FlightWidget : TrekWidget() { + @Composable + override fun Content(snapshot: WidgetSnapshot?) { + val context = LocalContext.current + val size = LocalSize.current + val labels = snapshot?.labels ?: return EmptyWidget(WidgetSamples.emptyText(context)) + val flight = snapshot.flight + WidgetFrame(onClick = openPath(context, flight?.path ?: snapshot.trip?.path ?: "/")) { + Column(modifier = GlanceModifier.fillMaxSize()) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = GlanceModifier.fillMaxWidth()) { + Icon(Icons.Rounded.Flight, GlanceTheme.colors.primary, 14.dp) + Spacer(GlanceModifier.width(5.dp)) + Eyebrow(flight?.number ?: labels.flight, GlanceTheme.colors.primary, GlanceModifier.defaultWeight()) + flight?.let { f -> + delayChip(f.delay, labels)?.let { (text, color) -> + if (size.isWide || (f.delay ?: 0) > 5) Chip(text, GlanceTheme.colors.surfaceVariant, color) + } + } + } + if (flight == null) { + Spacer(GlanceModifier.defaultWeight()) + Line(labels.noFlight, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 2) + Spacer(GlanceModifier.defaultWeight()) + } else { + FlightBody(flight, labels, size.isWide, size.isTall) + } + } + } + } +} + +/** + * The origin stands on the right in a right-to-left layout, so the drawn arc is + * mirrored with it. Read from the locale the widget speaks, not from the + * Configuration, which a composition may not read directly. + */ +private fun isRtl(): Boolean = + android.text.TextUtils.getLayoutDirectionFromLocale(java.util.Locale.getDefault()) == android.view.View.LAYOUT_DIRECTION_RTL + +@Composable +private fun ColumnScope.FlightBody(f: WidgetSnapshot.Flight, labels: WidgetSnapshot.Labels, wide: Boolean, tall: Boolean) { + val now = System.currentTimeMillis() / 1000 + val m = FlightMoment(f, now) + val arrival = f.arrTimeExpected ?: f.arrTime + val momentColor = if (m.airborne) GlanceTheme.colors.primary else GlanceTheme.colors.onSurface + Spacer(GlanceModifier.defaultWeight()) + if (!wide) Line(momentText(m, labels, now), 13.sp, momentColor, FontWeight.Bold, maxLines = 2) + Spacer(GlanceModifier.height(6.dp)) + Row(verticalAlignment = Alignment.CenterVertically, modifier = GlanceModifier.fillMaxWidth()) { + Column(modifier = GlanceModifier.defaultWeight()) { + Line(f.from, if (wide) 26.sp else 22.sp, weight = FontWeight.Bold) + if (wide) f.fromCity?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant) } + } + if (wide) { + Image( + provider = ImageProvider(WidgetArt.flightArc(m.progress, FLIGHT_BLUE, android.graphics.Color.argb(90, 120, 120, 130), rtl = isRtl())), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = GlanceModifier.width(120.dp).height(26.dp), + ) + } + Column(modifier = GlanceModifier.defaultWeight(), horizontalAlignment = Alignment.End) { + Line(f.to, if (wide) 26.sp else 22.sp, weight = FontWeight.Bold) + if (wide) f.toCity?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant) } + } + } + if (!wide) { + Image( + provider = ImageProvider(WidgetArt.flightArc(m.progress, FLIGHT_BLUE, android.graphics.Color.argb(90, 120, 120, 130), rtl = isRtl())), + contentDescription = null, + contentScale = ContentScale.FillBounds, + modifier = GlanceModifier.fillMaxWidth().height(22.dp), + ) + } + Spacer(GlanceModifier.height(4.dp)) + Row(modifier = GlanceModifier.fillMaxWidth()) { + Line(f.depTime, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold, modifier = GlanceModifier.defaultWeight()) + Line(arrival, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold) + } + if (wide) { + Spacer(GlanceModifier.height(8.dp)) + Line(momentText(m, labels, now), 13.sp, momentColor, FontWeight.Bold) + if (m.airborne) { + Spacer(GlanceModifier.height(5.dp)) + Bar(m.progress, GlanceTheme.colors.primary, GlanceTheme.colors.surfaceVariant, 5.dp) + } + } + if (tall) { + Spacer(GlanceModifier.height(10.dp)) + f.aircraft?.let { FlightFact(it) } + f.fromCity?.let { from -> f.toCity?.let { to -> FlightFact("$from \u2192 $to") } } + } + Spacer(GlanceModifier.defaultWeight()) +} + +@Composable +private fun FlightFact(text: String) { + Row( + modifier = GlanceModifier.fillMaxWidth().background(GlanceTheme.colors.surfaceVariant).cornerRadius(12.dp) + .padding(horizontal = 10.dp, vertical = 7.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(Icons.Rounded.Flight, GlanceTheme.colors.primary, 13.dp) + Spacer(GlanceModifier.width(7.dp)) + Line(text, 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium) + } + Spacer(GlanceModifier.height(5.dp)) +} + +// ---- To-dos ---- + +/** What is still open for the trip, and how far the packing has come. */ +class TodosWidget : TrekWidget() { + @Composable + override fun Content(snapshot: WidgetSnapshot?) { + val context = LocalContext.current + val size = LocalSize.current + val labels = snapshot?.labels ?: return EmptyWidget(WidgetSamples.emptyText(context)) + val todos = snapshot.todos + WidgetFrame(onClick = openPath(context, todos?.path ?: snapshot.trip?.path ?: "/")) { + Column(modifier = GlanceModifier.fillMaxSize()) { + Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Rounded.CheckCircle, GlanceTheme.colors.primary, 14.dp) + Spacer(GlanceModifier.width(5.dp)) + Eyebrow(labels.todos, GlanceTheme.colors.primary, GlanceModifier.defaultWeight()) + if (todos != null && todos.total > 0) Line("${todos.total - todos.open}/${todos.total}", 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold) + } + Spacer(GlanceModifier.height(8.dp)) + if (todos == null || todos.open == 0) { + Spacer(GlanceModifier.defaultWeight()) + Line(labels.noTodos, 16.sp, weight = FontWeight.Bold) + snapshot.trip?.title?.let { Line(it, 12.sp, GlanceTheme.colors.onSurfaceVariant) } + Spacer(GlanceModifier.defaultWeight()) + } else { + if (!size.isWide) { + Line(todos.open.toString(), 34.sp, GlanceTheme.colors.primary, FontWeight.Bold) + Spacer(GlanceModifier.defaultWeight()) + } + val limit = when { + size.isTall -> 6 + size.isWide -> 3 + else -> 1 + } + Column(modifier = GlanceModifier.fillMaxWidth()) { + todos.items.take(limit).forEach { todo -> + Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 3.dp), verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = GlanceModifier.size(14.dp).cornerRadius(7.dp).background(priorityColor(todo.priority) ?: GlanceTheme.colors.outline), + contentAlignment = Alignment.Center, + ) { + Box(modifier = GlanceModifier.size(10.dp).cornerRadius(5.dp).background(GlanceTheme.colors.widgetBackground)) {} + } + Spacer(GlanceModifier.width(8.dp)) + Line(todo.name, 13.sp, modifier = GlanceModifier.defaultWeight()) + if (size.isWide) RelativeDay.label(todo.due, labels)?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium) } + } + } + } + if (size.isWide) Spacer(GlanceModifier.defaultWeight()) + } + val packing = snapshot.packing + if (size.isTall && packing != null && packing.total > 0) { + Spacer(GlanceModifier.height(8.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Rounded.Luggage, GlanceTheme.colors.onSurfaceVariant, 13.dp) + Spacer(GlanceModifier.width(5.dp)) + Line("${labels.packing}: ${packing.packed}/${packing.total}", 12.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium) + } + Spacer(GlanceModifier.height(5.dp)) + Bar(packing.packed.toFloat() / packing.total, GlanceTheme.colors.primary, GlanceTheme.colors.surfaceVariant) + } + } + } + } + + private fun priorityColor(priority: Int): ColorProvider? = when (priority) { + 3 -> TrekStatus.danger + 2 -> TrekStatus.pending + 1 -> ColorProvider(androidx.compose.ui.graphics.Color(0xFF4A7DDB)) + else -> null + } +} + +// ---- Packing ---- + +/** How full the bags are, their weight, and what is still missing. */ +class PackingWidget : TrekWidget() { + @Composable + override fun Content(snapshot: WidgetSnapshot?) { + val context = LocalContext.current + val size = LocalSize.current + val labels = snapshot?.labels ?: return EmptyWidget(WidgetSamples.emptyText(context)) + val packing = snapshot.packing + WidgetFrame(onClick = openPath(context, packing?.path ?: snapshot.trip?.path ?: "/")) { + Column(modifier = GlanceModifier.fillMaxSize()) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Rounded.Luggage, GlanceTheme.colors.primary, 14.dp) + Spacer(GlanceModifier.width(5.dp)) + Eyebrow(labels.packing, GlanceTheme.colors.primary) + } + if (packing == null || packing.total == 0) { + Spacer(GlanceModifier.defaultWeight()) + Line(snapshot.trip?.title ?: labels.noTrip, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 3) + Spacer(GlanceModifier.defaultWeight()) + return@Column + } + val progress = packing.packed.toFloat() / packing.total + Spacer(GlanceModifier.height(if (size.isWide) 8.dp else 4.dp)) + if (!size.isWide) { + // Small: the ring is the widget. + Box(modifier = GlanceModifier.fillMaxWidth().defaultWeight(), contentAlignment = Alignment.Center) { + PackRing(progress, 64.dp) + } + Line("${packing.packed}/${packing.total} ${labels.packed}", 11.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium) + return@Column + } + Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + PackRing(progress, 64.dp) + Spacer(GlanceModifier.width(12.dp)) + Column(modifier = GlanceModifier.defaultWeight()) { + Line("${packing.packed}/${packing.total}", 18.sp, weight = FontWeight.Bold) + Line(labels.packed, 12.sp, GlanceTheme.colors.onSurfaceVariant) + if (!size.isTall && packing.missing.isNotEmpty()) { + Line("${packing.missing.size} ${labels.missing}", 12.sp, GlanceTheme.colors.primary, FontWeight.Medium) + } + } + } + if (size.isTall) { + Spacer(GlanceModifier.height(10.dp)) + // Each group in a column of its own: a Glance column takes ten children at most. + Column(modifier = GlanceModifier.fillMaxWidth()) { + packing.bags.take(2).forEach { bag -> BagRow(bag) } + } + if (packing.missing.isNotEmpty()) { + Spacer(GlanceModifier.height(4.dp)) + Column(modifier = GlanceModifier.fillMaxWidth()) { + Eyebrow(labels.missing) + Spacer(GlanceModifier.height(2.dp)) + packing.missing.take(2).forEach { item -> + Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) { + Box(modifier = GlanceModifier.size(6.dp).cornerRadius(3.dp).background(cssColor(item.color) ?: GlanceTheme.colors.outline)) {} + Spacer(GlanceModifier.width(8.dp)) + Line(item.name, 12.sp, modifier = GlanceModifier.defaultWeight()) + item.category?.let { Line(it, 11.sp, GlanceTheme.colors.onSurfaceVariant) } + } + } + } + } + } + } + } + } + + @Composable + private fun PackRing(progress: Float, size: androidx.compose.ui.unit.Dp) { + Box(modifier = GlanceModifier.size(size), contentAlignment = Alignment.Center) { + Image( + provider = ImageProvider(WidgetArt.ring(progress, stroke = 16f)), + contentDescription = null, + colorFilter = ColorFilter.tint(GlanceTheme.colors.primary), + modifier = GlanceModifier.fillMaxSize(), + ) + Line("${(progress * 100).toInt()}%", 13.sp, weight = FontWeight.Bold) + } + } + + @Composable + private fun BagRow(bag: WidgetSnapshot.Bag) { + val bagColor = cssColor(bag.color) ?: GlanceTheme.colors.primary + Column(modifier = GlanceModifier.fillMaxWidth().padding(bottom = 6.dp)) { + Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Box(modifier = GlanceModifier.size(8.dp).cornerRadius(4.dp).background(bagColor)) {} + Spacer(GlanceModifier.width(6.dp)) + Line(bag.name, 12.sp, weight = FontWeight.Medium, modifier = GlanceModifier.defaultWeight()) + Line(weight(bag.grams) + (bag.limit?.let { " / ${weight(it)}" } ?: ""), 11.sp, GlanceTheme.colors.onSurfaceVariant) + } + Spacer(GlanceModifier.height(4.dp)) + Bar(if (bag.limit != null && bag.limit > 0) bag.grams.toFloat() / bag.limit else bag.packed.toFloat() / bag.total.coerceAtLeast(1), bagColor, GlanceTheme.colors.surfaceVariant, 5.dp) + } + } + + private fun weight(grams: Int): String = if (grams >= 1000) "%.1f kg".format(grams / 1000f) else "$grams g" +} + +// ---- Atlas ---- + +/** The countries the user has been to, glowing on the world map. Not tied to a trip. */ +class AtlasWidget : TrekWidget() { + override val perTrip = false + + @Composable + override fun Content(snapshot: WidgetSnapshot?) { + val context = LocalContext.current + val size = LocalSize.current + val labels = snapshot?.labels ?: return EmptyWidget(WidgetSamples.emptyText(context)) + val atlas = snapshot.atlas + val codes = atlas?.codes?.toSet() ?: emptySet() + WidgetFrame(onClick = openPath(context, "/atlas")) { + Column(modifier = GlanceModifier.fillMaxSize()) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Rounded.Public, GlanceTheme.colors.primary, 14.dp) + Spacer(GlanceModifier.width(5.dp)) + Eyebrow(context.getString(com.liketrek.trek.R.string.widget_atlas_name), GlanceTheme.colors.primary) + } + Spacer(GlanceModifier.height(4.dp)) + val count: @Composable () -> Unit = { + Row(verticalAlignment = Alignment.Bottom) { + Line((atlas?.count ?: 0).toString(), if (size.isWide) 34.sp else 30.sp, GlanceTheme.colors.onSurface, FontWeight.Bold) + Spacer(GlanceModifier.width(6.dp)) + Column(modifier = GlanceModifier.padding(bottom = 4.dp)) { + Line(labels.countries, 12.sp, GlanceTheme.colors.onSurface, FontWeight.Bold) + // 195 countries make the world, as on the Atlas page. + if (size.isWide) Line("${((atlas?.count ?: 0) * 100 / 195)}% ${labels.world}", 11.sp, GlanceTheme.colors.onSurfaceVariant) + } + } + } + if (size.isWide && !size.isTall) { + // Wide: the count beside the map, which gets the height. + Row(modifier = GlanceModifier.fillMaxWidth().defaultWeight(), verticalAlignment = Alignment.CenterVertically) { + count() + Spacer(GlanceModifier.width(10.dp)) + WorldMap(codes, GlanceModifier.defaultWeight().fillMaxHeight()) + } + } else { + count() + Spacer(GlanceModifier.height(6.dp)) + WorldMap(codes, GlanceModifier.fillMaxWidth().defaultWeight()) + } + if (size.isTall && atlas != null) { + Spacer(GlanceModifier.height(10.dp)) + Row(modifier = GlanceModifier.fillMaxWidth()) { + atlas.recent.take(4).forEach { country -> + Column(modifier = GlanceModifier.defaultWeight(), horizontalAlignment = Alignment.CenterHorizontally) { + Text(flag(country.code), style = TextStyle(fontSize = 20.sp, textAlign = TextAlign.Center)) + Line(country.name, 10.sp, GlanceTheme.colors.onSurfaceVariant) + } + } + } + } + } + } + } + + @Composable + private fun WorldMap(codes: Set, modifier: GlanceModifier) { + Box(modifier = modifier) { + Image( + provider = ImageProvider(WidgetArt.worldDots(codes, visited = false)), + contentDescription = null, + colorFilter = ColorFilter.tint(GlanceTheme.colors.outline), + contentScale = ContentScale.Fit, + modifier = GlanceModifier.fillMaxSize(), + ) + Image( + provider = ImageProvider(WidgetArt.worldDots(codes, visited = true)), + contentDescription = null, + colorFilter = ColorFilter.tint(GlanceTheme.colors.primary), + contentScale = ContentScale.Fit, + modifier = GlanceModifier.fillMaxSize(), + ) + } + } + + /** The flag emoji of an ISO 3166-1 alpha-2 code. */ + private fun flag(code: String): String { + if (code.length != 2) return "" + val first = Character.toChars(0x1F1E6 + (code[0].uppercaseChar() - 'A')) + val second = Character.toChars(0x1F1E6 + (code[1].uppercaseChar() - 'A')) + return String(first) + String(second) + } +} + +// ---- Travel group ---- + +/** Who comes along, the latest messages and the open poll. */ +class CollabWidget : TrekWidget() { + @Composable + override fun Content(snapshot: WidgetSnapshot?) { + val context = LocalContext.current + val size = LocalSize.current + val labels = snapshot?.labels ?: return EmptyWidget(WidgetSamples.emptyText(context)) + val collab = snapshot.collab + WidgetFrame(onClick = openPath(context, collab?.path ?: snapshot.trip?.path ?: "/")) { + Column(modifier = GlanceModifier.fillMaxSize()) { + Row(modifier = GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Rounded.Group, GlanceTheme.colors.primary, 14.dp) + Spacer(GlanceModifier.width(5.dp)) + if (size.isWide) Eyebrow(labels.group, GlanceTheme.colors.primary, GlanceModifier.defaultWeight()) else Spacer(GlanceModifier.defaultWeight()) + collab?.members?.take(if (size.isWide) 4 else 3)?.forEach { member -> + Spacer(GlanceModifier.width(2.dp)) + Initials(member.initials, 22.dp) + } + } + Spacer(GlanceModifier.height(8.dp)) + val messages = collab?.messages.orEmpty() + if (messages.isEmpty() && collab?.poll == null) { + Spacer(GlanceModifier.defaultWeight()) + Line(labels.noMessages, 14.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Medium, maxLines = 2) + Spacer(GlanceModifier.defaultWeight()) + return@Column + } + messages.takeLast(if (size.isTall) (if (collab?.poll != null) 2 else 4) else 1).forEach { message -> + Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 3.dp), verticalAlignment = Alignment.Top) { + if (!message.mine) { + Initials(message.initials, 24.dp) + Spacer(GlanceModifier.width(6.dp)) + } else { + Spacer(GlanceModifier.defaultWeight()) + } + Column( + modifier = GlanceModifier + .background(if (message.mine) GlanceTheme.colors.primary else GlanceTheme.colors.surfaceVariant) + .cornerRadius(14.dp).padding(horizontal = 10.dp, vertical = 6.dp), + ) { + if (!message.mine && size.isWide) Line(message.author, 10.sp, GlanceTheme.colors.onSurfaceVariant, FontWeight.Bold) + Line( + message.text, + 12.sp, + if (message.mine) GlanceTheme.colors.onPrimary else GlanceTheme.colors.onSurface, + maxLines = if (size.isWide) 2 else 3, + ) + } + } + } + val poll = collab?.poll + if (size.isTall && poll != null) { + Spacer(GlanceModifier.defaultWeight()) + Column(modifier = GlanceModifier.fillMaxWidth().background(GlanceTheme.colors.secondaryContainer).cornerRadius(14.dp).padding(10.dp)) { + Eyebrow("${labels.poll}: ${poll.voters} ${labels.votes}", GlanceTheme.colors.onSecondaryContainer) + Line(poll.question, 13.sp, GlanceTheme.colors.onSecondaryContainer, FontWeight.Bold) + Spacer(GlanceModifier.height(4.dp)) + val most = poll.options.maxOfOrNull { it.votes }?.coerceAtLeast(1) ?: 1 + poll.options.take(3).forEach { option -> + Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) { + Line(option.label, 12.sp, GlanceTheme.colors.onSecondaryContainer, modifier = GlanceModifier.width(70.dp)) + Bar(option.votes.toFloat() / most, GlanceTheme.colors.primary, GlanceTheme.colors.surface, 5.dp, GlanceModifier.defaultWeight()) + Spacer(GlanceModifier.width(6.dp)) + Line(option.votes.toString(), 11.sp, GlanceTheme.colors.onSecondaryContainer, FontWeight.Bold) + } + } + } + } + } + } + } + + @Composable + private fun Initials(text: String, size: androidx.compose.ui.unit.Dp) { + Box( + modifier = GlanceModifier.size(size).cornerRadius(size / 2).background(GlanceTheme.colors.tertiaryContainer), + contentAlignment = Alignment.Center, + ) { + Text(text, style = TextStyle(color = GlanceTheme.colors.onTertiaryContainer, fontSize = 9.sp, fontWeight = FontWeight.Bold), maxLines = 1) + } + } +} + +/** A widget with nothing to show yet: TREK's mark and what to do. */ +@Composable +fun EmptyWidget(text: String) { + val context = LocalContext.current + WidgetFrame(onClick = openPath(context, "/")) { + Column(modifier = GlanceModifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = GlanceModifier.size(34.dp).cornerRadius(11.dp).background(GlanceTheme.colors.primary), + contentAlignment = Alignment.Center, + ) { + Text("T", style = TextStyle(color = GlanceTheme.colors.onPrimary, fontSize = 18.sp, fontWeight = FontWeight.Bold)) + } + Spacer(GlanceModifier.height(10.dp)) + Line(text, 13.sp, GlanceTheme.colors.onSurface, FontWeight.Medium, maxLines = 4) + } + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetArt.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetArt.kt new file mode 100644 index 000000000..da005b067 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetArt.kt @@ -0,0 +1,248 @@ +package com.liketrek.trek.widget + +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.LinearGradient +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RadialGradient +import android.graphics.Shader +import android.util.Base64 +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.min +import kotlin.math.sin + +/** + * The pictures a widget shows that RemoteViews cannot draw: the trip's cover, + * its own sky when it has none, and the world map's dots. Drawn once per + * update into bitmaps, kept small (a widget's RemoteViews have a size budget). + */ +object WidgetArt { + /** A stable number for a text (FNV-1a), the same as TrekStyle.swift's seed. */ + fun seed(text: String): Long { + var hash = 1469598103934665603L + for (byte in text.toByteArray(Charsets.UTF_8)) { + hash = (hash xor (byte.toLong() and 0xff)) * 1099511628211L + } + return hash + } + + /** The trip's two colours, from its title: the same trip always gets the same sky. */ + fun tripHues(title: String): Pair { + val base = (java.lang.Long.remainderUnsigned(seed(title), 360)).toFloat() + val first = Color.HSVToColor(floatArrayOf(base, 0.62f, 0.78f)) + val second = Color.HSVToColor(floatArrayOf((base + 40f) % 360f, 0.7f, 0.42f)) + return first to second + } + + /** The cover the app sent, base64 JPEG, decoded down to at most [maxSide] pixels. */ + fun cover(base64: String?, maxSide: Int = 720): Bitmap? { + if (base64.isNullOrBlank()) return null + return try { + val bytes = Base64.decode(base64, Base64.DEFAULT) + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + var sample = 1 + while (bounds.outWidth / (sample * 2) >= maxSide || bounds.outHeight / (sample * 2) >= maxSide) sample *= 2 + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample }) + } catch (e: IllegalArgumentException) { + null + } + } + + /** A trip without a cover: its two colours as a sky, with contour lines over it. */ + fun sky(title: String, width: Int = 480, height: Int = 480): Bitmap { + val (first, second) = tripHues(title) + val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) + val canvas = Canvas(bitmap) + val paint = Paint(Paint.ANTI_ALIAS_FLAG) + paint.shader = LinearGradient(0f, 0f, width.toFloat(), height.toFloat(), first, second, Shader.TileMode.CLAMP) + canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint) + paint.shader = RadialGradient(width * 0.85f, height * 0.05f, width * 0.6f, Color.argb(70, 255, 255, 255), Color.TRANSPARENT, Shader.TileMode.CLAMP) + canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint) + paint.shader = null + drawContours(canvas, width, height, java.lang.Long.remainderUnsigned(seed(title), 997).toInt(), Color.argb(36, 255, 255, 255)) + return bitmap + } + + /** Concentric wobbly rings, the topographic lines that stand for travel in TREK. */ + private fun drawContours(canvas: Canvas, width: Int, height: Int, seed: Int, color: Int) { + val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeWidth = 2f + this.color = color + } + val cx = width * (0.25f + (seed % 50) / 100f) + val cy = height * (0.35f + (seed % 30) / 100f) + val maxR = min(width, height) * 1.1f + val rings = 11 + for (ring in 1..rings) { + val r = maxR * ring / rings + val path = Path() + val steps = 72 + for (i in 0..steps) { + val a = 2 * PI * i / steps + val wobble = 1 + 0.08 * sin(a * 3 + seed + ring) + 0.05 * cos(a * 5 + seed * 0.7) + val x = cx + (r * wobble * cos(a)).toFloat() + val y = cy + (r * wobble * sin(a) * 0.8).toFloat() + if (i == 0) path.moveTo(x, y) else path.lineTo(x, y) + } + canvas.drawPath(path, paint) + } + } + + /** + * The world map as dots, white so the widget tints it: [visited] true draws + * only the countries in [codes], false only the others. + */ + fun worldDots(codes: Set, visited: Boolean, dot: Int = 8): Bitmap { + val rows = WorldGrid.ROWS.size + val bitmap = Bitmap.createBitmap(WorldGrid.COLUMNS * dot, rows * dot, Bitmap.Config.ARGB_8888) + val canvas = Canvas(bitmap) + val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = Color.WHITE } + val radius = dot * 0.36f + for (row in 0 until rows) { + for (column in 0 until WorldGrid.COLUMNS) { + val code = WorldGrid.code(row, column) ?: continue + if ((code in codes) != visited) continue + canvas.drawCircle(column * dot + dot / 2f, row * dot + dot / 2f, radius, paint) + } + } + return bitmap + } + + /** A ring of [progress] (0..1), white on a faint track, for the countdown and the packing. */ + fun ring(progress: Float, sizePx: Int = 160, stroke: Float = 14f, track: Int = Color.argb(60, 255, 255, 255)): Bitmap { + val bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888) + val canvas = Canvas(bitmap) + val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeWidth = stroke + strokeCap = Paint.Cap.ROUND + } + val inset = stroke / 2 + 1 + val oval = android.graphics.RectF(inset, inset, sizePx - inset, sizePx - inset) + paint.color = track + canvas.drawArc(oval, 0f, 360f, false, paint) + paint.color = Color.WHITE + val sweep = 360f * progress.coerceIn(0f, 1f) + if (sweep > 0) canvas.drawArc(oval, -90f, sweep, false, paint) + return bitmap + } + + /** A trip's days as segments, filled up to [index]: white, the widget tints it. Track at a third. */ + fun segments(index: Int, total: Int, width: Int = 600, height: Int = 10): Bitmap { + val count = total.coerceIn(1, 31) + val filled = if (total > 31) (index * 31f / total).toInt().coerceAtLeast(1) else index + val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) + val canvas = Canvas(bitmap) + val paint = Paint(Paint.ANTI_ALIAS_FLAG) + val gap = if (count > 14) 4f else 8f + val w = (width - gap * (count - 1)) / count + for (i in 0 until count) { + paint.color = if (i < filled) Color.WHITE else Color.argb(85, 255, 255, 255) + val left = i * (w + gap) + canvas.drawRoundRect(android.graphics.RectF(left, 0f, left + w, height.toFloat()), height / 2f, height / 2f, paint) + } + return bitmap + } + + /** + * A flight's route as an arc: dashed ahead, solid where it has flown, a dot + * at either airport and an airliner riding the curve at its heading. White + * on a translucent track, like the ring; the widget tints nothing, so the + * caller passes the flight colour. + */ + fun flightArc( + progress: Float, + color: Int, + track: Int, + width: Int = 600, + height: Int = 120, + showPlane: Boolean = true, + rtl: Boolean = false, + ): Bitmap { + val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) + val canvas = Canvas(bitmap) + // Right to left the origin stands on the right: the whole drawing is mirrored. + if (rtl) canvas.scale(-1f, 1f, width / 2f, height / 2f) + val p = progress.coerceIn(0f, 1f) + val inset = height * 0.14f + val sx = inset + val sy = height - inset + val ex = width - inset + val ey = height - inset + val cx = width / 2f + val cy = -height * 0.45f + val path = android.graphics.Path().apply { + moveTo(sx, sy) + quadTo(cx, cy, ex, ey) + } + val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeCap = Paint.Cap.ROUND + strokeWidth = height * 0.035f + this.color = track + pathEffect = android.graphics.DashPathEffect(floatArrayOf(height * 0.02f, height * 0.07f), 0f) + } + canvas.drawPath(path, line) + val measure = android.graphics.PathMeasure(path, false) + if (p > 0f) { + val flown = android.graphics.Path() + measure.getSegment(0f, measure.length * p, flown, true) + line.pathEffect = null + line.strokeWidth = height * 0.045f + line.color = color + canvas.drawPath(flown, line) + } + val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color } + canvas.drawCircle(sx, sy, height * 0.05f, dot) + val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = if (p >= 1f) Paint.Style.FILL else Paint.Style.STROKE + strokeWidth = height * 0.03f + this.color = color + } + canvas.drawCircle(ex, ey, height * 0.06f, ring) + if (showPlane) { + val pos = FloatArray(2) + val tan = FloatArray(2) + measure.getPosTan(measure.length * p, pos, tan) + canvas.save() + canvas.translate(pos[0], pos[1]) + canvas.rotate(Math.toDegrees(kotlin.math.atan2(tan[1].toDouble(), tan[0].toDouble())).toFloat()) + val scale = height * 0.012f + canvas.scale(scale, scale) + canvas.drawCircle(0f, 0f, 13f, Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = Color.WHITE }) + canvas.drawPath(airliner(), Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color }) + canvas.restore() + } + return bitmap + } + + /** An airliner seen from above, nose along +x, about 18 units long, centred. */ + private fun airliner(): android.graphics.Path = android.graphics.Path().apply { + moveTo(9f, 0f) + cubicTo(9f, -0.9f, 8.3f, -1.3f, 7.4f, -1.3f) + lineTo(3.2f, -1.3f) + lineTo(-1.6f, -7.6f) + lineTo(-3.7f, -7.6f) + lineTo(-1.4f, -1.3f) + lineTo(-5.5f, -1.3f) + lineTo(-7.2f, -3.7f) + lineTo(-8.8f, -3.7f) + lineTo(-7.8f, 0f) + lineTo(-8.8f, 3.7f) + lineTo(-7.2f, 3.7f) + lineTo(-5.5f, 1.3f) + lineTo(-1.4f, 1.3f) + lineTo(-3.7f, 7.6f) + lineTo(-1.6f, 7.6f) + lineTo(3.2f, 1.3f) + lineTo(7.4f, 1.3f) + cubicTo(8.3f, 1.3f, 9f, 0.9f, 9f, 0f) + close() + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetConfigActivity.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetConfigActivity.kt new file mode 100644 index 000000000..6b2a4d3c5 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetConfigActivity.kt @@ -0,0 +1,176 @@ +package com.liketrek.trek.widget + +import android.appwidget.AppWidgetManager +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.AutoAwesome +import androidx.compose.material.icons.rounded.Luggage +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.LargeTopAppBar +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.material3.rememberTopAppBarState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.glance.appwidget.GlanceAppWidgetManager +import androidx.lifecycle.lifecycleScope +import com.liketrek.trek.R +import com.liketrek.trek.ui.TrekMaterialTheme +import kotlinx.coroutines.launch + +/** + * "Choose trip" for a placed widget, the counterpart of the iOS widget's Edit + * Widget (TripIntent.swift): Automatic follows the dashboard's trip, or one of + * the trips the app listed (key "trips"). Shown when the widget is placed + * (optional, it starts on Automatic) and again from the widget's long press. + */ +class WidgetConfigActivity : ComponentActivity() { + private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID + + override fun onCreate(savedInstanceState: Bundle?) { + enableEdgeToEdge() + super.onCreate(savedInstanceState) + appWidgetId = intent?.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) + ?: AppWidgetManager.INVALID_APPWIDGET_ID + if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { + finish() + return + } + // Backing out keeps the widget on what it had (Automatic for a new one). + setResult(RESULT_OK, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)) + val trips = WidgetStore.trips(this) + val current = WidgetStore.tripFor(this, appWidgetId) + setContent { + TrekMaterialTheme { + TripPicker(trips, current, onPick = ::pick) + } + } + } + + private fun pick(tripId: String) { + WidgetStore.setTripFor(this, appWidgetId, tripId) + lifecycleScope.launch { + val manager = GlanceAppWidgetManager(this@WidgetConfigActivity) + val glanceId = runCatching { manager.getGlanceIdBy(appWidgetId) }.getOrNull() + // Only the widget this id belongs to: Glance keys a session by the id alone, + // so another class updating it would draw its own layout there. + val widget = TrekWidgetUpdater.widgetFor(this@WidgetConfigActivity, appWidgetId) + if (glanceId != null && widget != null) runCatching { widget.update(this@WidgetConfigActivity, glanceId) } + setResult(RESULT_OK, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)) + finish() + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun TripPicker(trips: List, current: String, onPick: (String) -> Unit) { + var selected by remember { mutableStateOf(current) } + val scroll = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(rememberTopAppBarState()) + Scaffold( + modifier = Modifier.fillMaxSize().nestedScroll(scroll.nestedScrollConnection), + topBar = { + LargeTopAppBar( + title = { Text(stringResource(R.string.widget_intent_title)) }, + scrollBehavior = scroll, + ) + }, + ) { padding -> + LazyColumn( + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = padding.calculateTopPadding(), bottom = padding.calculateBottomPadding() + 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + item { + Text( + stringResource(R.string.widget_intent_description), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 4.dp, bottom = 8.dp), + ) + } + item { + PickRow( + title = stringResource(R.string.widget_intent_auto), + subtitle = stringResource(R.string.widget_intent_auto_hint), + leading = { Icon(Icons.Rounded.AutoAwesome, null, tint = MaterialTheme.colorScheme.primary) }, + checked = selected == WidgetStore.AUTO, + ) { + selected = WidgetStore.AUTO + onPick(WidgetStore.AUTO) + } + } + items(trips, key = { it.id }) { trip -> + PickRow( + title = trip.title, + subtitle = RelativeDayRange(trip), + leading = { Icon(Icons.Rounded.Luggage, null, tint = MaterialTheme.colorScheme.secondary) }, + checked = selected == trip.id.toString(), + ) { + selected = trip.id.toString() + onPick(trip.id.toString()) + } + } + } + } +} + +@Composable +private fun RelativeDayRange(trip: TripRef): String? { + val context = androidx.compose.ui.platform.LocalContext.current + return RelativeDay.range(context, trip.start, trip.end) +} + +@Composable +private fun PickRow(title: String, subtitle: String?, leading: @Composable () -> Unit, checked: Boolean, onClick: () -> Unit) { + Surface( + shape = RoundedCornerShape(20.dp), + color = if (checked) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceContainerLow, + modifier = Modifier.fillMaxWidth().clickable(onClick = onClick), + ) { + Row(modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically) { + Surface(shape = RoundedCornerShape(12.dp), color = MaterialTheme.colorScheme.surface, modifier = Modifier.size(40.dp)) { + Row(horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) { leading() } + } + Spacer(Modifier.width(14.dp)) + Column(modifier = Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) + if (subtitle != null) { + Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1) + } + } + RadioButton(selected = checked, onClick = onClick) + } + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetSamples.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetSamples.kt new file mode 100644 index 000000000..60c5f8bb6 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetSamples.kt @@ -0,0 +1,103 @@ +package com.liketrek.trek.widget + +import android.content.Context +import com.liketrek.trek.R +import java.time.LocalDate +import org.json.JSONObject + +/** + * The sample trip the widget picker shows before the app ever wrote a snapshot, + * and what the screenshot tests draw: the same trip to Kyoto as the iOS gallery + * (WidgetSnapshot.sample in TrekFamily.swift). + */ +object WidgetSamples { + /** In the air on a running trip, two days ahead before one: the same LH 716 as the iOS sample. */ + private fun flightJson(running: Boolean): String { + val now = System.currentTimeMillis() / 1000 + val dep = if (running) now - 4 * 3600 else now + 2 * 86_400 + 5 * 3600 + val live = if (running) { + """"depActual": ${dep + 18 * 60}, "arrExpected": ${dep + 12 * 3600 + 41 * 60}, "arrTimeExpected": "08:46", "delay": 16, "aircraft": "A359 D-AIXA",""" + } else { + "" + } + return """{"number": "LH 716", "from": "FRA", "to": "HND", "fromCity": "Frankfurt", "toCity": "Tokyo Haneda", + "dep": $dep, "arr": ${dep + 12 * 3600 + 25 * 60}, $live "depTime": "13:05", "arrTime": "08:30", "path": "/trips/1?booking=1"}""" + } + + fun emptyText(context: Context): String = context.getString(R.string.widget_empty) + + fun snapshot(running: Boolean, now: LocalDate = LocalDate.now()): WidgetSnapshot = WidgetSnapshot.fromJson(JSONObject(json(running, now))) + + fun json(running: Boolean, now: LocalDate = LocalDate.now()): String { + fun iso(offset: Long) = now.plusDays(offset).toString() + val start = if (running) -2L else 12L + val today = if (running) { + """ + "today": {"dayLabel": "Day 3 of 9", "index": 3, "total": 9, "stops": [ + {"time": "08:30", "name": "Fushimi Inari Taisha", "minutes": 510, "color": "#D6273B", "symbol": "building.columns.fill"}, + {"time": "11:00", "name": "Nishiki Market", "minutes": 660, "color": "#E8A13A", "symbol": "storefront.fill"}, + {"time": "13:30", "name": "Kiyomizu-dera", "minutes": 810, "color": "#2FA37A", "symbol": "leaf.fill"}, + {"time": "16:00", "name": "Gion walk", "minutes": 960, "color": "#4A7DDB", "symbol": "figure.walk"}, + {"time": "19:30", "name": "Dinner at Pontocho", "minutes": 1170, "color": "#8E6CD9", "symbol": "fork.knife"} + ]}, + """ + } else { + "" + } + return """ + { + "trip": {"title": "Autumn in Kyoto", "start": "${iso(start)}", "end": "${iso(start + 8)}", "path": "/trips/1", + "place": "Kyoto, Japan", "dayCount": 9, "placeCount": 34, "memberCount": 3}, + $today + "weather": {"temp": 18, "high": 21, "low": 11, "main": "${if (running) "Clear" else "Clouds"}", "label": "Mostly sunny", "place": "Kyoto", "rain": 10}, + "flight": ${flightJson(running)}, + "bookings": [ + {"title": "LH 716", "kind": "flight", "date": "${iso(if (running) 6 else 12)}", "time": "13:05", "detail": "FRA → HND", "confirmed": true, "path": "/trips/1"}, + {"title": "Shinkansen Nozomi 21", "kind": "train", "date": "${iso(if (running) 0 else 13)}", "time": "09:12", "detail": "Tokyo → Kyoto", "confirmed": true, "path": "/trips/1"}, + {"title": "Hotel Kanra Kyoto", "kind": "hotel", "date": "${iso(if (running) 0 else 13)}", "time": "15:00", "detail": "6 nights", "confirmed": true, "path": "/trips/1"}, + {"title": "Kaiseki at Kikunoi", "kind": "restaurant", "date": "${iso(if (running) 1 else 15)}", "time": "19:00", "detail": "Higashiyama", "confirmed": false, "path": "/trips/1"}, + {"title": "Tea ceremony", "kind": "event", "date": "${iso(if (running) 2 else 16)}", "time": "10:30", "detail": "Camellia Flower", "confirmed": true, "path": "/trips/1"} + ], + "todos": {"open": 4, "total": 11, "path": "/trips/1/todos", "items": [ + {"name": "Order JR Pass", "due": "${iso(if (running) 0 else 3)}", "priority": 3}, + {"name": "Book Ghibli Museum tickets", "due": "${iso(if (running) 1 else 5)}", "priority": 2}, + {"name": "Get yen in cash", "priority": 1}, + {"name": "Download offline maps", "priority": 0} + ]}, + "packing": {"packed": 23, "total": 31, "path": "/trips/1/packing", + "bags": [ + {"name": "Suitcase", "color": "#4A7DDB", "grams": 14200, "limit": 23000, "packed": 15, "total": 19}, + {"name": "Daypack", "color": "#2FA37A", "grams": 4100, "limit": 8000, "packed": 8, "total": 12} + ], + "missing": [ + {"name": "Rain jacket", "category": "Clothes", "color": "#4A7DDB"}, + {"name": "Power bank", "category": "Tech", "color": "#2FA37A"}, + {"name": "Passport", "category": "Documents", "color": "#2FA37A"}, + {"name": "Sandals", "category": "Shoes", "color": "#4A7DDB"} + ]}, + "atlas": {"count": 23, "trips": 41, "days": 318, + "codes": ["DE","AT","CH","FR","IT","ES","PT","NL","BE","DK","NO","SE","GB","IE","GR","HR","JP","TH","VN","US","CA","MA","AU"], + "recent": [{"code": "JP", "name": "Japan"}, {"code": "NO", "name": "Norway"}, {"code": "PT", "name": "Portugal"}, {"code": "MA", "name": "Morocco"}], + "continents": [{"name": "Europe", "count": 16}, {"name": "Asia", "count": 3}, {"name": "North America", "count": 2}, {"name": "Africa", "count": 1}, {"name": "Oceania", "count": 1}]}, + "collab": {"path": "/trips/1?tab=collab", + "members": [{"name": "Maurice", "initials": "MA"}, {"name": "Julien", "initials": "JU"}, {"name": "Elmo", "initials": "EL"}, {"name": "Sara", "initials": "SA"}], + "messages": [ + {"author": "Julien", "initials": "JU", "text": "Got the JR Pass vouchers, all four of us", "mine": false}, + {"author": "Sara", "initials": "SA", "text": "Can we push dinner to 20:00? Train is late", "mine": false}, + {"author": "Maurice", "initials": "MA", "text": "Sure, I moved the table at Pontocho", "mine": true} + ], + "poll": {"question": "Day trip on Saturday?", "voters": 4, "options": [{"label": "Nara", "votes": 3}, {"label": "Uji", "votes": 1}, {"label": "Kurama", "votes": 0}]}}, + "labels": { + "nextTrip": "Next trip", "today": "Today", "noTrip": "No trip coming up. Plan the next one in TREK.", + "inDays": "in {n} days", "tomorrow": "Tomorrow", "nothingPlanned": "Nothing planned today", + "days": "days", "bookings": "Coming up", "noBookings": "No bookings ahead", + "todos": "To-dos", "noTodos": "All done", "packing": "Packing", "packed": "packed", + "confirmed": "Confirmed", "pending": "Pending", "todayShort": "Today", "tomorrowShort": "Tomorrow", + "now": "Now", "places": "places", "travellers": "travellers", "allDone": "Day done", + "missing": "still to pack", "countries": "countries", "world": "of the world", "group": "Travel group", + "poll": "Poll", "votes": "votes", "noMessages": "No messages yet", "departure": "Departure" + } + } + """.trimIndent() + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetSnapshot.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetSnapshot.kt new file mode 100644 index 000000000..3f23623a7 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetSnapshot.kt @@ -0,0 +1,363 @@ +package com.liketrek.trek.widget + +import java.time.LocalDate +import java.time.format.DateTimeParseException +import java.time.temporal.ChronoUnit +import org.json.JSONArray +import org.json.JSONObject + +/** + * What the app last told the widgets: client/src/native/widgets.ts builds it and + * hands it over through TrekShell.setWidgetSnapshot, the same JSON the iOS + * widgets read (client/ios/App/TREKWidgets/WidgetSnapshot.swift). Texts arrive + * already translated, so a widget always speaks the language the app does. + * + * Everything past trip, today and labels is optional: a binary newer than the + * server's UI shows what it gets, and unknown fields are ignored. + */ +data class WidgetSnapshot( + val trip: Trip?, + val today: Today?, + val weather: Weather?, + val bookings: List, + val todos: Todos?, + val packing: Packing?, + val atlas: Atlas?, + val collab: Collab?, + val labels: Labels, + /** The trip's next flight or the one in the air; last and defaulted, so older callers keep compiling. */ + val flight: Flight? = null, +) { + data class Trip( + val title: String, + val start: String, + val end: String, + val path: String, + val place: String?, + /** A small JPEG of the cover, base64. */ + val cover: String?, + val dayCount: Int?, + val placeCount: Int?, + val memberCount: Int?, + ) + + data class Stop( + val time: String?, + val name: String, + /** Minutes after midnight. */ + val minutes: Int?, + /** #rrggbb */ + val color: String?, + /** The SF Symbol name the iOS widget uses; [TrekIcons] maps it. */ + val symbol: String?, + ) + + data class Today(val dayLabel: String, val stops: List, val index: Int?, val total: Int?) + + data class Weather( + val temp: Int, + val high: Int?, + val low: Int?, + val main: String, + val label: String, + val place: String?, + val rain: Int?, + ) + + data class Booking( + val title: String, + val kind: String, + val date: String?, + val time: String?, + val detail: String?, + val confirmed: Boolean, + val path: String, + ) + + data class Todo(val name: String, val due: String?, val priority: Int) + + data class Todos(val open: Int, val total: Int, val items: List, val path: String) + + data class Bag(val name: String, val color: String, val grams: Int, val limit: Int?, val packed: Int, val total: Int) + + data class PackItem(val name: String, val category: String?, val color: String?) + + data class Packing(val packed: Int, val total: Int, val path: String, val bags: List, val missing: List) + + data class Country(val code: String, val name: String) + + data class Continent(val name: String, val count: Int) + + data class Atlas( + val count: Int, + val codes: List, + val recent: List, + val continents: List, + val trips: Int?, + val days: Int?, + ) + + data class Member(val name: String, val initials: String) + + data class Message(val author: String, val initials: String, val text: String, val at: String?, val mine: Boolean) + + data class PollOption(val label: String, val votes: Int) + + data class Poll(val question: String, val options: List, val voters: Int) + + data class Collab(val members: List, val messages: List, val poll: Poll?, val path: String) + + /** + * The flight widget's flight. Times are epoch seconds, so the widget moves on + * with the clock between two snapshots; the clock times at either airport + * come formatted, since the widget has no zone data. + */ + data class Flight( + val number: String, + val from: String, + val to: String, + val fromCity: String?, + val toCity: String?, + val dep: Long, + val arr: Long, + /** Observed take-off. */ + val depActual: Long?, + /** Before take-off: the planned departure plus the delay seen so far. */ + val depExpected: Long?, + /** The feed saw the aircraft in the air when the app last looked. */ + val airborne: Boolean, + /** Touchdown once landed, else the estimate while in the air. */ + val arrExpected: Long?, + val landed: Boolean, + val depTime: String, + val arrTime: String, + val arrTimeExpected: String?, + /** Minutes late against the schedule, negative when early. */ + val delay: Int?, + val aircraft: String?, + /** When the feed last heard the aircraft; null for a flight it never heard of. */ + val seen: Long?, + val path: String, + ) + + /** The labels, translated by the app. The optional ones fall back to English. */ + data class Labels(private val raw: JSONObject) { + val nextTrip get() = text("nextTrip", "Next trip") + val today get() = text("today", "Today") + val noTrip get() = text("noTrip", "No trip coming up. Plan the next one in TREK.") + val inDays get() = text("inDays", "in {n} days") + val tomorrow get() = text("tomorrow", "Tomorrow") + val nothingPlanned get() = text("nothingPlanned", "Nothing planned today") + val days get() = text("days", "days") + val bookings get() = text("bookings", "Coming up") + val noBookings get() = text("noBookings", "No bookings ahead") + val todos get() = text("todos", "To-dos") + val noTodos get() = text("noTodos", "All done") + val packing get() = text("packing", "Packing") + val packed get() = text("packed", "packed") + val confirmed get() = text("confirmed", "Confirmed") + val pending get() = text("pending", "Pending") + val todayShort get() = text("todayShort", today) + val tomorrowShort get() = text("tomorrowShort", tomorrow) + val now get() = text("now", "Now") + val places get() = text("places", "places") + val travellers get() = text("travellers", "travellers") + val allDone get() = text("allDone", "Day done") + val openTrek get() = text("openTrek", "Open TREK") + val missing get() = text("missing", "still to pack") + val countries get() = text("countries", "countries") + val world get() = text("world", "of the world") + val group get() = text("group", "Travel group") + val poll get() = text("poll", "Poll") + val votes get() = text("votes", "votes") + val noMessages get() = text("noMessages", "No messages yet") + val departure get() = text("departure", "Departure") + val flight get() = text("flight", "Flight") + /** Contains "{time}". */ + val flightDeparts get() = text("flightDeparts", "Departs in {time}") + /** Contains "{time}". */ + val flightLands get() = text("flightLands", "Lands in {time}") + val flightLanded get() = text("flightLanded", "Landed") + val flightReady get() = text("flightReady", "Ready for departure") + val noFlight get() = text("noFlight", "No flight ahead") + val flightOnTime get() = text("flightOnTime", "On time") + /** Contains "{m}". */ + val flightLate get() = text("flightLate", "+{m} min") + /** Contains "{m}". */ + val flightEarly get() = text("flightEarly", "{m} min early") + /** Contain "{d}" and "{h}", "{h}" and "{m}", and "{m}". */ + val durDaysHours get() = text("durDaysHours", "{d} d {h} h") + val durHoursMinutes get() = text("durHoursMinutes", "{h} h {m} min") + val durMinutes get() = text("durMinutes", "{m} min") + + private fun text(key: String, fallback: String): String = raw.optString(key).ifBlank { fallback } + } + + /** Whole days from [now] to the trip's start. */ + fun daysUntilStart(now: LocalDate = LocalDate.now()): Long? = trip?.let { day(it.start) }?.let { ChronoUnit.DAYS.between(now, it) } + + /** The trip's length in days, from its dates when the app sent no count. */ + val tripLength: Int? + get() { + trip?.dayCount?.takeIf { it > 0 }?.let { return it } + val start = trip?.let { day(it.start) } ?: return null + val end = day(trip.end) ?: return null + return ChronoUnit.DAYS.between(start, end).toInt() + 1 + } + + companion object { + fun parse(json: String): WidgetSnapshot? = try { + fromJson(JSONObject(json)) + } catch (e: Exception) { + null + } + + fun fromJson(o: JSONObject): WidgetSnapshot = WidgetSnapshot( + trip = o.optJSONObject("trip")?.let { + Trip( + title = it.optString("title"), + start = it.optString("start"), + end = it.optString("end"), + path = it.optString("path", "/"), + place = it.str("place"), + cover = it.str("cover"), + dayCount = it.int("dayCount"), + placeCount = it.int("placeCount"), + memberCount = it.int("memberCount"), + ) + }, + today = o.optJSONObject("today")?.let { t -> + Today( + dayLabel = t.optString("dayLabel"), + stops = t.optJSONArray("stops").objects().map { + Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol")) + }, + index = t.int("index"), + total = t.int("total"), + ) + }, + weather = o.optJSONObject("weather")?.let { + Weather(it.optInt("temp"), it.int("high"), it.int("low"), it.optString("main"), it.optString("label"), it.str("place"), it.int("rain")) + }, + bookings = o.optJSONArray("bookings").objects().map { + Booking( + title = it.optString("title"), + kind = it.optString("kind", "other"), + date = it.str("date"), + time = it.str("time"), + detail = it.str("detail"), + confirmed = it.optBoolean("confirmed"), + path = it.optString("path", "/"), + ) + }, + todos = o.optJSONObject("todos")?.let { t -> + Todos( + open = t.optInt("open"), + total = t.optInt("total"), + items = t.optJSONArray("items").objects().map { Todo(it.optString("name"), it.str("due"), it.optInt("priority")) }, + path = t.optString("path", "/"), + ) + }, + packing = o.optJSONObject("packing")?.let { p -> + Packing( + packed = p.optInt("packed"), + total = p.optInt("total"), + path = p.optString("path", "/"), + bags = p.optJSONArray("bags").objects().map { + Bag(it.optString("name"), it.optString("color", "#4A7DDB"), it.optInt("grams"), it.int("limit"), it.optInt("packed"), it.optInt("total")) + }, + missing = p.optJSONArray("missing").objects().map { PackItem(it.optString("name"), it.str("category"), it.str("color")) }, + ) + }, + atlas = o.optJSONObject("atlas")?.let { a -> + Atlas( + count = a.optInt("count"), + codes = a.optJSONArray("codes").strings(), + recent = a.optJSONArray("recent").objects().map { Country(it.optString("code"), it.optString("name")) }, + continents = a.optJSONArray("continents").objects().map { Continent(it.optString("name"), it.optInt("count")) }, + trips = a.int("trips"), + days = a.int("days"), + ) + }, + collab = o.optJSONObject("collab")?.let { c -> + Collab( + members = c.optJSONArray("members").objects().map { Member(it.optString("name"), it.optString("initials")) }, + messages = c.optJSONArray("messages").objects().map { + Message(it.optString("author"), it.optString("initials"), it.optString("text"), it.str("at"), it.optBoolean("mine")) + }, + poll = c.optJSONObject("poll")?.let { p -> + Poll(p.optString("question"), p.optJSONArray("options").objects().map { PollOption(it.optString("label"), it.optInt("votes")) }, p.optInt("voters")) + }, + path = c.optString("path", "/"), + ) + }, + labels = Labels(o.optJSONObject("labels") ?: JSONObject()), + flight = o.optJSONObject("flight")?.let { f -> + Flight( + number = f.optString("number"), + from = f.optString("from"), + to = f.optString("to"), + fromCity = f.str("fromCity"), + toCity = f.str("toCity"), + dep = f.optLong("dep"), + arr = f.optLong("arr"), + depActual = f.long("depActual"), + depExpected = f.long("depExpected"), + airborne = f.optBoolean("airborne"), + arrExpected = f.long("arrExpected"), + landed = f.optBoolean("landed"), + depTime = f.optString("depTime"), + arrTime = f.optString("arrTime"), + arrTimeExpected = f.str("arrTimeExpected"), + delay = f.int("delay"), + aircraft = f.str("aircraft"), + seen = f.long("seen"), + path = f.optString("path", "/"), + ) + }?.takeIf { it.dep > 0 && it.arr > 0 }, + ) + + fun day(iso: String?): LocalDate? { + if (iso.isNullOrBlank() || iso.length < 10) return null + return try { + LocalDate.parse(iso.substring(0, 10)) + } catch (e: DateTimeParseException) { + null + } + } + + /** The app link a tap opens: com.liketrek.trek://navigate, which the UI routes (nativeApp.ts). */ + fun link(path: String): String = "com.liketrek.trek://navigate" + if (path.startsWith("/")) path else "/$path" + + private fun JSONObject.str(key: String): String? = if (isNull(key)) null else optString(key).ifEmpty { null } + + private fun JSONObject.int(key: String): Int? = if (has(key) && !isNull(key)) optInt(key) else null + + private fun JSONObject.long(key: String): Long? = if (has(key) && !isNull(key)) optLong(key) else null + + private fun JSONArray?.objects(): List = + if (this == null) emptyList() else (0 until length()).mapNotNull { optJSONObject(it) } + + private fun JSONArray?.strings(): List = + if (this == null) emptyList() else (0 until length()).mapNotNull { optString(it).ifEmpty { null } } + } +} + +/** A trip a widget can be set to, as the app lists them (key "trips"). */ +data class TripRef(val id: Long, val title: String, val start: String, val end: String) { + companion object { + fun parseList(json: String?): List { + if (json.isNullOrBlank()) return emptyList() + return try { + val array = JSONArray(json) + (0 until array.length()).mapNotNull { i -> + val o = array.optJSONObject(i) ?: return@mapNotNull null + if (!o.has("id")) return@mapNotNull null + TripRef(o.optLong("id"), o.optString("title"), o.optString("start"), o.optString("end")) + } + } catch (e: Exception) { + emptyList() + } + } + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetStore.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetStore.kt new file mode 100644 index 000000000..519384d86 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetStore.kt @@ -0,0 +1,80 @@ +package com.liketrek.trek.widget + +import android.content.Context +import java.io.File +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +/** + * Where the widgets' snapshots live: one JSON file per key in the app's own + * storage. The widgets run in the app's process, so no shared container is + * needed as on iOS; the keys are the same ones the UI writes there + * ("snapshot", "trips", "trip."). + */ +object WidgetStore { + private val KEY = Regex("^(snapshot|trips|trip\\.[0-9]{1,12})$") + private const val PREFS = "trek.widgets" + const val AUTO = "auto" + + private val changes = MutableStateFlow(0L) + + /** + * Counts every write and every trip picked for a widget. A widget reads its + * data inside its composition, keyed on this, so a write that lands while its + * Glance session still runs is drawn too, not only the first one. + */ + val version: StateFlow = changes + + fun isValidKey(key: String): Boolean = KEY.matches(key) + + private fun dir(context: Context): File = File(context.filesDir, "widgets").apply { mkdirs() } + + fun write(context: Context, key: String, json: String) { + require(isValidKey(key)) { "key must be snapshot, trips or trip." } + val target = File(dir(context), "$key.json") + val temp = File(dir(context), "$key.json.tmp") + temp.writeText(json) + if (!temp.renameTo(target)) { + target.delete() + temp.renameTo(target) + } + changes.value++ + } + + fun read(context: Context, key: String): String? { + if (!isValidKey(key)) return null + val file = File(dir(context), "$key.json") + return if (file.exists()) runCatching { file.readText() }.getOrNull() else null + } + + /** The dashboard's snapshot. */ + fun load(context: Context): WidgetSnapshot? = read(context, "snapshot")?.let(WidgetSnapshot::parse) + + /** + * The snapshot of the trip a widget is set to; the dashboard's for none or + * "auto", and the dashboard's too while the app has not written that trip. + * A trip's snapshot carries no Atlas, so it borrows the dashboard's. + */ + fun load(context: Context, tripId: String?): WidgetSnapshot? { + if (tripId == null || tripId == AUTO) return load(context) + val own = read(context, "trip.$tripId")?.let(WidgetSnapshot::parse) ?: return load(context) + return if (own.atlas == null) own.copy(atlas = load(context)?.atlas) else own + } + + fun trips(context: Context): List = TripRef.parseList(read(context, "trips")) + + /** The trip picked for one placed widget, "auto" when none was. */ + fun tripFor(context: Context, appWidgetId: Int): String = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("trip.$appWidgetId", AUTO) ?: AUTO + + fun setTripFor(context: Context, appWidgetId: Int, tripId: String) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString("trip.$appWidgetId", tripId).commit() + changes.value++ + } + + fun forget(context: Context, appWidgetIds: IntArray) { + val editor = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + for (id in appWidgetIds) editor.remove("trip.$id") + editor.apply() + } +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetUi.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetUi.kt new file mode 100644 index 000000000..f395fdd0b --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/WidgetUi.kt @@ -0,0 +1,278 @@ +package com.liketrek.trek.widget + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.text.format.DateFormat +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.TextUnit +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.glance.ColorFilter +import androidx.glance.GlanceComposable +import androidx.glance.GlanceModifier +import androidx.glance.GlanceTheme +import androidx.glance.Image +import androidx.glance.ImageProvider +import androidx.glance.action.Action +import androidx.glance.action.clickable +import androidx.glance.appwidget.action.actionStartActivity +import androidx.glance.appwidget.appWidgetBackground +import androidx.glance.appwidget.cornerRadius +import androidx.glance.background +import androidx.glance.layout.Alignment +import androidx.glance.layout.Box +import androidx.glance.layout.Column +import androidx.glance.layout.Row +import androidx.glance.layout.Spacer +import androidx.glance.layout.fillMaxSize +import androidx.glance.layout.fillMaxWidth +import androidx.glance.layout.height +import androidx.glance.layout.padding +import androidx.glance.layout.size +import androidx.glance.layout.width +import androidx.glance.material3.ColorProviders +import androidx.glance.text.FontWeight +import androidx.glance.text.Text +import androidx.glance.text.TextStyle +import androidx.glance.unit.ColorProvider +import com.liketrek.trek.MainActivity +import java.time.LocalDate +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoUnit +import java.util.Locale + +/** + * What every TREK widget shares: Material You's colours on Android 12 and later + * (the wallpaper's), TREK's own before that, the system's corner radius, the + * tap that opens a place in the app, and the small pieces (eyebrow, chip, icon + * badge) the widgets are built from. + */ +object TrekWidgetTheme { + /** TREK's palette (client/src/mobile/mobile.css) for systems without dynamic colour. */ + val fallback = ColorProviders( + light = lightColorScheme( + primary = Color(0xFF101013), + onPrimary = Color(0xFFF5F5F7), + primaryContainer = Color(0xFFE7E5DF), + onPrimaryContainer = Color(0xFF101013), + secondary = Color(0xFF4A7DDB), + secondaryContainer = Color(0xFFE4EAF7), + onSecondaryContainer = Color(0xFF1B2F57), + tertiary = Color(0xFF2FA37A), + surface = Color(0xFFF7F6F2), + onSurface = Color(0xFF101013), + onSurfaceVariant = Color(0xFF68686F), + surfaceVariant = Color(0xFFECEAE4), + outline = Color(0xFF9A9AA1), + background = Color(0xFFF1EFEA), + error = Color(0xFFD6273B), + ), + dark = darkColorScheme( + primary = Color(0xFFF5F5F7), + onPrimary = Color(0xFF101013), + primaryContainer = Color(0xFF26262C), + onPrimaryContainer = Color(0xFFF5F5F7), + secondary = Color(0xFF8AAEF0), + secondaryContainer = Color(0xFF233250), + onSecondaryContainer = Color(0xFFDCE6FA), + tertiary = Color(0xFF5CC79E), + surface = Color(0xFF121216), + onSurface = Color(0xFFF5F5F7), + onSurfaceVariant = Color(0xFF9C9CA3), + surfaceVariant = Color(0xFF1E1E24), + outline = Color(0xFF6E6E76), + background = Color(0xFF0C0C0F), + error = Color(0xFFFF6B7A), + ), + ) + + @Composable + fun Themed(content: @Composable () -> Unit) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) GlanceTheme(content = content) else GlanceTheme(colors = fallback, content = content) + } +} + +/** The status colours, the same on every wallpaper so they keep their meaning. */ +object TrekStatus { + val confirmed = ColorProvider(Color(0xFF2FA37A)) + val pending = ColorProvider(Color(0xFFE8A13A)) + val danger = ColorProvider(Color(0xFFD6273B)) + val white = ColorProvider(Color.White) + val whiteMuted = ColorProvider(Color(0xCCFFFFFF)) + val whiteFaint = ColorProvider(Color(0x99FFFFFF)) + val scrim = ColorProvider(Color(0x66000000)) + val glass = ColorProvider(Color(0x33000000)) +} + +/** Opens [path] of the user's server in the app (nativeApp.ts routes com.liketrek.trek://navigate). */ +fun openPath(context: Context, path: String): Action = actionStartActivity( + Intent(Intent.ACTION_VIEW, Uri.parse(WidgetSnapshot.link(path)), context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP), +) + +/** The ground of a widget: the system's widget shape and the theme's widget background. */ +@Composable +fun WidgetFrame( + onClick: Action?, + background: ColorProvider = GlanceTheme.colors.widgetBackground, + padding: Dp = 14.dp, + content: @Composable () -> Unit, +) { + var modifier = GlanceModifier.fillMaxSize().appWidgetBackground().background(background).padding(padding) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) modifier = modifier.cornerRadius(android.R.dimen.system_app_widget_background_radius) + if (onClick != null) modifier = modifier.clickable(onClick) + Box(modifier = modifier) { content() } +} + +/** A small, bold, upper-case line above a widget's content. */ +@Composable +@GlanceComposable +fun Eyebrow(text: String, color: ColorProvider = GlanceTheme.colors.onSurfaceVariant, modifier: GlanceModifier = GlanceModifier) { + Text( + text = text.uppercase(Locale.getDefault()), + style = TextStyle(color = color, fontSize = 11.sp, fontWeight = FontWeight.Bold), + maxLines = 1, + modifier = modifier, + ) +} + +@Composable +fun Line( + text: String, + size: TextUnit = 13.sp, + color: ColorProvider = GlanceTheme.colors.onSurface, + weight: FontWeight = FontWeight.Normal, + maxLines: Int = 1, + modifier: GlanceModifier = GlanceModifier, +) { + Text(text = text, style = TextStyle(color = color, fontSize = size, fontWeight = weight), maxLines = maxLines, modifier = modifier) +} + +/** An icon in a tinted circle: a booking's kind, a stop's category. */ +@Composable +fun IconBadge(symbol: String?, tint: ColorProvider, background: ColorProvider, size: Dp = 28.dp) { + Box( + modifier = GlanceModifier.size(size).background(background).cornerRadius(size / 2), + contentAlignment = Alignment.Center, + ) { + Image( + provider = TrekIcons.provider(symbol), + contentDescription = null, + colorFilter = ColorFilter.tint(tint), + modifier = GlanceModifier.size(size * 0.58f), + ) + } +} + +@Composable +fun Icon(vector: ImageVector, tint: ColorProvider, size: Dp = 14.dp) { + Image(provider = TrekIcons.provider(vector), contentDescription = null, colorFilter = ColorFilter.tint(tint), modifier = GlanceModifier.size(size)) +} + +@Composable +fun SymbolIcon(symbol: String, tint: ColorProvider, size: Dp = 14.dp) { + Image(provider = TrekIcons.provider(symbol), contentDescription = null, colorFilter = ColorFilter.tint(tint), modifier = GlanceModifier.size(size)) +} + +/** A rounded pill with a short text: a date range, a weather reading, a status. */ +@Composable +fun Chip( + text: String, + background: ColorProvider, + color: ColorProvider, + leading: ImageProvider? = null, + leadingTint: ColorProvider? = null, +) { + Row( + modifier = GlanceModifier.background(background).cornerRadius(100.dp).padding(horizontal = 8.dp, vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (leading != null) { + Image( + provider = leading, + contentDescription = null, + colorFilter = leadingTint?.let { ColorFilter.tint(it) }, + modifier = GlanceModifier.size(12.dp), + ) + Spacer(GlanceModifier.width(4.dp)) + } + Text(text = text, style = TextStyle(color = color, fontSize = 11.sp, fontWeight = FontWeight.Medium), maxLines = 1) + } +} + +@Composable +fun WeatherChip(weather: WidgetSnapshot.Weather, onPhoto: Boolean) { + Chip( + text = "${weather.temp}°", + background = if (onPhoto) TrekStatus.glass else GlanceTheme.colors.secondaryContainer, + color = if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSecondaryContainer, + leading = TrekIcons.provider(TrekIcons.weather(weather.main)), + leadingTint = if (onPhoto) TrekStatus.white else GlanceTheme.colors.onSecondaryContainer, + ) +} + +/** A horizontal bar of [value] (0..1): Glance's progress indicator, rounded. */ +@Composable +fun Bar(value: Float, color: ColorProvider, track: ColorProvider, height: Dp = 6.dp, modifier: GlanceModifier = GlanceModifier.fillMaxWidth()) { + androidx.glance.appwidget.LinearProgressIndicator( + progress = value.coerceIn(0f, 1f), + color = color, + backgroundColor = track, + modifier = modifier.height(height).cornerRadius(height / 2), + ) +} + +/** The day segments of a trip: one bar per day, filled up to today. Drawn as one image (a Row takes ten children at most). */ +@Composable +fun DaySegments(index: Int, total: Int, color: ColorProvider) { + Image( + provider = ImageProvider(WidgetArt.segments(index, total)), + contentDescription = "$index / $total", + colorFilter = ColorFilter.tint(color), + contentScale = androidx.glance.layout.ContentScale.FillBounds, + modifier = GlanceModifier.fillMaxWidth().height(4.dp), + ) +} + +/** Relative days and ranges in the device's language. */ +object RelativeDay { + fun label(iso: String?, labels: WidgetSnapshot.Labels, today: LocalDate = LocalDate.now(), locale: Locale = Locale.getDefault()): String? { + val date = WidgetSnapshot.day(iso) ?: return null + val days = ChronoUnit.DAYS.between(today, date) + if (days == 0L) return labels.todayShort + if (days == 1L) return labels.tomorrowShort + val skeleton = if (days in 2..6) "EEE" else "EEEdMMM" + return DateTimeFormatter.ofPattern(DateFormat.getBestDateTimePattern(locale, skeleton), locale).format(date) + } + + /** "1-9 Oct" in the device's own way of writing a range. */ + fun range(context: Context, start: String, end: String): String? { + val from = WidgetSnapshot.day(start) ?: return null + val to = WidgetSnapshot.day(end) ?: return null + val zone = java.time.ZoneId.systemDefault() + val startMs = from.atStartOfDay(zone).toInstant().toEpochMilli() + // formatDateRange's end is exclusive: noon of the last day keeps it in the range. + val endMs = to.atTime(12, 0).atZone(zone).toInstant().toEpochMilli() + val flags = android.text.format.DateUtils.FORMAT_SHOW_DATE or android.text.format.DateUtils.FORMAT_ABBREV_MONTH or + android.text.format.DateUtils.FORMAT_NO_YEAR + return android.text.format.DateUtils.formatDateRange(context, startMs, endMs, flags) + } +} + +/** Minutes after midnight, now. */ +fun nowMinutes(): Int = java.time.LocalTime.now().let { it.hour * 60 + it.minute } + +/** "#rrggbb" as a colour, null for anything else. */ +fun cssColor(css: String?): ColorProvider? { + val hex = css?.removePrefix("#") ?: return null + if (hex.length != 6) return null + val value = hex.toLongOrNull(16) ?: return null + return ColorProvider(Color(0xFF000000 or value)) +} diff --git a/client/android/app/src/main/java/com/liketrek/trek/widget/WorldGrid.kt b/client/android/app/src/main/java/com/liketrek/trek/widget/WorldGrid.kt new file mode 100644 index 000000000..7632d4a98 --- /dev/null +++ b/client/android/app/src/main/java/com/liketrek/trek/widget/WorldGrid.kt @@ -0,0 +1,53 @@ +package com.liketrek.trek.widget + +/** + * The world as 76 by 34 dots from 80 degrees north to 58 south, each the ISO + * code of the country under it, ".." for sea. The same grid as the iOS widget + * (client/ios/App/TREKWidgets/WorldGrid.swift, generated from + * server/assets/atlas/admin0.geojson.gz); copy it over when that one changes. + */ +object WorldGrid { + const val COLUMNS = 76 + val ROWS: List = listOf( + "........................CACACA..CACACACACACA..GLGLGLGLGLGLGLGLGLGLGL............NONONO..................RU..........RURURU..............................", + "......................CACACACACA..CACACACACA........GLGLGLGLGLGLGLGL..............................RURU....RURURURURURURURURURURURURU..RURURU............", + "......USUSUSUSUSCACACACACACACACACACACACACACACACA....GLGLGLGLGLGLGL................NONONORURU....RURU..RURURURURURURURURURURURURURURURURURURURURURURURURU", + "RURU..USUSUSUSUSCACACACACACACACACACACACACACACACACA....GLGLGLGL....ISIS..........NOSESEFIRURURURURURURURURURURURURURURURURURURURURURURURURURURURURURURURU", + "......USUSUSUSUSCACACACACACACACACACACA....CACACACA....GLGL....................NONOSEFIFIRURURURURURURURURURURURURURURURURURURURURURURURURURURURURURURURU", + "........USUS......USCACACACACACACACACACA..CACACACA........................GB..NOSESELVLVRURURURURURURURURURURURURURURURURURURURURURURURU......RURU......", + "......US............CACACACACACACACACACACACACACACACA....................IEGBGBNLDEPLPLBYBYRURURURURURUKZKZRURURURURURURURURURURURURURURURU....RU........", + "......................CACACACACACACACACACACACACACACACA....................FRFRDEDECZPLUAUAUARURUKZKZKZKZKZKZKZKZRUMNMNMNMNRUMNCNCNRURURURU..............", + "........................USUSUSUSUSUSUSUSCACACAUSCA........................FRFRITITHRROROMDUARURURUKZKZKZKZKZKZCNCNMNMNMNMNMNCNCNCNCNRU..................", + "......................USUSUSUSUSUSUSUSUSUSUSUS..........................ESESES..ITITALBGTRTRTRGEAZTMTMUZKZKGKGCNCNCNCNCNCNCNCNCNCNCN..JPJP..............", + "........................USUSUSUSUSUSUSUSUSUS............................ESESDZDZ....GRTRTRTRTRIRIRIRIRTMTJTJCNCNCNCNCNCNCNCNCNCNKPKR..JP................", + "..........................USUSUSUSUSUSUSUSUS............................MAMADZDZTN..LY....LBIQIQIRIRIRAFAFPKINCNCNCNCNCNCNCNCNCNKRJPJP..................", + "..........................MXMXMXMXUSUS..US............................MADZDZDZDZLYLYLYEGEGSASAIQIRIRIRPKPKININNPCNCNCNCNCNCNCNCN........................", + "............................MXMXMXUS....US..........................EHEHMRDZDZDZLYLYLYEGEGSASASASAAEIRPKPKINININININMMCNCNCNCNCN........................", + "..............................MXMXMX..MXCUCUBS......................MRMRMRMLDZDZNETDLYSDSDSDSASASASAOM..INININININMMMMLAVNCN............................", + "................................MXMXMXMX..JM........................MRMRMRMLMLNENETDTDSDSDSDERYEYEOM......INININ....MMTHVN....PH........................", + "....................................GTSVNI....VE....................SNSNMLBFNENENGTDTDSDSDSDETYEYE........ININ......MMTHKH....PH........................", + "........................................CRPACOVEVEVE..................SLCIGHBJNGNGTDCFSSSSETETSOSO..........IN....IN....VN......PH......................", + "..........................................COCOCOVEGYSR..................CICI..NGCMCFCFCDSSKEETSOSO..................IDMY....MY..ID......................", + "..........................................ECCOBRBRBRBRBR........................GACGCDCDUGKEKESO......................ID..IDIDID........................", + "..........................................ECPEBRBRBRBRBRBRBR....................CGCDCDCDBITZKE........................IDIDIDIDID..IDIDIDPG..PG..........", + "..........................................PEBRBRBRBRBRBRBRBRBR..................AOAOCDCDTZTZTZ..........................IDIDID........IDPGPGPG..........", + "..........................................PEPEBOBRBRBRBRBRBRBR....................AOAOCDZMTZMZKM..................................AUAU....PG............", + "............................................PEBOBOBRBRBRBRBR....................AOAOAOZMMZMZMZMGMG..............................AUAUAU..AU..............", + "..............................................CLBOPYBRBRBRBR....................NANABWBWZWMZ..MGMG............................AUAUAUAUAUAUAU....FR......", + "..............................................CLARPYBRBRBR........................NABWBWZAMZ..MG............................AUAUAUAUAUAUAUAU............", + "..............................................ARARARBRBR..........................NAZAZAZA..................................AUAUAUAUAUAUAUAUAU..........", + "..............................................ARARARUY............................ZAZAZAZA..................................AUAUAUAUAUAUAUAUAU..........", + "............................................CLARARARUY..............................ZA......................................AU........AUAUAU............", + "............................................CLARARAR....................................................................................AU............NZ", + "............................................CLARAR......................................................................................AU........NZNZ..", + "............................................CLAR........................................................................................................", + "............................................CLAR........................................................................................................", + "..............................................CL........................................................................................................", + ) + + /** The country code of a dot, null for sea. */ + fun code(row: Int, column: Int): String? { + val code = ROWS[row].substring(column * 2, column * 2 + 2) + return if (code == "..") null else code + } +} diff --git a/client/android/app/src/main/res/drawable-land-hdpi/splash.png b/client/android/app/src/main/res/drawable-land-hdpi/splash.png new file mode 100644 index 000000000..74dc3b3b9 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-hdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-ldpi/splash.png b/client/android/app/src/main/res/drawable-land-ldpi/splash.png new file mode 100644 index 000000000..0fc76905b Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-ldpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-mdpi/splash.png b/client/android/app/src/main/res/drawable-land-mdpi/splash.png new file mode 100644 index 000000000..44e47fe08 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-mdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-hdpi/splash.png b/client/android/app/src/main/res/drawable-land-night-hdpi/splash.png new file mode 100644 index 000000000..74dc3b3b9 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-hdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-ldpi/splash.png b/client/android/app/src/main/res/drawable-land-night-ldpi/splash.png new file mode 100644 index 000000000..0fc76905b Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-ldpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-mdpi/splash.png b/client/android/app/src/main/res/drawable-land-night-mdpi/splash.png new file mode 100644 index 000000000..44e47fe08 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-mdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-xhdpi/splash.png b/client/android/app/src/main/res/drawable-land-night-xhdpi/splash.png new file mode 100644 index 000000000..86befb958 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-xhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-xxhdpi/splash.png b/client/android/app/src/main/res/drawable-land-night-xxhdpi/splash.png new file mode 100644 index 000000000..05ed96e11 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-xxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-night-xxxhdpi/splash.png b/client/android/app/src/main/res/drawable-land-night-xxxhdpi/splash.png new file mode 100644 index 000000000..a10b336e5 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-night-xxxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-xhdpi/splash.png b/client/android/app/src/main/res/drawable-land-xhdpi/splash.png new file mode 100644 index 000000000..86befb958 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-xhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-xxhdpi/splash.png b/client/android/app/src/main/res/drawable-land-xxhdpi/splash.png new file mode 100644 index 000000000..05ed96e11 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-xxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-land-xxxhdpi/splash.png b/client/android/app/src/main/res/drawable-land-xxxhdpi/splash.png new file mode 100644 index 000000000..a10b336e5 Binary files /dev/null and b/client/android/app/src/main/res/drawable-land-xxxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-night/splash.png b/client/android/app/src/main/res/drawable-night/splash.png new file mode 100644 index 000000000..0fc76905b Binary files /dev/null and b/client/android/app/src/main/res/drawable-night/splash.png differ diff --git a/client/android/app/src/main/res/drawable-nodpi/widget_preview_atlas.png b/client/android/app/src/main/res/drawable-nodpi/widget_preview_atlas.png new file mode 100644 index 000000000..b469b971c Binary files /dev/null and b/client/android/app/src/main/res/drawable-nodpi/widget_preview_atlas.png differ diff --git a/client/android/app/src/main/res/drawable-nodpi/widget_preview_bookings.png b/client/android/app/src/main/res/drawable-nodpi/widget_preview_bookings.png new file mode 100644 index 000000000..f05eea50f Binary files /dev/null and b/client/android/app/src/main/res/drawable-nodpi/widget_preview_bookings.png differ diff --git a/client/android/app/src/main/res/drawable-nodpi/widget_preview_collab.png b/client/android/app/src/main/res/drawable-nodpi/widget_preview_collab.png new file mode 100644 index 000000000..1e8040aa1 Binary files /dev/null and b/client/android/app/src/main/res/drawable-nodpi/widget_preview_collab.png differ diff --git a/client/android/app/src/main/res/drawable-nodpi/widget_preview_packing.png b/client/android/app/src/main/res/drawable-nodpi/widget_preview_packing.png new file mode 100644 index 000000000..89a3a0578 Binary files /dev/null and b/client/android/app/src/main/res/drawable-nodpi/widget_preview_packing.png differ diff --git a/client/android/app/src/main/res/drawable-nodpi/widget_preview_today.png b/client/android/app/src/main/res/drawable-nodpi/widget_preview_today.png new file mode 100644 index 000000000..ad3b7b6e1 Binary files /dev/null and b/client/android/app/src/main/res/drawable-nodpi/widget_preview_today.png differ diff --git a/client/android/app/src/main/res/drawable-nodpi/widget_preview_todos.png b/client/android/app/src/main/res/drawable-nodpi/widget_preview_todos.png new file mode 100644 index 000000000..88ab2dda3 Binary files /dev/null and b/client/android/app/src/main/res/drawable-nodpi/widget_preview_todos.png differ diff --git a/client/android/app/src/main/res/drawable-nodpi/widget_preview_trip.png b/client/android/app/src/main/res/drawable-nodpi/widget_preview_trip.png new file mode 100644 index 000000000..bab4da1a0 Binary files /dev/null and b/client/android/app/src/main/res/drawable-nodpi/widget_preview_trip.png differ diff --git a/client/android/app/src/main/res/drawable-port-hdpi/splash.png b/client/android/app/src/main/res/drawable-port-hdpi/splash.png new file mode 100644 index 000000000..26fb4b482 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-hdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-ldpi/splash.png b/client/android/app/src/main/res/drawable-port-ldpi/splash.png new file mode 100644 index 000000000..aebbc4c8d Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-ldpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-mdpi/splash.png b/client/android/app/src/main/res/drawable-port-mdpi/splash.png new file mode 100644 index 000000000..55a7a810d Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-mdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-hdpi/splash.png b/client/android/app/src/main/res/drawable-port-night-hdpi/splash.png new file mode 100644 index 000000000..26fb4b482 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-hdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-ldpi/splash.png b/client/android/app/src/main/res/drawable-port-night-ldpi/splash.png new file mode 100644 index 000000000..aebbc4c8d Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-ldpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-mdpi/splash.png b/client/android/app/src/main/res/drawable-port-night-mdpi/splash.png new file mode 100644 index 000000000..55a7a810d Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-mdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-xhdpi/splash.png b/client/android/app/src/main/res/drawable-port-night-xhdpi/splash.png new file mode 100644 index 000000000..4bc78881a Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-xhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-xxhdpi/splash.png b/client/android/app/src/main/res/drawable-port-night-xxhdpi/splash.png new file mode 100644 index 000000000..1db91f892 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-xxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-night-xxxhdpi/splash.png b/client/android/app/src/main/res/drawable-port-night-xxxhdpi/splash.png new file mode 100644 index 000000000..b4480e6c5 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-night-xxxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-xhdpi/splash.png b/client/android/app/src/main/res/drawable-port-xhdpi/splash.png new file mode 100644 index 000000000..4bc78881a Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-xhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-xxhdpi/splash.png b/client/android/app/src/main/res/drawable-port-xxhdpi/splash.png new file mode 100644 index 000000000..1db91f892 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-xxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable-port-xxxhdpi/splash.png b/client/android/app/src/main/res/drawable-port-xxxhdpi/splash.png new file mode 100644 index 000000000..b4480e6c5 Binary files /dev/null and b/client/android/app/src/main/res/drawable-port-xxxhdpi/splash.png differ diff --git a/client/android/app/src/main/res/drawable/ic_stat_trek.xml b/client/android/app/src/main/res/drawable/ic_stat_trek.xml new file mode 100644 index 000000000..3f7b9155f --- /dev/null +++ b/client/android/app/src/main/res/drawable/ic_stat_trek.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/client/android/app/src/main/res/drawable/splash.png b/client/android/app/src/main/res/drawable/splash.png new file mode 100644 index 000000000..55a7a810d Binary files /dev/null and b/client/android/app/src/main/res/drawable/splash.png differ diff --git a/client/android/app/src/main/res/drawable/widget_scrim.xml b/client/android/app/src/main/res/drawable/widget_scrim.xml new file mode 100644 index 000000000..fabef7c70 --- /dev/null +++ b/client/android/app/src/main/res/drawable/widget_scrim.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/client/android/app/src/main/res/layout/activity_main.xml b/client/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 000000000..b5ad13870 --- /dev/null +++ b/client/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 000000000..9fa1d84f9 --- /dev/null +++ b/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 000000000..9fa1d84f9 --- /dev/null +++ b/client/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 000000000..1ecdbd50a Binary files /dev/null and b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png new file mode 100644 index 000000000..9eda142ec Binary files /dev/null and b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..4c4f0d080 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 000000000..48574eef7 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/mipmap-ldpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher.png new file mode 100644 index 000000000..18c52ea62 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_background.png new file mode 100644 index 000000000..156955491 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_foreground.png new file mode 100644 index 000000000..d703351f9 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_round.png new file mode 100644 index 000000000..df8fd53aa Binary files /dev/null and b/client/android/app/src/main/res/mipmap-ldpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 000000000..8ffbeb0f7 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png new file mode 100644 index 000000000..590b65af8 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..380f393ba Binary files /dev/null and b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 000000000..237de9a01 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 000000000..8233d2e85 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png new file mode 100644 index 000000000..c10f64659 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..1d654c1a3 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 000000000..911f1e4fa Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..012c55d9a Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png new file mode 100644 index 000000000..059ab588a Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..bc3061c86 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 000000000..e572cd218 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 000000000..bebe0ad39 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png new file mode 100644 index 000000000..92f23a500 Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png differ diff --git a/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 000000000..83d5921ac Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 000000000..94317032b Binary files /dev/null and b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/client/android/app/src/main/res/resources.properties b/client/android/app/src/main/res/resources.properties new file mode 100644 index 000000000..467b3efec --- /dev/null +++ b/client/android/app/src/main/res/resources.properties @@ -0,0 +1 @@ +unqualifiedResLocale=en-US diff --git a/client/android/app/src/main/res/values-ar/strings_native.xml b/client/android/app/src/main/res/values-ar/strings_native.xml new file mode 100644 index 000000000..56b3ddbd3 --- /dev/null +++ b/client/android/app/src/main/res/values-ar/strings_native.xml @@ -0,0 +1,59 @@ + + + + رحلة + عدّ تنازلي لرحلتك القادمة، ثم اليوم وما يليه أثناء السفر. + اليوم + خطة اليوم كخط زمني، مع الطقس والمحطة التالية. + الحجوزات + رحلاتك وقطاراتك وفنادقك وحجوزات المطاعم القادمة ومواعيدها. + الرحلة + رحلتك القادمة مباشرة: عد تنازلي للإقلاع، والطائرة في طريقها، والتأخير والوصول. + المهام + ما تبقى للرحلة، ومدى تقدم تجهيز الأمتعة. + قائمة الأمتعة + مدى امتلاء الحقائب ووزنها وما الذي ما زال ناقصًا. + خريطة العالم + الدول التي زرتها مضيئة على الخريطة. + مجموعة السفر + من يرافقك وأحدث الرسائل والتصويت المفتوح. + اختر الرحلة + الرحلة التي تعرضها هذه الأداة. + الرحلة + تلقائي + نفس رحلة لوحة التحكم + إضافة إلى TREK + إلغاء + إغلاق + الرحلة + افتح TREK مرة واحدة وستظهر رحلاتك هنا. + يقرأ TREK الحجز ويضيفه إلى الرحلة. + الاختيار لاحقًا + إضافة + إضافة إلى %1$s + تمت الإضافة + جارٍ القراءة… + هذا الملف أكبر من أن يُستورد. + لا يستطيع TREK استيراد هذا. + تعذّر تمرير هذا إلى TREK. حاول مرة أخرى. + الآن + انتهت + غدًا + بعد %1$d يومًا + بطاقة Wallet + PDF + بريد + صفحة ويب + نص + صورة + ملف + افتح TREK مرة واحدة وستظهر رحلاتك هنا. + دردشة الرحلة + تحديثات الرحلة + الدعوات والمشاركات + عام + يوم السفر + إشعار جديد + يوم الرحلة الجارية ومحطتها التالية. + diff --git a/client/android/app/src/main/res/values-az/strings_native.xml b/client/android/app/src/main/res/values-az/strings_native.xml new file mode 100644 index 000000000..3d7068016 --- /dev/null +++ b/client/android/app/src/main/res/values-az/strings_native.xml @@ -0,0 +1,59 @@ + + + + Səyahət + Növbəti səyahətə qədər günləri sayır, yolda isə günü və sonrakını göstərir. + Bu gün + Günün planı zaman xətti kimi, hava və növbəti dayanacaqla. + Bronlar + Növbəti uçuşlar, qatarlar, otellər və restoranlar, nə vaxt olduqları ilə. + Uçuş + Növbəti uçuşun canlı: uçuşa qədər geri sayım, yolda olan təyyarə, gecikmə və gəliş. + Tapşırıqlar + Səyahət üçün hələ nəyin qaldığı və yığışmağın nə yerdə olduğu. + Yük siyahısı + Çantaların doluluğu, çəkisi və hələ nəyin çatışmadığı. + Dünya xəritəsi + Olduğun ölkələr xəritədə parlayır. + Səyahət qrupu + Kim gəlir, son mesajlar və açıq səsvermə. + Səyahəti seç + Bu vidcetin göstərdiyi səyahət. + Səyahət + Avtomatik + İdarə panelindəki səyahət + TREK-ə əlavə et + Ləğv et + Bağla + Səyahət + TREK-i bir dəfə açın, səyahətləriniz burada görünəcək. + TREK rezervasiyanı oxuyur və səyahətə əlavə edir. + Sonra seç + Əlavə et + %1$s səyahətinə əlavə et + Əlavə edildi + Oxunur… + Bu fayl idxal üçün çox böyükdür. + TREK bunu idxal edə bilmir. + Bunu TREK-ə ötürmək alınmadı. Yenidən cəhd edin. + İndi + Keçib + Sabah + %1$d gün sonra + Wallet kartı + PDF + E-poçt + Veb səhifə + Mətn + Foto + Fayl + TREK-i bir dəfə açın, səyahətləriniz burada görünəcək. + Səyahət söhbəti + Səyahət yenilikləri + Dəvətlər və paylaşımlar + Ümumi + Səyahət günü + Yeni bildiriş + Davam edən səyahətin günü və növbəti dayanacağı. + diff --git a/client/android/app/src/main/res/values-b+zh+Hans/strings_native.xml b/client/android/app/src/main/res/values-b+zh+Hans/strings_native.xml new file mode 100644 index 000000000..52a472a2d --- /dev/null +++ b/client/android/app/src/main/res/values-b+zh+Hans/strings_native.xml @@ -0,0 +1,59 @@ + + + + 旅行 + 倒数到下一次旅行,旅途中显示当天行程和接下来的安排。 + 今天 + 以时间线显示今天的计划,附带天气和下一站。 + 预订 + 你接下来的航班、火车、酒店和餐厅,以及时间。 + 航班 + 实时查看下一班航班:起飞倒计时、飞行中的飞机、延误和到达。 + 待办 + 旅行还剩哪些事没做,以及行李收拾到哪一步。 + 行李 + 包装得多满、重量多少,以及还缺什么。 + 世界地图 + 你去过的国家在地图上亮起。 + 旅行小组 + 谁一起去、最新消息和进行中的投票。 + 选择旅行 + 此小组件显示的旅行。 + 旅行 + 自动 + 与仪表板相同的旅行 + 添加到 TREK + 取消 + 关闭 + 行程 + 打开一次 TREK,你的行程就会显示在这里。 + TREK 会读取预订并添加到行程中。 + 稍后选择 + 添加 + 添加到 %1$s + 已添加 + 正在读取… + 此文件太大,无法导入。 + TREK 无法导入此内容。 + 无法传给 TREK。请重试。 + 进行中 + 已结束 + 明天 + %1$d 天后 + Wallet 卡券 + PDF + 邮件 + 网页 + 文本 + 照片 + 文件 + 打开一次 TREK,你的行程就会显示在这里。 + 行程聊天 + 行程动态 + 邀请与共享 + 常规 + 旅行日 + 新通知 + 进行中行程的当天安排和下一站。 + diff --git a/client/android/app/src/main/res/values-b+zh+Hant/strings_native.xml b/client/android/app/src/main/res/values-b+zh+Hant/strings_native.xml new file mode 100644 index 000000000..fff51c837 --- /dev/null +++ b/client/android/app/src/main/res/values-b+zh+Hant/strings_native.xml @@ -0,0 +1,59 @@ + + + + 旅行 + 倒數到下一次旅行,旅途中顯示當天行程與接下來的安排。 + 今天 + 以時間軸顯示今天的計畫,附上天氣與下一站。 + 預訂 + 你接下來的航班、火車、飯店與餐廳,以及時間。 + 航班 + 即時查看下一班航班:起飛倒數、飛行中的飛機、延誤和抵達。 + 待辦 + 旅行還剩哪些事沒做,以及行李整理到哪一步。 + 行李 + 包包裝得多滿、重量多少,以及還缺什麼。 + 世界地圖 + 你去過的國家在地圖上亮起。 + 旅行小組 + 誰一起去、最新訊息與進行中的投票。 + 選擇旅行 + 此小工具顯示的旅行。 + 旅行 + 自動 + 與儀表板相同的旅行 + 加入 TREK + 取消 + 關閉 + 行程 + 開啟一次 TREK,你的行程就會顯示在這裡。 + TREK 會讀取訂位並加入行程。 + 稍後選擇 + 加入 + 加入 %1$s + 已加入 + 正在讀取… + 此檔案太大,無法匯入。 + TREK 無法匯入此內容。 + 無法傳給 TREK。請重試。 + 進行中 + 已結束 + 明天 + %1$d 天後 + Wallet 票卡 + PDF + 郵件 + 網頁 + 文字 + 照片 + 檔案 + 開啟一次 TREK,你的行程就會顯示在這裡。 + 行程聊天 + 行程動態 + 邀請與共享 + 一般 + 旅行日 + 新通知 + 進行中行程的當天安排與下一站。 + diff --git a/client/android/app/src/main/res/values-ca/strings_native.xml b/client/android/app/src/main/res/values-ca/strings_native.xml new file mode 100644 index 000000000..459e13f64 --- /dev/null +++ b/client/android/app/src/main/res/values-ca/strings_native.xml @@ -0,0 +1,59 @@ + + + + Viatge + Compta els dies fins al proper viatge i, durant el viatge, mostra el dia i el que ve després. + Avui + El pla del dia com a línia de temps, amb el temps i la propera parada. + Reserves + Els teus propers vols, trens, hotels i taules, i quan toquen. + Vol + El teu proper vol en directe: compte enrere de la sortida, l’avió en camí, retard i arribada. + Tasques + El que encara queda per al viatge i com va l\'equipatge. + Equipatge + Com de plenes són les maletes, el pes i el que encara falta. + Mapa del món + Els països on has estat, brillant al mapa. + Grup de viatge + Qui ve, els darrers missatges i la votació oberta. + Tria el viatge + El viatge que mostra aquest giny. + Viatge + Automàtic + El mateix viatge que el tauler + Afegeix a TREK + Cancel·la + Tanca + Viatge + Obre TREK una vegada i aquí apareixeran els teus viatges. + TREK llegeix la reserva i l’afegeix al viatge. + Tria més tard + Afegeix + Afegeix a %1$s + Afegit + Llegint… + Aquest fitxer és massa gran per importar-lo. + TREK no pot importar això. + No s’ha pogut passar a TREK. Torna-ho a provar. + Ara + Passat + Demà + D’aquí a %1$d dies + Passi de Wallet + PDF + Correu + Pàgina web + Text + Foto + Fitxer + Obre TREK una vegada i aquí apareixeran els teus viatges. + Xat del viatge + Novetats del viatge + Invitacions i comparticions + General + Dia de viatge + Notificació nova + El dia d\'un viatge en curs i la seva propera parada. + diff --git a/client/android/app/src/main/res/values-cs/strings_native.xml b/client/android/app/src/main/res/values-cs/strings_native.xml new file mode 100644 index 000000000..7a7ddab9e --- /dev/null +++ b/client/android/app/src/main/res/values-cs/strings_native.xml @@ -0,0 +1,59 @@ + + + + Cesta + Odpočítává dny do další cesty a během ní ukazuje den a co přijde dál. + Dnes + Plán dne jako časová osa, s počasím a další zastávkou. + Rezervace + Tvoje další lety, vlaky, hotely a stoly, a kdy tě čekají. + Let + Tvůj další let živě: odpočet do odletu, letadlo na cestě, zpoždění a přílet. + Úkoly + Co ještě zbývá k cestě a jak daleko je balení. + Balení + Jak plná jsou zavazadla, jejich váha a co ještě chybí. + Mapa světa + Země, kde jsi byl, zářící na mapě. + Cestovní skupina + Kdo jede s tebou, nejnovější zprávy a otevřené hlasování. + Vybrat cestu + Cesta, kterou tento widget zobrazuje. + Cesta + Automaticky + Stejná cesta jako na nástěnce + Přidat do TREK + Zrušit + Zavřít + Cesta + Jednou otevřete TREK a vaše cesty se zobrazí zde. + TREK přečte rezervaci a přidá ji k cestě. + Vybrat později + Přidat + Přidat do %1$s + Přidáno + Načítání… + Tento soubor je pro import příliš velký. + Tohle TREK neumí importovat. + Nepodařilo se to předat do TREK. Zkuste to znovu. + Teď + Proběhla + Zítra + Za %1$d dní + Karta Wallet + PDF + E-mail + Webová stránka + Text + Fotka + Soubor + Jednou otevřete TREK a vaše cesty se zobrazí zde. + Chat výletu + Novinky z výletu + Pozvánky a sdílení + Obecné + Cestovní den + Nové oznámení + Den probíhajícího výletu a jeho další zastávka. + diff --git a/client/android/app/src/main/res/values-de/strings_native.xml b/client/android/app/src/main/res/values-de/strings_native.xml new file mode 100644 index 000000000..062bb98db --- /dev/null +++ b/client/android/app/src/main/res/values-de/strings_native.xml @@ -0,0 +1,59 @@ + + + + Reise + Zählt die Tage bis zur nächsten Reise und zeigt unterwegs den Tag und was als Nächstes kommt. + Heute + Der Tagesplan als Zeitleiste, mit dem Wetter und dem nächsten Stopp. + Buchungen + Deine nächsten Flüge, Züge, Hotels und Tische, und wann sie anstehen. + Flug + Dein nächster Flug live: Countdown bis zum Abflug, die Maschine unterwegs, Verspätung und Ankunft. + To-dos + Was für die Reise noch offen ist und wie weit das Packen ist. + Packliste + Wie voll die Taschen sind, ihr Gewicht und was noch fehlt. + Weltkarte + Die Länder, in denen du warst, leuchtend auf der Karte. + Reisegruppe + Wer mitreist, die neuesten Nachrichten und die offene Abstimmung. + Reise wählen + Die Reise, die dieses Widget zeigt. + Reise + Automatisch + Dieselbe Reise wie im Dashboard + Zu TREK hinzufügen + Abbrechen + Schließen + Reise + Öffne TREK einmal, dann erscheinen hier deine Reisen. + TREK liest die Buchung und trägt sie in die Reise ein. + Später wählen + Hinzufügen + Zu %1$s hinzufügen + Hinzugefügt + Wird gelesen… + Diese Datei ist zu groß für den Import. + Das kann TREK nicht importieren. + Das konnte nicht an TREK übergeben werden. Bitte versuch es erneut. + Läuft + Vorbei + Morgen + In %1$d Tagen + Wallet-Pass + PDF + E-Mail + Webseite + Text + Foto + Datei + Öffne TREK einmal, dann erscheinen hier deine Reisen. + Reise-Chat + Neues zur Reise + Einladungen und Freigaben + Allgemein + Reisetag + Neue Benachrichtigung + Der Tag einer laufenden Reise und der nächste Stopp. + diff --git a/client/android/app/src/main/res/values-el/strings_native.xml b/client/android/app/src/main/res/values-el/strings_native.xml new file mode 100644 index 000000000..bf8bd4586 --- /dev/null +++ b/client/android/app/src/main/res/values-el/strings_native.xml @@ -0,0 +1,59 @@ + + + + Ταξίδι + Μετρά αντίστροφα ως το επόμενο ταξίδι και στη διάρκειά του δείχνει τη μέρα και τι ακολουθεί. + Σήμερα + Το πρόγραμμα της ημέρας ως χρονολόγιο, με τον καιρό και την επόμενη στάση. + Κρατήσεις + Οι επόμενες πτήσεις, τα τρένα, τα ξενοδοχεία και τα τραπέζια σου, και πότε είναι. + Πτήση + Η επόμενη πτήση σου ζωντανά: αντίστροφη μέτρηση για την αναχώρηση, το αεροσκάφος καθ’ οδόν, καθυστέρηση και άφιξη. + Εκκρεμότητες + Τι μένει ακόμα για το ταξίδι και πόσο έχει προχωρήσει το πακετάρισμα. + Αποσκευές + Πόσο γεμάτες είναι οι τσάντες, το βάρος τους και τι λείπει ακόμα. + Παγκόσμιος χάρτης + Οι χώρες που έχεις επισκεφθεί, φωτεινές στον χάρτη. + Ομάδα ταξιδιού + Ποιος έρχεται, τα τελευταία μηνύματα και η ανοιχτή ψηφοφορία. + Επιλογή ταξιδιού + Το ταξίδι που δείχνει αυτό το widget. + Ταξίδι + Αυτόματα + Το ίδιο ταξίδι με τον πίνακα + Προσθήκη στο TREK + Ακύρωση + Κλείσιμο + Ταξίδι + Ανοίξτε το TREK μία φορά και τα ταξίδια σας θα εμφανιστούν εδώ. + Το TREK διαβάζει την κράτηση και την προσθέτει στο ταξίδι. + Επιλογή αργότερα + Προσθήκη + Προσθήκη στο %1$s + Προστέθηκε + Ανάγνωση… + Το αρχείο είναι πολύ μεγάλο για εισαγωγή. + Το TREK δεν μπορεί να το εισαγάγει. + Δεν ήταν δυνατή η μεταφορά στο TREK. Δοκιμάστε ξανά. + Τώρα + Παρελθόν + Αύριο + Σε %1$d ημέρες + Κάρτα Wallet + PDF + Email + Ιστοσελίδα + Κείμενο + Φωτογραφία + Αρχείο + Ανοίξτε το TREK μία φορά και τα ταξίδια σας θα εμφανιστούν εδώ. + Συνομιλία ταξιδιού + Ενημερώσεις ταξιδιού + Προσκλήσεις και κοινοποιήσεις + Γενικά + Ημέρα ταξιδιού + Νέα ειδοποίηση + Η ημέρα ενός ταξιδιού σε εξέλιξη και η επόμενη στάση του. + diff --git a/client/android/app/src/main/res/values-es/strings_native.xml b/client/android/app/src/main/res/values-es/strings_native.xml new file mode 100644 index 000000000..defbbad30 --- /dev/null +++ b/client/android/app/src/main/res/values-es/strings_native.xml @@ -0,0 +1,59 @@ + + + + Viaje + Cuenta los días hasta tu próximo viaje y, durante él, muestra el día y lo que sigue. + Hoy + El plan del día como línea de tiempo, con el tiempo y la próxima parada. + Reservas + Tus próximos vuelos, trenes, hoteles y mesas, y cuándo tocan. + Vuelo + Tu próximo vuelo en directo: cuenta atrás de la salida, el avión en camino, retraso y llegada. + Tareas + Lo que aún queda para el viaje y cómo va la maleta. + Equipaje + Lo llenas que van las maletas, su peso y lo que aún falta. + Mapa del mundo + Los países donde has estado, brillando en el mapa. + Grupo de viaje + Quién viene, los últimos mensajes y la votación abierta. + Elegir viaje + El viaje que muestra este widget. + Viaje + Automático + El mismo viaje que el panel + Añadir a TREK + Cancelar + Cerrar + Viaje + Abre TREK una vez y tus viajes aparecerán aquí. + TREK lee la reserva y la añade al viaje. + Elegir después + Añadir + Añadir a %1$s + Añadido + Leyendo… + Este archivo es demasiado grande para importarlo. + TREK no puede importar esto. + No se pudo pasar a TREK. Inténtalo de nuevo. + En curso + Pasado + Mañana + En %1$d días + Pase de Wallet + PDF + Correo + Página web + Texto + Foto + Archivo + Abre TREK una vez y tus viajes aparecerán aquí. + Chat del viaje + Novedades del viaje + Invitaciones y compartidos + General + Día de viaje + Notificación nueva + El día de un viaje en curso y su próxima parada. + diff --git a/client/android/app/src/main/res/values-et/strings_native.xml b/client/android/app/src/main/res/values-et/strings_native.xml new file mode 100644 index 000000000..39bdec36f --- /dev/null +++ b/client/android/app/src/main/res/values-et/strings_native.xml @@ -0,0 +1,59 @@ + + + + Reis + Loeb päevi järgmise reisini ja näitab reisi ajal päeva ning seda, mis järgmisena tuleb. + Täna + Päeva plaan ajajoonena, koos ilma ja järgmise peatusega. + Broneeringud + Sinu järgmised lennud, rongid, hotellid ja lauad ning millal need on. + Lend + Sinu järgmine lend otse: loendus väljumiseni, lennuk teel, hilinemine ja saabumine. + Ülesanded + Mis reisi jaoks veel tegemata on ja kui kaugel pakkimine on. + Pakkimine + Kui täis kotid on, nende kaal ja mis veel puudu on. + Maailmakaart + Riigid, kus oled käinud, kaardil helendamas. + Reisiseltskond + Kes tuleb kaasa, viimased sõnumid ja avatud hääletus. + Vali reis + Reis, mida see vidin näitab. + Reis + Automaatne + Sama reis mis töölaual + Lisa TREK-i + Tühista + Sulge + Reis + Ava TREK korra ja sinu reisid ilmuvad siia. + TREK loeb broneeringu ja lisab selle reisile. + Vali hiljem + Lisa + Lisa reisile %1$s + Lisatud + Loen… + See fail on importimiseks liiga suur. + TREK ei saa seda importida. + Seda ei õnnestunud TREK-ile üle anda. Proovi uuesti. + Praegu + Möödas + Homme + %1$d päeva pärast + Wallet’i pass + PDF + E-kiri + Veebileht + Tekst + Foto + Fail + Ava TREK korra ja sinu reisid ilmuvad siia. + Reisi vestlus + Reisi uudised + Kutsed ja jagamised + Üldine + Reisipäev + Uus teavitus + Käimasoleva reisi päev ja järgmine peatus. + diff --git a/client/android/app/src/main/res/values-fr/strings_native.xml b/client/android/app/src/main/res/values-fr/strings_native.xml new file mode 100644 index 000000000..b12d17323 --- /dev/null +++ b/client/android/app/src/main/res/values-fr/strings_native.xml @@ -0,0 +1,59 @@ + + + + Voyage + Compte les jours jusqu\'au prochain voyage, puis montre la journée et la suite pendant le voyage. + Aujourd\'hui + Le programme du jour en frise, avec la météo et la prochaine étape. + Réservations + Vos prochains vols, trains, hôtels et tables, et quand ils arrivent. + Vol + Votre prochain vol en direct : compte à rebours du départ, l’avion en route, retard et arrivée. + À faire + Ce qui reste à faire pour le voyage et où en sont les bagages. + Bagages + Le remplissage des sacs, leur poids et ce qui manque encore. + Carte du monde + Les pays où vous êtes allé, illuminés sur la carte. + Groupe de voyage + Qui vient, les derniers messages et le sondage ouvert. + Choisir le voyage + Le voyage affiché par ce widget. + Voyage + Automatique + Le même voyage que le tableau de bord + Ajouter à TREK + Annuler + Fermer + Voyage + Ouvrez TREK une fois et vos voyages apparaîtront ici. + TREK lit la réservation et l’ajoute au voyage. + Choisir plus tard + Ajouter + Ajouter à %1$s + Ajouté + Lecture… + Ce fichier est trop volumineux pour être importé. + TREK ne peut pas importer ceci. + Impossible de transmettre ceci à TREK. Réessayez. + En cours + Passé + Demain + Dans %1$d jours + Carte Wallet + PDF + E-mail + Page web + Texte + Photo + Fichier + Ouvrez TREK une fois et vos voyages apparaîtront ici. + Discussion du voyage + Nouvelles du voyage + Invitations et partages + Général + Jour de voyage + Nouvelle notification + La journée d\'un voyage en cours et sa prochaine étape. + diff --git a/client/android/app/src/main/res/values-hu/strings_native.xml b/client/android/app/src/main/res/values-hu/strings_native.xml new file mode 100644 index 000000000..6df7237b2 --- /dev/null +++ b/client/android/app/src/main/res/values-hu/strings_native.xml @@ -0,0 +1,59 @@ + + + + Utazás + Visszaszámol a következő utazásig, útközben pedig a napot és a következő programot mutatja. + Ma + A nap terve idővonalon, az időjárással és a következő megállóval. + Foglalások + A következő járataid, vonataid, szállásaid és asztalfoglalásaid, és hogy mikor esedékesek. + Járat + A következő járatod élőben: visszaszámlálás az indulásig, a gép útközben, késés és érkezés. + Teendők + Ami még hátravan az utazáshoz, és hol tart a csomagolás. + Csomagolás + Mennyire telik a táska, a súlya, és mi hiányzik még. + Világtérkép + Az országok, ahol jártál, világítva a térképen. + Útitársak + Ki jön veled, a legújabb üzenetek és a nyitott szavazás. + Utazás választása + Az utazás, amelyet ez a widget mutat. + Utazás + Automatikus + Ugyanaz az utazás, mint az irányítópulton + Hozzáadás a TREK-hez + Mégse + Bezárás + Utazás + Nyisd meg egyszer a TREK-et, és itt megjelennek az utazásaid. + A TREK beolvassa a foglalást, és hozzáadja az utazáshoz. + Később választok + Hozzáadás + Hozzáadás ehhez: %1$s + Hozzáadva + Olvasás… + Ez a fájl túl nagy az importáláshoz. + Ezt a TREK nem tudja importálni. + Nem sikerült átadni a TREK-nek. Próbáld újra. + Most + Elmúlt + Holnap + %1$d nap múlva + Wallet-kártya + PDF + E-mail + Weboldal + Szöveg + Fotó + Fájl + Nyisd meg egyszer a TREK-et, és itt megjelennek az utazásaid. + Utazási csevegés + Utazási hírek + Meghívások és megosztások + Általános + Utazási nap + Új értesítés + Egy folyamatban lévő utazás napja és a következő megálló. + diff --git a/client/android/app/src/main/res/values-in/strings_native.xml b/client/android/app/src/main/res/values-in/strings_native.xml new file mode 100644 index 000000000..751f785ee --- /dev/null +++ b/client/android/app/src/main/res/values-in/strings_native.xml @@ -0,0 +1,59 @@ + + + + Perjalanan + Menghitung mundur ke perjalanan berikutnya, lalu menampilkan hari dan apa yang berikutnya. + Hari ini + Rencana hari ini sebagai linimasa, dengan cuaca dan perhentian berikutnya. + Pemesanan + Penerbangan, kereta, hotel, dan meja berikutnya, beserta waktunya. + Penerbangan + Penerbangan berikutnya secara langsung: hitung mundur keberangkatan, pesawat dalam perjalanan, keterlambatan, dan kedatangan. + Tugas + Yang masih tersisa untuk perjalanan dan sejauh mana persiapan barang. + Barang bawaan + Seberapa penuh tas, beratnya, dan yang masih kurang. + Peta dunia + Negara yang pernah kamu kunjungi, bersinar di peta. + Rombongan + Siapa yang ikut, pesan terbaru, dan polling yang terbuka. + Pilih perjalanan + Perjalanan yang ditampilkan widget ini. + Perjalanan + Otomatis + Perjalanan yang sama dengan dasbor + Tambahkan ke TREK + Batal + Tutup + Perjalanan + Buka TREK sekali dan perjalanan Anda akan muncul di sini. + TREK membaca pemesanan dan menambahkannya ke perjalanan. + Pilih nanti + Tambahkan + Tambahkan ke %1$s + Ditambahkan + Membaca… + File ini terlalu besar untuk diimpor. + TREK tidak dapat mengimpor ini. + Tidak dapat diteruskan ke TREK. Silakan coba lagi. + Sekarang + Lewat + Besok + Dalam %1$d hari + Pass Wallet + PDF + Email + Halaman web + Teks + Foto + File + Buka TREK sekali dan perjalanan Anda akan muncul di sini. + Obrolan perjalanan + Kabar perjalanan + Undangan dan berbagi + Umum + Hari perjalanan + Notifikasi baru + Hari dari perjalanan yang berlangsung dan perhentian berikutnya. + diff --git a/client/android/app/src/main/res/values-it/strings_native.xml b/client/android/app/src/main/res/values-it/strings_native.xml new file mode 100644 index 000000000..699802d94 --- /dev/null +++ b/client/android/app/src/main/res/values-it/strings_native.xml @@ -0,0 +1,59 @@ + + + + Viaggio + Conta i giorni al prossimo viaggio e durante il viaggio mostra la giornata e cosa viene dopo. + Oggi + Il programma del giorno come linea del tempo, con il meteo e la prossima tappa. + Prenotazioni + I tuoi prossimi voli, treni, hotel e tavoli, e quando sono. + Volo + Il tuo prossimo volo in tempo reale: conto alla rovescia per la partenza, l’aereo in viaggio, ritardo e arrivo. + Da fare + Cosa manca ancora per il viaggio e a che punto è la valigia. + Bagagli + Quanto sono piene le borse, il loro peso e cosa manca ancora. + Mappa del mondo + I paesi in cui sei stato, illuminati sulla mappa. + Gruppo di viaggio + Chi viene, gli ultimi messaggi e il sondaggio aperto. + Scegli viaggio + Il viaggio mostrato da questo widget. + Viaggio + Automatico + Lo stesso viaggio della dashboard + Aggiungi a TREK + Annulla + Chiudi + Viaggio + Apri TREK una volta e qui compariranno i tuoi viaggi. + TREK legge la prenotazione e la aggiunge al viaggio. + Scegli dopo + Aggiungi + Aggiungi a %1$s + Aggiunto + Lettura… + Questo file è troppo grande da importare. + TREK non può importare questo contenuto. + Impossibile passarlo a TREK. Riprova. + In corso + Passato + Domani + Tra %1$d giorni + Pass di Wallet + PDF + E-mail + Pagina web + Testo + Foto + File + Apri TREK una volta e qui compariranno i tuoi viaggi. + Chat del viaggio + Novità del viaggio + Inviti e condivisioni + Generali + Giorno di viaggio + Nuova notifica + La giornata di un viaggio in corso e la prossima tappa. + diff --git a/client/android/app/src/main/res/values-iw/strings_native.xml b/client/android/app/src/main/res/values-iw/strings_native.xml new file mode 100644 index 000000000..87a83b3aa --- /dev/null +++ b/client/android/app/src/main/res/values-iw/strings_native.xml @@ -0,0 +1,59 @@ + + + + טיול + סופר את הימים עד הטיול הבא, ובמהלכו מציג את היום ואת מה שבא אחריו. + היום + תוכנית היום כציר זמן, עם מזג האוויר והעצירה הבאה. + הזמנות + הטיסות, הרכבות, המלונות והשולחנות הבאים שלך, ומתי הם. + טיסה + הטיסה הבאה שלך בזמן אמת: ספירה לאחור עד ההמראה, המטוס בדרך, עיכוב והגעה. + משימות + מה עוד פתוח לטיול וכמה התקדמה האריזה. + אריזה + כמה מלאים התיקים, המשקל שלהם ומה עוד חסר. + מפת העולם + המדינות שביקרת בהן, זוהרות על המפה. + קבוצת הטיול + מי מצטרף, ההודעות האחרונות והסקר הפתוח. + בחירת טיול + הטיול שהווידג׳ט הזה מציג. + טיול + אוטומטי + אותו טיול כמו בלוח הבקרה + הוספה ל-TREK + ביטול + סגירה + טיול + פתחו את TREK פעם אחת והטיולים שלכם יופיעו כאן. + TREK קורא את ההזמנה ומוסיף אותה לטיול. + לבחור אחר כך + הוספה + הוספה אל %1$s + נוסף + קורא… + הקובץ גדול מדי לייבוא. + TREK לא יכול לייבא את זה. + לא ניתן היה להעביר את זה ל-TREK. אנא נסו שוב. + עכשיו + עבר + מחר + בעוד %1$d ימים + כרטיס Wallet + PDF + דוא״ל + דף אינטרנט + טקסט + תמונה + קובץ + פתחו את TREK פעם אחת והטיולים שלכם יופיעו כאן. + צ׳אט הטיול + עדכוני הטיול + הזמנות ושיתופים + כללי + יום טיול + התראה חדשה + היום של טיול פעיל והעצירה הבאה שלו. + diff --git a/client/android/app/src/main/res/values-ja/strings_native.xml b/client/android/app/src/main/res/values-ja/strings_native.xml new file mode 100644 index 000000000..dd5b3a1b9 --- /dev/null +++ b/client/android/app/src/main/res/values-ja/strings_native.xml @@ -0,0 +1,59 @@ + + + + 旅行 + 次の旅行までをカウントダウンし、旅行中はその日の予定と次の行き先を表示します。 + 今日 + 今日の予定をタイムラインで、天気と次の予定とともに表示します。 + 予約 + 次のフライト、列車、ホテル、レストランとその日時。 + フライト + 次のフライトをライブで:出発までのカウントダウン、飛行中の機体、遅延と到着。 + やること + 旅行のために残っていることと、荷造りの進み具合。 + 持ち物 + バッグの詰め具合と重さ、まだ足りないもの。 + 世界地図 + 訪れた国が地図上で光ります。 + 旅行グループ + 一緒に行くメンバー、最新のメッセージ、受付中の投票。 + 旅行を選択 + このウィジェットに表示する旅行。 + 旅行 + 自動 + ダッシュボードと同じ旅行 + TREKに追加 + キャンセル + 閉じる + 旅行 + 一度TREKを開くと、ここに旅行が表示されます。 + TREKが予約を読み取り、旅行に追加します。 + あとで選ぶ + 追加 + %1$sに追加 + 追加しました + 読み込み中… + このファイルは大きすぎて読み込めません。 + TREKではこれを読み込めません。 + TREKに渡せませんでした。もう一度お試しください。 + 旅行中 + 終了 + 明日 + %1$d日後 + Walletパス + PDF + メール + Webページ + テキスト + 写真 + ファイル + 一度TREKを開くと、ここに旅行が表示されます。 + 旅行チャット + 旅行の更新 + 招待と共有 + 一般 + 旅行日 + 新しい通知 + 進行中の旅行の一日と次の立ち寄り先。 + diff --git a/client/android/app/src/main/res/values-ko/strings_native.xml b/client/android/app/src/main/res/values-ko/strings_native.xml new file mode 100644 index 000000000..a58e2e220 --- /dev/null +++ b/client/android/app/src/main/res/values-ko/strings_native.xml @@ -0,0 +1,59 @@ + + + + 여행 + 다음 여행까지 남은 날을 세고, 여행 중에는 오늘과 다음 일정을 보여 줍니다. + 오늘 + 오늘 일정을 타임라인으로, 날씨와 다음 장소와 함께 보여 줍니다. + 예약 + 다가오는 항공편, 기차, 호텔, 식당과 그 시간. + 항공편 + 다음 항공편을 실시간으로: 출발 카운트다운, 비행 중인 항공기, 지연과 도착. + 할 일 + 여행을 위해 남은 일과 짐 싸기 진행 상황. + 짐 싸기 + 가방이 얼마나 찼는지, 무게, 아직 빠진 것. + 세계 지도 + 다녀온 나라가 지도 위에서 빛납니다. + 여행 그룹 + 함께 가는 사람, 최근 메시지, 진행 중인 투표. + 여행 선택 + 이 위젯에 표시할 여행. + 여행 + 자동 + 대시보드와 같은 여행 + TREK에 추가 + 취소 + 닫기 + 여행 + TREK을 한 번 열면 여기에 여행이 표시됩니다. + TREK이 예약을 읽고 여행에 추가합니다. + 나중에 선택 + 추가 + %1$s에 추가 + 추가됨 + 읽는 중… + 이 파일은 가져오기에는 너무 큽니다. + TREK에서 가져올 수 없는 항목입니다. + TREK에 전달하지 못했습니다. 다시 시도하세요. + 진행 중 + 지난 여행 + 내일 + %1$d일 후 + Wallet 패스 + PDF + 이메일 + 웹 페이지 + 텍스트 + 사진 + 파일 + TREK을 한 번 열면 여기에 여행이 표시됩니다. + 여행 채팅 + 여행 소식 + 초대 및 공유 + 일반 + 여행일 + 새 알림 + 진행 중인 여행의 하루와 다음 장소. + diff --git a/client/android/app/src/main/res/values-nl/strings_native.xml b/client/android/app/src/main/res/values-nl/strings_native.xml new file mode 100644 index 000000000..b2e656f29 --- /dev/null +++ b/client/android/app/src/main/res/values-nl/strings_native.xml @@ -0,0 +1,59 @@ + + + + Reis + Telt af naar je volgende reis en toont onderweg de dag en wat er hierna komt. + Vandaag + Het dagplan als tijdlijn, met het weer en de volgende stop. + Boekingen + Je volgende vluchten, treinen, hotels en tafels, en wanneer ze zijn. + Vlucht + Je volgende vlucht live: aftellen tot vertrek, het toestel onderweg, vertraging en aankomst. + Taken + Wat er nog openstaat voor de reis en hoe ver het inpakken is. + Bagage + Hoe vol de tassen zijn, hun gewicht en wat er nog mist. + Wereldkaart + De landen waar je bent geweest, oplichtend op de kaart. + Reisgezelschap + Wie er meegaat, de nieuwste berichten en de open peiling. + Reis kiezen + De reis die deze widget toont. + Reis + Automatisch + Dezelfde reis als het dashboard + Toevoegen aan TREK + Annuleer + Sluit + Reis + Open TREK één keer, dan verschijnen je reizen hier. + TREK leest de boeking en zet hem in de reis. + Later kiezen + Toevoegen + Toevoegen aan %1$s + Toegevoegd + Lezen… + Dit bestand is te groot om te importeren. + Dit kan TREK niet importeren. + Dit kon niet aan TREK worden doorgegeven. Probeer het opnieuw. + Nu + Voorbij + Morgen + Over %1$d dagen + Wallet-pas + PDF + E-mail + Webpagina + Tekst + Foto + Bestand + Open TREK één keer, dan verschijnen je reizen hier. + Reischat + Reisupdates + Uitnodigingen en delen + Algemeen + Reisdag + Nieuwe melding + De dag van een lopende reis en de volgende stop. + diff --git a/client/android/app/src/main/res/values-pl/strings_native.xml b/client/android/app/src/main/res/values-pl/strings_native.xml new file mode 100644 index 000000000..943e5996c --- /dev/null +++ b/client/android/app/src/main/res/values-pl/strings_native.xml @@ -0,0 +1,59 @@ + + + + Podróż + Odlicza dni do następnej podróży, a w trakcie pokazuje dzień i to, co dalej. + Dziś + Plan dnia jako oś czasu, z pogodą i kolejnym przystankiem. + Rezerwacje + Twoje najbliższe loty, pociągi, hotele i stoliki oraz ich terminy. + Lot + Twój następny lot na żywo: odliczanie do odlotu, samolot w drodze, opóźnienie i przylot. + Zadania + Co jeszcze zostało do zrobienia przed podróżą i jak idzie pakowanie. + Pakowanie + Jak pełne są torby, ich waga i czego jeszcze brakuje. + Mapa świata + Kraje, w których byłeś, świecące na mapie. + Grupa podróży + Kto jedzie, najnowsze wiadomości i otwarta ankieta. + Wybierz podróż + Podróż, którą pokazuje ten widżet. + Podróż + Automatycznie + Ta sama podróż co na pulpicie + Dodaj do TREK + Anuluj + Zamknij + Podróż + Otwórz TREK raz, a Twoje podróże pojawią się tutaj. + TREK odczyta rezerwację i doda ją do podróży. + Wybierz później + Dodaj + Dodaj do %1$s + Dodano + Odczytywanie… + Ten plik jest za duży do zaimportowania. + TREK nie może tego zaimportować. + Nie udało się przekazać tego do TREK. Spróbuj ponownie. + Teraz + Minęła + Jutro + Za %1$d dni + Karta Wallet + PDF + E-mail + Strona + Tekst + Zdjęcie + Plik + Otwórz TREK raz, a Twoje podróże pojawią się tutaj. + Czat podróży + Nowości o podróży + Zaproszenia i udostępnienia + Ogólne + Dzień podróży + Nowe powiadomienie + Dzień trwającej podróży i jej następny przystanek. + diff --git a/client/android/app/src/main/res/values-pt-rBR/strings_native.xml b/client/android/app/src/main/res/values-pt-rBR/strings_native.xml new file mode 100644 index 000000000..9467ff568 --- /dev/null +++ b/client/android/app/src/main/res/values-pt-rBR/strings_native.xml @@ -0,0 +1,59 @@ + + + + Viagem + Conta os dias até a próxima viagem e, durante ela, mostra o dia e o que vem a seguir. + Hoje + O plano do dia como linha do tempo, com o clima e a próxima parada. + Reservas + Seus próximos voos, trens, hotéis e mesas, e quando acontecem. + Voo + Seu próximo voo ao vivo: contagem regressiva para a partida, o avião a caminho, atraso e chegada. + Tarefas + O que ainda falta para a viagem e quanto da mala já está pronto. + Bagagem + Quão cheias estão as malas, o peso e o que ainda falta. + Mapa-múndi + Os países em que você esteve, brilhando no mapa. + Grupo de viagem + Quem vai junto, as mensagens recentes e a votação aberta. + Escolher viagem + A viagem que este widget mostra. + Viagem + Automático + A mesma viagem do painel + Adicionar ao TREK + Cancelar + Fechar + Viagem + Abra o TREK uma vez e suas viagens aparecerão aqui. + O TREK lê a reserva e a adiciona à viagem. + Escolher depois + Adicionar + Adicionar a %1$s + Adicionado + Lendo… + Este arquivo é grande demais para importar. + O TREK não consegue importar isto. + Não foi possível passar isto ao TREK. Tente novamente. + Agora + Passada + Amanhã + Em %1$d dias + Passe do Wallet + PDF + E-mail + Página web + Texto + Foto + Arquivo + Abra o TREK uma vez e suas viagens aparecerão aqui. + Chat da viagem + Novidades da viagem + Convites e compartilhamentos + Geral + Dia de viagem + Nova notificação + O dia de uma viagem em andamento e sua próxima parada. + diff --git a/client/android/app/src/main/res/values-ru/strings_native.xml b/client/android/app/src/main/res/values-ru/strings_native.xml new file mode 100644 index 000000000..c6ff959f8 --- /dev/null +++ b/client/android/app/src/main/res/values-ru/strings_native.xml @@ -0,0 +1,59 @@ + + + + Поездка + Отсчитывает дни до следующей поездки, а в пути показывает день и что дальше. + Сегодня + План дня в виде ленты времени, с погодой и следующей остановкой. + Бронирования + Ближайшие рейсы, поезда, отели и столики и когда они. + Рейс + Ваш следующий рейс в реальном времени: отсчёт до вылета, самолёт в пути, задержка и прибытие. + Задачи + Что ещё осталось сделать к поездке и как идут сборы. + Сборы + Насколько заполнены сумки, их вес и чего ещё не хватает. + Карта мира + Страны, где вы были, светятся на карте. + Группа поездки + Кто едет, последние сообщения и открытый опрос. + Выбрать поездку + Поездка, которую показывает этот виджет. + Поездка + Автоматически + Та же поездка, что и на главной + Добавить в TREK + Отменить + Закрыть + Поездка + Откройте TREK один раз, и ваши поездки появятся здесь. + TREK прочитает бронь и добавит её в поездку. + Выбрать позже + Добавить + Добавить в «%1$s» + Добавлено + Чтение… + Файл слишком большой для импорта. + TREK не может это импортировать. + Не удалось передать это в TREK. Повторите попытку. + Сейчас + Прошла + Завтра + Через %1$d дн. + Карта Wallet + PDF + Письмо + Веб-страница + Текст + Фото + Файл + Откройте TREK один раз, и ваши поездки появятся здесь. + Чат поездки + Новости поездки + Приглашения и доступ + Общие + День поездки + Новое уведомление + День текущей поездки и следующая остановка. + diff --git a/client/android/app/src/main/res/values-sk/strings_native.xml b/client/android/app/src/main/res/values-sk/strings_native.xml new file mode 100644 index 000000000..fa0d320a6 --- /dev/null +++ b/client/android/app/src/main/res/values-sk/strings_native.xml @@ -0,0 +1,59 @@ + + + + Cesta + Odpočítava dni do ďalšej cesty a počas nej ukazuje deň a čo príde ďalej. + Dnes + Plán dňa ako časová os, s počasím a ďalšou zastávkou. + Rezervácie + Tvoje ďalšie lety, vlaky, hotely a stoly a kedy ťa čakajú. + Let + Tvoj ďalší let naživo: odpočet do odletu, lietadlo na ceste, meškanie a prílet. + Úlohy + Čo ešte zostáva na cestu a ako ďaleko je balenie. + Balenie + Aké plné sú tašky, ich váha a čo ešte chýba. + Mapa sveta + Krajiny, kde si bol, žiariace na mape. + Cestovná skupina + Kto ide s tebou, najnovšie správy a otvorené hlasovanie. + Vybrať cestu + Cesta, ktorú zobrazuje tento widget. + Cesta + Automaticky + Rovnaká cesta ako na nástenke + Pridať do TREK + Zrušiť + Zavrieť + Cesta + Raz otvorte TREK a vaše cesty sa zobrazia tu. + TREK prečíta rezerváciu a pridá ju k ceste. + Vybrať neskôr + Pridať + Pridať do %1$s + Pridané + Načítava sa… + Tento súbor je na import príliš veľký. + Toto TREK nevie importovať. + Nepodarilo sa to odovzdať do TREK. Skúste to znova. + Teraz + Prebehla + Zajtra + O %1$d dní + Karta Wallet + PDF + E-mail + Webová stránka + Text + Fotka + Súbor + Raz otvorte TREK a vaše cesty sa zobrazia tu. + Chat výletu + Novinky z výletu + Pozvánky a zdieľania + Všeobecné + Cestovný deň + Nové upozornenie + Deň prebiehajúceho výletu a jeho ďalšia zastávka. + diff --git a/client/android/app/src/main/res/values-sv/strings_native.xml b/client/android/app/src/main/res/values-sv/strings_native.xml new file mode 100644 index 000000000..a0cdecb1f --- /dev/null +++ b/client/android/app/src/main/res/values-sv/strings_native.xml @@ -0,0 +1,59 @@ + + + + Resa + Räknar ner till nästa resa och visar under resan dagen och vad som kommer härnäst. + Idag + Dagens plan som tidslinje, med vädret och nästa stopp. + Bokningar + Dina nästa flyg, tåg, hotell och bord, och när de är. + Flyg + Ditt nästa flyg live: nedräkning till avgång, planet på väg, försening och ankomst. + Att göra + Vad som återstår inför resan och hur långt packningen har kommit. + Packning + Hur fulla väskorna är, deras vikt och vad som fortfarande saknas. + Världskarta + Länderna du har besökt, lysande på kartan. + Resesällskap + Vem som följer med, de senaste meddelandena och den öppna omröstningen. + Välj resa + Resan som den här widgeten visar. + Resa + Automatiskt + Samma resa som på startsidan + Lägg till i TREK + Avbryt + Stäng + Resa + Öppna TREK en gång så visas dina resor här. + TREK läser bokningen och lägger till den i resan. + Välj senare + Lägg till + Lägg till i %1$s + Tillagd + Läser… + Filen är för stor för att importeras. + Det här kan TREK inte importera. + Det gick inte att lämna över till TREK. Försök igen. + Nu + Förbi + I morgon + Om %1$d dagar + Wallet-kort + PDF + Mejl + Webbsida + Text + Foto + Fil + Öppna TREK en gång så visas dina resor här. + Resechatt + Nytt om resan + Inbjudningar och delningar + Allmänt + Resdag + Ny avisering + Dagen för en pågående resa och nästa stopp. + diff --git a/client/android/app/src/main/res/values-th/strings_native.xml b/client/android/app/src/main/res/values-th/strings_native.xml new file mode 100644 index 000000000..ed6c9320b --- /dev/null +++ b/client/android/app/src/main/res/values-th/strings_native.xml @@ -0,0 +1,59 @@ + + + + ทริป + นับถอยหลังสู่ทริปถัดไป และระหว่างทริปแสดงวันนี้และสิ่งที่จะตามมา + วันนี้ + แผนของวันนี้เป็นไทม์ไลน์ พร้อมสภาพอากาศและจุดหมายถัดไป + การจอง + เที่ยวบิน รถไฟ โรงแรม และร้านอาหารถัดไปของคุณ และเวลาของแต่ละรายการ + เที่ยวบิน + เที่ยวบินถัดไปแบบสด: นับถอยหลังถึงเวลาออกเดินทาง เครื่องบินระหว่างทาง ความล่าช้า และเวลาถึง + สิ่งที่ต้องทำ + สิ่งที่ยังค้างอยู่สำหรับทริป และความคืบหน้าการจัดกระเป๋า + จัดกระเป๋า + กระเป๋าเต็มแค่ไหน น้ำหนัก และอะไรที่ยังขาด + แผนที่โลก + ประเทศที่คุณเคยไป ส่องแสงบนแผนที่ + กลุ่มเดินทาง + ใครไปด้วย ข้อความล่าสุด และโหวตที่เปิดอยู่ + เลือกทริป + ทริปที่วิดเจ็ตนี้แสดง + ทริป + อัตโนมัติ + ทริปเดียวกับแดชบอร์ด + เพิ่มลงใน TREK + ยกเลิก + ปิด + ทริป + เปิด TREK หนึ่งครั้ง แล้วทริปของคุณจะแสดงที่นี่ + TREK จะอ่านการจองและเพิ่มลงในทริป + เลือกภายหลัง + เพิ่ม + เพิ่มลงใน %1$s + เพิ่มแล้ว + กำลังอ่าน… + ไฟล์นี้ใหญ่เกินไปสำหรับการนำเข้า + TREK นำเข้ารายการนี้ไม่ได้ + ส่งต่อให้ TREK ไม่สำเร็จ โปรดลองอีกครั้ง + ตอนนี้ + ผ่านไปแล้ว + พรุ่งนี้ + อีก %1$d วัน + บัตร Wallet + PDF + อีเมล + หน้าเว็บ + ข้อความ + รูปภาพ + ไฟล์ + เปิด TREK หนึ่งครั้ง แล้วทริปของคุณจะแสดงที่นี่ + แชทการเดินทาง + อัปเดตการเดินทาง + คำเชิญและการแชร์ + ทั่วไป + วันเดินทาง + การแจ้งเตือนใหม่ + วันของทริปที่กำลังดำเนินอยู่และจุดหมายถัดไป + diff --git a/client/android/app/src/main/res/values-tr/strings_native.xml b/client/android/app/src/main/res/values-tr/strings_native.xml new file mode 100644 index 000000000..3315a7c94 --- /dev/null +++ b/client/android/app/src/main/res/values-tr/strings_native.xml @@ -0,0 +1,59 @@ + + + + Seyahat + Sonraki seyahate kalan günleri sayar, yolculukta günü ve sırada ne olduğunu gösterir. + Bugün + Günün planı zaman çizelgesi olarak, hava durumu ve sonraki durakla. + Rezervasyonlar + Sıradaki uçuşların, trenlerin, otellerin ve masaların, ne zaman oldukları ile. + Uçuş + Bir sonraki uçuşun canlı: kalkışa geri sayım, yoldaki uçak, gecikme ve varış. + Yapılacaklar + Seyahat için hâlâ açık olanlar ve bavulun ne durumda olduğu. + Bavul + Çantaların ne kadar dolu olduğu, ağırlıkları ve eksikler. + Dünya haritası + Bulunduğun ülkeler haritada parlıyor. + Seyahat grubu + Kimler geliyor, son mesajlar ve açık anket. + Seyahat seç + Bu widget\'ın gösterdiği seyahat. + Seyahat + Otomatik + Paneldeki seyahatin aynısı + TREK’e ekle + Vazgeç + Kapat + Seyahat + TREK’i bir kez açın, seyahatleriniz burada görünür. + TREK rezervasyonu okur ve seyahate ekler. + Sonra seç + Ekle + %1$s seyahatine ekle + Eklendi + Okunuyor… + Bu dosya içe aktarmak için çok büyük. + TREK bunu içe aktaramaz. + Bu TREK’e aktarılamadı. Lütfen tekrar deneyin. + Şimdi + Geçti + Yarın + %1$d gün sonra + Wallet kartı + PDF + E-posta + Web sayfası + Metin + Fotoğraf + Dosya + TREK’i bir kez açın, seyahatleriniz burada görünür. + Seyahat sohbeti + Seyahat güncellemeleri + Davetler ve paylaşımlar + Genel + Seyahat günü + Yeni bildirim + Süren bir seyahatin günü ve sonraki durağı. + diff --git a/client/android/app/src/main/res/values-uk/strings_native.xml b/client/android/app/src/main/res/values-uk/strings_native.xml new file mode 100644 index 000000000..ab1675b1f --- /dev/null +++ b/client/android/app/src/main/res/values-uk/strings_native.xml @@ -0,0 +1,59 @@ + + + + Подорож + Відлічує дні до наступної подорожі, а в дорозі показує день і що далі. + Сьогодні + План дня у вигляді стрічки часу, з погодою і наступною зупинкою. + Бронювання + Найближчі рейси, поїзди, готелі й столики та коли вони. + Рейс + Ваш наступний рейс наживо: відлік до вильоту, літак у дорозі, затримка й прибуття. + Завдання + Що ще лишилося зробити до подорожі і як просувається пакування. + Пакування + Наскільки заповнені сумки, їхня вага і чого ще бракує. + Мапа світу + Країни, де ви були, світяться на мапі. + Група подорожі + Хто їде, останні повідомлення і відкрите опитування. + Вибрати подорож + Подорож, яку показує цей віджет. + Подорож + Автоматично + Та сама подорож, що й на панелі + Додати до TREK + Скасувати + Закрити + Подорож + Відкрийте TREK один раз, і ваші подорожі з’являться тут. + TREK прочитає бронювання й додасть його до подорожі. + Вибрати пізніше + Додати + Додати до «%1$s» + Додано + Читання… + Файл завеликий для імпорту. + TREK не може це імпортувати. + Не вдалося передати це до TREK. Повторіть спробу. + Зараз + Минула + Завтра + Через %1$d дн. + Картка Wallet + PDF + Лист + Вебсторінка + Текст + Фото + Файл + Відкрийте TREK один раз, і ваші подорожі з’являться тут. + Чат подорожі + Новини подорожі + Запрошення та доступ + Загальні + День подорожі + Нове сповіщення + День поточної подорожі та наступна зупинка. + diff --git a/client/android/app/src/main/res/values-vi/strings_native.xml b/client/android/app/src/main/res/values-vi/strings_native.xml new file mode 100644 index 000000000..ed7d17523 --- /dev/null +++ b/client/android/app/src/main/res/values-vi/strings_native.xml @@ -0,0 +1,59 @@ + + + + Chuyến đi + Đếm ngược đến chuyến đi tiếp theo, trong chuyến đi thì hiện ngày và điểm tiếp theo. + Hôm nay + Kế hoạch hôm nay dạng dòng thời gian, kèm thời tiết và điểm dừng tiếp theo. + Đặt chỗ + Các chuyến bay, tàu, khách sạn và bàn sắp tới của bạn, cùng thời gian. + Chuyến bay + Chuyến bay tiếp theo trực tiếp: đếm ngược giờ khởi hành, máy bay đang bay, độ trễ và giờ đến. + Việc cần làm + Những gì còn lại cho chuyến đi và việc soạn hành lý đã tới đâu. + Hành lý + Túi đã đầy đến đâu, cân nặng và những gì còn thiếu. + Bản đồ thế giới + Những quốc gia bạn đã đến, sáng lên trên bản đồ. + Nhóm du lịch + Ai đi cùng, tin nhắn mới nhất và cuộc bình chọn đang mở. + Chọn chuyến đi + Chuyến đi mà tiện ích này hiển thị. + Chuyến đi + Tự động + Cùng chuyến đi với bảng điều khiển + Thêm vào TREK + Hủy + Đóng + Chuyến đi + Mở TREK một lần, các chuyến đi của bạn sẽ hiện ở đây. + TREK đọc đặt chỗ và thêm vào chuyến đi. + Chọn sau + Thêm + Thêm vào %1$s + Đã thêm + Đang đọc… + Tệp này quá lớn để nhập. + TREK không thể nhập nội dung này. + Không thể chuyển sang TREK. Vui lòng thử lại. + Đang diễn ra + Đã qua + Ngày mai + Sau %1$d ngày + Thẻ Wallet + PDF + Email + Trang web + Văn bản + Ảnh + Tệp + Mở TREK một lần, các chuyến đi của bạn sẽ hiện ở đây. + Trò chuyện chuyến đi + Cập nhật chuyến đi + Lời mời và chia sẻ + Chung + Ngày đi + Thông báo mới + Ngày của chuyến đi đang diễn ra và điểm dừng tiếp theo. + diff --git a/client/android/app/src/main/res/values/colors.xml b/client/android/app/src/main/res/values/colors.xml new file mode 100644 index 000000000..e7073645c --- /dev/null +++ b/client/android/app/src/main/res/values/colors.xml @@ -0,0 +1,7 @@ + + + + #4A7DDB + + #4A7DDB + diff --git a/client/android/app/src/main/res/values/firebase.xml b/client/android/app/src/main/res/values/firebase.xml new file mode 100644 index 000000000..9615c5484 --- /dev/null +++ b/client/android/app/src/main/res/values/firebase.xml @@ -0,0 +1,13 @@ + + + + 1:1074454522965:android:3ff2fe270a27a73051b8dc + 1074454522965 + AIzaSyB2VYXmZ90BZuksHhHR_n2W8naNE_vJAJA + AIzaSyB2VYXmZ90BZuksHhHR_n2W8naNE_vJAJA + trek-9392e + trek-9392e.firebasestorage.app + diff --git a/client/android/app/src/main/res/values/ic_launcher_background.xml b/client/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 000000000..c96e7f892 --- /dev/null +++ b/client/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,5 @@ + + + #09090B + #09090B + diff --git a/client/android/app/src/main/res/values/strings.xml b/client/android/app/src/main/res/values/strings.xml new file mode 100644 index 000000000..da857069a --- /dev/null +++ b/client/android/app/src/main/res/values/strings.xml @@ -0,0 +1,8 @@ + + + TREK + TREK + com.liketrek.trek + com.liketrek.trek + TREK + diff --git a/client/android/app/src/main/res/values/strings_native.xml b/client/android/app/src/main/res/values/strings_native.xml new file mode 100644 index 000000000..3a1650b30 --- /dev/null +++ b/client/android/app/src/main/res/values/strings_native.xml @@ -0,0 +1,59 @@ + + + + Trip + Counts down to your next trip, then shows the day and what comes next. + Today + Today\'s plan as a timeline, with the weather and what is next. + Bookings + Your next flights, trains, hotels and tables, and when they are due. + Flight + Your next flight live: departure countdown, the aircraft on its way, delay and arrival. + To-dos + What is still open for the trip, and how far the packing has come. + Packing + How full the bags are, their weight, and what is still missing. + World map + The countries you have been to, glowing on the map. + Travel group + Who comes along, the latest messages and the open poll. + Choose trip + The trip this widget shows. + Trip + Automatic + Same trip as the dashboard + Add to TREK + Cancel + Close + Trip + Open TREK once and your trips show up here. + TREK reads the booking and adds it to the trip. + Choose later + Add + Add to %1$s + Added + Reading… + This file is too large to import. + TREK cannot import this. + This could not be handed to TREK. Please try again. + Now + Past + Tomorrow + In %1$d days + Wallet pass + PDF + Email + Web page + Text + Photo + File + Open TREK once and your trips show up here. + Trip chat + Trip updates + Invitations and shares + General + Travel day + New notification + The day of a running trip and its next stop. + diff --git a/client/android/app/src/main/res/values/styles.xml b/client/android/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..7a61ed65a --- /dev/null +++ b/client/android/app/src/main/res/values/styles.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/client/android/app/src/main/res/xml/file_paths.xml b/client/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 000000000..63d8bf279 --- /dev/null +++ b/client/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/client/android/app/src/main/res/xml/network_security_config.xml b/client/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 000000000..479404e90 --- /dev/null +++ b/client/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,30 @@ + + + + + + + + + + diff --git a/client/android/app/src/main/res/xml/shortcuts.xml b/client/android/app/src/main/res/xml/shortcuts.xml new file mode 100644 index 000000000..9e1877c80 --- /dev/null +++ b/client/android/app/src/main/res/xml/shortcuts.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/client/android/app/src/main/res/xml/widget_atlas.xml b/client/android/app/src/main/res/xml/widget_atlas.xml new file mode 100644 index 000000000..af6970388 --- /dev/null +++ b/client/android/app/src/main/res/xml/widget_atlas.xml @@ -0,0 +1,17 @@ + + + diff --git a/client/android/app/src/main/res/xml/widget_bookings.xml b/client/android/app/src/main/res/xml/widget_bookings.xml new file mode 100644 index 000000000..eff5390ee --- /dev/null +++ b/client/android/app/src/main/res/xml/widget_bookings.xml @@ -0,0 +1,19 @@ + + + diff --git a/client/android/app/src/main/res/xml/widget_collab.xml b/client/android/app/src/main/res/xml/widget_collab.xml new file mode 100644 index 000000000..dba90af5c --- /dev/null +++ b/client/android/app/src/main/res/xml/widget_collab.xml @@ -0,0 +1,19 @@ + + + diff --git a/client/android/app/src/main/res/xml/widget_flight.xml b/client/android/app/src/main/res/xml/widget_flight.xml new file mode 100644 index 000000000..26e9540de --- /dev/null +++ b/client/android/app/src/main/res/xml/widget_flight.xml @@ -0,0 +1,19 @@ + + + diff --git a/client/android/app/src/main/res/xml/widget_packing.xml b/client/android/app/src/main/res/xml/widget_packing.xml new file mode 100644 index 000000000..01d8d96c4 --- /dev/null +++ b/client/android/app/src/main/res/xml/widget_packing.xml @@ -0,0 +1,19 @@ + + + diff --git a/client/android/app/src/main/res/xml/widget_today.xml b/client/android/app/src/main/res/xml/widget_today.xml new file mode 100644 index 000000000..6402a8165 --- /dev/null +++ b/client/android/app/src/main/res/xml/widget_today.xml @@ -0,0 +1,19 @@ + + + diff --git a/client/android/app/src/main/res/xml/widget_todos.xml b/client/android/app/src/main/res/xml/widget_todos.xml new file mode 100644 index 000000000..237e7989d --- /dev/null +++ b/client/android/app/src/main/res/xml/widget_todos.xml @@ -0,0 +1,19 @@ + + + diff --git a/client/android/app/src/main/res/xml/widget_trip.xml b/client/android/app/src/main/res/xml/widget_trip.xml new file mode 100644 index 000000000..b53e4ec49 --- /dev/null +++ b/client/android/app/src/main/res/xml/widget_trip.xml @@ -0,0 +1,19 @@ + + + diff --git a/client/android/app/src/test/java/com/liketrek/trek/ClientIdentityTest.kt b/client/android/app/src/test/java/com/liketrek/trek/ClientIdentityTest.kt new file mode 100644 index 000000000..ad4784e33 --- /dev/null +++ b/client/android/app/src/test/java/com/liketrek/trek/ClientIdentityTest.kt @@ -0,0 +1,89 @@ +package com.liketrek.trek + +import com.liketrek.trek.clientcert.ClientCertWatch +import com.liketrek.trek.clientcert.TrekClientIdentity +import com.liketrek.trek.clientcert.TrekClientIdentity.Failure +import java.util.Date +import javax.security.auth.x500.X500Principal +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** + * Reading a client certificate file (TrekClientIdentity.read) and the rule for + * which server sees it. The files in test/resources/clientcert are test-only: + * a throwaway CA, password "trek-test". valid.p12 has OpenSSL 3's default + * encryption (AES-256, PBKDF2), valid-legacy.p12 the older RC2/3DES one that + * many routers and NAS systems still export. + */ +class ClientIdentityTest { + private val password = "trek-test".toCharArray() + private val inside = Date(1_800_000_000_000L) // 2027-01-15, inside every valid test certificate + + private fun file(name: String): ByteArray = + requireNotNull(javaClass.classLoader?.getResourceAsStream("clientcert/$name")) { name }.use { it.readBytes() } + + private fun failure(name: String, pass: CharArray = password, now: Date = inside): Failure { + try { + TrekClientIdentity.read(file(name), pass, now) + } catch (e: TrekClientIdentity.ImportException) { + return e.reason + } + fail("$name opened") + throw AssertionError() + } + + @Test + fun opensModernAndLegacyFiles() { + for (name in listOf("valid.p12", "valid-legacy.p12")) { + val identity = TrekClientIdentity.read(file(name), password, inside) + assertEquals("trek-test-valid", TrekClientIdentity.commonName(identity.chain[0].subjectX500Principal)) + assertEquals("TREK mTLS Test CA", TrekClientIdentity.commonName(identity.chain[0].issuerX500Principal)) + assertEquals("RSA", identity.key.algorithm) + } + } + + @Test + fun namesWhatIsWrongWithAFile() { + assertEquals(Failure.PASSWORD, failure("valid.p12", "wrong".toCharArray())) + assertEquals(Failure.PASSWORD, failure("valid-legacy.p12", "wrong".toCharArray())) + assertEquals(Failure.EXPIRED, failure("expired.p12")) + assertEquals(Failure.NOT_YET_VALID, failure("future.p12")) + assertEquals(Failure.NO_KEY, failure("cert-only.p12")) + try { + TrekClientIdentity.read("not a certificate".toByteArray(), password, inside) + fail("text opened") + } catch (e: TrekClientIdentity.ImportException) { + assertEquals(Failure.FORMAT, e.reason) + } + } + + @Test + fun showsTheCertificateOnlyToItsHostAndPort() { + assertTrue(TrekClientIdentity.matches("trek.example.com", 443, "Trek.Example.com", -1)) + assertTrue(TrekClientIdentity.matches("trek.example.com", 443, "trek.example.com", 443)) + assertTrue(TrekClientIdentity.matches("nas.local", 8443, "nas.local", 8443)) + assertFalse(TrekClientIdentity.matches("trek.example.com", 443, "auth.example.com", 443)) + assertFalse(TrekClientIdentity.matches("trek.example.com", 443, "trek.example.com", 8443)) + assertFalse(TrekClientIdentity.matches("nas.local", 8443, "nas.local", -1)) + assertFalse(TrekClientIdentity.matches("trek.example.com", 443, null, 443)) + } + + @Test + fun leavesForTheAddressScreenOnlyWhenTheCertificateIsWhatFails() { + assertTrue(ClientCertWatch.refused(true, 0)) // handshake broken off: nginx, Caddy, Traefik + assertTrue(ClientCertWatch.refused(true, 403)) // Cloudflare's block page + assertTrue(ClientCertWatch.refused(true, 400)) // nginx without a valid certificate + assertFalse(ClientCertWatch.refused(true, 200)) // asks, but lets everyone in + assertFalse(ClientCertWatch.refused(true, 502)) // TREK restarting behind the proxy + assertFalse(ClientCertWatch.refused(false, 0)) // simply offline + } + + @Test + fun readsTheCommonNameOrFallsBackToTheWholeName() { + assertEquals("Phone, home", TrekClientIdentity.commonName(X500Principal("CN=Phone\\, home,O=Family"))) + assertEquals("O=Family", TrekClientIdentity.commonName(X500Principal("O=Family"))) + } +} diff --git a/client/android/app/src/test/java/com/liketrek/trek/NativeLogicTest.kt b/client/android/app/src/test/java/com/liketrek/trek/NativeLogicTest.kt new file mode 100644 index 000000000..fabac8968 --- /dev/null +++ b/client/android/app/src/test/java/com/liketrek/trek/NativeLogicTest.kt @@ -0,0 +1,193 @@ +package com.liketrek.trek + +import android.view.KeyEvent +import com.android.billingclient.api.Purchase +import com.liketrek.trek.billing.TrekBilling +import com.liketrek.trek.screen.TrekKeyCommands +import com.liketrek.trek.screen.TrekWindowLayout +import com.liketrek.trek.share.ShareHandoff +import com.liketrek.trek.share.ShareItem +import com.liketrek.trek.share.ShareLoader +import com.liketrek.trek.tiles.TrekTileStore +import java.time.LocalDate +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The native side's own decisions, apart from the views. */ +class NativeLogicTest { + @Test + fun aRedirectAwayWhileTheServerLoadsIsTakenAsItsSignIn() { + val server = "https://trek.example.com" + // Authelia in front of the page, its check let through on /api. + assertEquals("auth.example.com", SignInRedirect.learnedHost(server, "https://auth.example.com/?rd=https%3A%2F%2Ftrek.example.com%2F", true, true, false)) + assertEquals("auth.example.com:9091", SignInRedirect.learnedHost(server, "https://Auth.example.com:9091/", true, true, false)) + // A link the user follows, a frame, or anything after the server's page has shown: the browser, as before. + assertNull(SignInRedirect.learnedHost(server, "https://auth.example.com/", true, false, false)) + assertNull(SignInRedirect.learnedHost(server, "https://auth.example.com/", false, true, false)) + assertNull(SignInRedirect.learnedHost(server, "https://auth.example.com/", true, true, true)) + // The server's own host, another scheme, or a step down to plain http. + assertNull(SignInRedirect.learnedHost(server, "https://trek.example.com/login", true, true, false)) + assertNull(SignInRedirect.learnedHost(server, "intent://auth.example.com/", true, true, false)) + assertNull(SignInRedirect.learnedHost(server, "http://auth.example.com/", true, true, false)) + assertEquals("auth.lan", SignInRedirect.learnedHost("http://trek.lan:3000", "http://auth.lan/", true, true, false)) + assertNull(SignInRedirect.learnedHost(null, "https://auth.example.com/", true, true, false)) + assertTrue(SignInRedirect.onServer(server, "https://TREK.example.com/dashboard")) + assertFalse(SignInRedirect.onServer(server, "https://auth.example.com/")) + } + + @Test + fun pushesLandInTheChannelOfTheirEvent() { + assertEquals(TrekPushService.CHANNEL_CHAT, TrekPushService.channelFor("collab_message")) + assertEquals(TrekPushService.CHANNEL_TRIPS, TrekPushService.channelFor("booking_change")) + assertEquals(TrekPushService.CHANNEL_TRIPS, TrekPushService.channelFor("todo_due")) + assertEquals(TrekPushService.CHANNEL_INVITES, TrekPushService.channelFor("trip_invite")) + assertEquals(TrekPushService.CHANNEL, TrekPushService.channelFor("version_available")) + // A server too old to name the event: the general channel. + assertEquals(TrekPushService.CHANNEL, TrekPushService.channelFor(null)) + } + + @Test + fun sharedFilesAreSortedByWhatTheyAre() { + assertEquals(ShareItem.Kind.PASS to "application/vnd.apple.pkpass", ShareLoader.classify("Boarding.pkpass", "application/octet-stream")) + assertEquals(ShareItem.Kind.PDF to "application/pdf", ShareLoader.classify("ticket", "application/pdf")) + assertEquals(ShareItem.Kind.MAIL to "message/rfc822", ShareLoader.classify("Booking.eml", "application/octet-stream")) + assertEquals(ShareItem.Kind.CALENDAR to "text/calendar", ShareLoader.classify("invite.ics", "")) + assertEquals(ShareItem.Kind.IMAGE to "image/png", ShareLoader.classify("shot.png", "image/png")) + assertEquals(ShareItem.Kind.FILE to "application/zip", ShareLoader.classify("a.zip", "application/zip")) + } + + @Test + fun aSharedLinkIsFetchedOnlyWhenTheTextIsLittleMore() { + assertEquals("https://example.com/booking/1", ShareLoader.firstLink("Your booking: https://example.com/booking/1.")) + assertNull(ShareLoader.firstLink("no link here")) + assertNull(ShareLoader.firstLink("x".repeat(400) + " https://example.com/a")) + assertEquals("Hotel Kanra", ShareLoader.pageTitle(" Hotel Kanra ")) + assertEquals("hotel-kanra-kyoto", ShareLoader.slug("Hotel Kanra, Kyoto!")) + assertEquals("page", ShareLoader.slug("!!!")) + } + + @Test + fun aLinkWhosePageCannotBeReadIsHandedOverAsTheLinkItself() { + val item = ShareLoader.linkOnly("https://www.instagram.com/p/abc", null) + assertEquals("text/uri-list", item.mimeType) + assertEquals("https://www.instagram.com/p/abc", item.url) + assertEquals("https://www.instagram.com/p/abc", String(item.data)) + assertEquals("www.instagram.com", item.title) + assertEquals("Ramen place", ShareLoader.linkOnly("https://maps.app.goo.gl/x", "Ramen place").title) + } + + @Test + fun theShareSheetOffersComingTripsFirstThenRecentPastOnes() { + val today = LocalDate.of(2026, 11, 7) + fun trip(id: Long, start: String, end: String) = + ShareHandoff.Trip(id, "T$id", LocalDate.parse(start), LocalDate.parse(end), null, null) + val past = (1L..8L).map { trip(100 + it, "2026-0$it-01", "2026-0$it-05") } + val ordered = ShareHandoff.order( + listOf(trip(1, "2026-12-01", "2026-12-05"), trip(2, "2026-11-05", "2026-11-09")) + past, + today, + ) + assertEquals(listOf(2L, 1L), ordered.take(2).map { it.id }) + assertEquals(8, ordered.size) + assertEquals(108L, ordered[2].id) + } + + @Test + fun keyCommandsFollowTheUi() { + TrekKeyCommands.set( + JSONArray( + """[{"id":"search","title":"Search","input":"k","modifiers":["command"]}, + {"id":"back","title":"Back","input":"[","modifiers":["command"]}, + {"id":"close","title":"Close","input":"escape","modifiers":[]}, + {"title":"no id","input":"x"}]""", + ), + ) + assertEquals(3, TrekKeyCommands.current.size) + assertEquals("search", TrekKeyCommands.match(KeyEvent.KEYCODE_K, KeyEvent.META_CTRL_ON)?.id) + // A Mac keyboard's Command key is Meta here, and counts as Ctrl. + assertEquals("search", TrekKeyCommands.match(KeyEvent.KEYCODE_K, KeyEvent.META_META_ON)?.id) + assertNull(TrekKeyCommands.match(KeyEvent.KEYCODE_K, 0)) + assertNull(TrekKeyCommands.match(KeyEvent.KEYCODE_K, KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON)) + assertEquals("back", TrekKeyCommands.match(KeyEvent.KEYCODE_LEFT_BRACKET, KeyEvent.META_CTRL_ON)?.id) + assertEquals("close", TrekKeyCommands.match(KeyEvent.KEYCODE_ESCAPE, 0)?.id) + TrekKeyCommands.set(null) + assertEquals(0, TrekKeyCommands.current.size) + } + + @Test + fun windowSizeClassesUseAndroidsBreakpoints() { + assertEquals("compact", TrekWindowLayout.sizeClass(411f, 600f, 840f)) + assertEquals("medium", TrekWindowLayout.sizeClass(673f, 600f, 840f)) + assertEquals("expanded", TrekWindowLayout.sizeClass(1280f, 600f, 840f)) + } + + @Test + fun aRestoreTakesTheNewestActiveCloudSubscription() { + fun purchase(product: String, time: Long, state: Int) = Purchase( + JSONObject() + .put("productIds", JSONArray().put(product)) + .put("purchaseTime", time) + .put("purchaseState", state) + .put("purchaseToken", "token-$product-$time") + .toString(), + "sig", + ) + val found = TrekBilling.newest( + listOf( + purchase("cloud.start.monthly", 1000, 0), + purchase("cloud.plus.yearly", 2000, 0), + purchase("cloud.pro.yearly", 3000, 4), + purchase("other.thing", 4000, 0), + ), + "cloud.", + ) + assertEquals("token-cloud.plus.yearly-2000", found?.purchaseToken) + assertNull(TrekBilling.newest(emptyList(), "cloud.")) + } + + @Test + fun mapboxRequestsKeepTheWebViewsHeaders() { + val forwarded = TrekTileStore.forwardedHeaders( + mapOf( + "Referer" to "https://trek.example.com/", + "Origin" to "https://trek.example.com", + "User-Agent" to "Mozilla/5.0 (Linux; Android 16; wv)", + "Accept" to "application/x-protobuf", + "Accept-Encoding" to "gzip", + "Connection" to "keep-alive", + "Host" to "api.mapbox.com", + ), + ) + // A URL-restricted token is checked against the Referer, so it has to go along. + assertEquals("https://trek.example.com/", forwarded["Referer"]) + assertEquals("https://trek.example.com", forwarded["Origin"]) + assertEquals("Mozilla/5.0 (Linux; Android 16; wv)", forwarded["User-Agent"]) + assertEquals("application/x-protobuf", forwarded["Accept"]) + assertNull(forwarded["Accept-Encoding"]) + assertNull(forwarded["Connection"]) + assertNull(forwarded["Host"]) + assertEquals(emptyMap(), TrekTileStore.forwardedHeaders(null)) + } + + @Test + fun aPaymentThatClearedLaterIsTheUndeliveredOne() { + fun purchase(product: String, time: Long, acknowledged: Boolean) = Purchase( + JSONObject() + .put("productIds", JSONArray().put(product)) + .put("purchaseTime", time) + .put("purchaseState", 0) + .put("acknowledged", acknowledged) + .put("purchaseToken", "token-$time") + .toString(), + "sig", + ) + val renewed = purchase("cloud.plus.yearly", 3000, acknowledged = true) + val cleared = purchase("cloud.start.monthly", 2000, acknowledged = false) + assertEquals("token-2000", TrekBilling.undelivered(listOf(renewed, cleared), "cloud.")?.purchaseToken) + assertNull(TrekBilling.undelivered(listOf(renewed), "cloud.")) + } +} diff --git a/client/android/app/src/test/java/com/liketrek/trek/TrekOfflineShellTest.kt b/client/android/app/src/test/java/com/liketrek/trek/TrekOfflineShellTest.kt new file mode 100644 index 000000000..4671623da --- /dev/null +++ b/client/android/app/src/test/java/com/liketrek/trek/TrekOfflineShellTest.kt @@ -0,0 +1,91 @@ +package com.liketrek.trek + +import java.io.File +import java.nio.file.Files +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The stored copy of the server's UI (TrekOfflineShell), on a plain folder. */ +class TrekOfflineShellTest { + private val root: File = Files.createTempDirectory("offline-shell").toFile() + + @After + fun cleanUp() { + TrekOfflineShell.deactivate() + root.deleteRecursively() + } + + @Test + fun theCopyAnswersOnlyForTheServerItWasStartedFor() { + TrekOfflineShell.activate("https://a.example.com") + assertTrue(TrekOfflineShell.isActive()) + assertTrue(TrekOfflineShell.isActiveFor("https://a.example.com")) + // Another server picked in the same process: its pages come from the server. + assertFalse(TrekOfflineShell.isActiveFor("https://b.example.com")) + assertFalse(TrekOfflineShell.isActiveFor(null)) + // A start that reaches the server leaves the copy behind. + TrekOfflineShell.deactivate() + assertFalse(TrekOfflineShell.isActive()) + assertFalse(TrekOfflineShell.isActiveFor("https://a.example.com")) + } + + @Test + fun aRefreshCutOffHalfwayKeepsThePreviousBuildWhole() { + val server = "https://a.example.com" + val oldPage = " + + diff --git a/client/native-shell/main.ts b/client/native-shell/main.ts new file mode 100644 index 000000000..4f1324d78 --- /dev/null +++ b/client/native-shell/main.ts @@ -0,0 +1,1840 @@ +import { App } from '@capacitor/app'; +import { Capacitor, CapacitorHttp } from '@capacitor/core'; +import { Haptics, ImpactStyle, NotificationType } from '@capacitor/haptics'; +import { SplashScreen } from '@capacitor/splash-screen'; +import { StatusBar, Style } from '@capacitor/status-bar'; +import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../shared/src/auth/password-policy'; +import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape +import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate'; +import { opensSoon, refundedBeforeOpening } from '../src/native/cloudOrders'; +import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap'; +import { + APP_STORE_SUBSCRIPTIONS_URL, + AUTH_PROXY_DOCS_URL, + CLIENT_CERT_DOCS_URL, + CLOUD_TERMS_URL, + CLOUD_URL, + PLAY_SUBSCRIPTIONS_URL, + PRIVACY_URL, + STORE_TERMS_URL, +} from '../src/native/links'; +import { + certificateTargetFor, + probeDemo, + probeServer, + type ClientCertDemand, + type ProbeFailure, + type ProbeGet, +} from '../src/native/serverAddress'; +import { TrekShell, type ClientCertificateFailure } from '../src/native/trekShell'; +import { amountIn } from './amount'; +import { directionOf, pickLocale, translator } from './i18n'; +import { WELCOME_CAMERA, cameraForPlan, startScenery, type Camera, type Scenery } from './scenery'; +import './shell.css'; + +/** + * The only pages the app ships itself. They welcome someone on first start, ask + * for the TREK server they open in their browser, offer TREK Cloud to someone + * without one, and stand in when a remembered server cannot be reached. Every + * screen stands on the same landscape (scenery.ts); the plans move the camera + * through it. Everything past them is the UI the chosen server delivers. + */ + +const locale = pickLocale(navigator.languages?.length ? navigator.languages : [navigator.language]); +/** Google Play sells on Android, the App Store everywhere else: the store's own words in the legal texts. */ +const onPlay = Capacitor.getPlatform() === 'android'; +const t = translator(locale); +document.documentElement.lang = locale; +document.documentElement.dir = directionOf(locale); + +const root = document.getElementById('shell')!; +const PROBE_TIMEOUT_MS = 8000; + +const iap = getIapClient(); +/** + * Whether this build can take a payment in-app, asked once at start. Without it + * the plan picker shows the plans but offers no way to buy: the store rules + * allow no link or button that sends a buyer to the website instead. + */ +const iapReady: Promise = iap.isAvailable().catch(() => false); + +/** The subdomain suffix a cloud instance sits on, from the cloud address: `liketrek.com` → `.liketrek.com`. */ +function cloudSuffix(): string { + try { + return `.${new URL(CLOUD_URL).host}`; + } catch { + return '.liketrek.com'; + } +} + +/** JSON bodies arrive as text from the app's own request; everything else stays text. */ +function parseBody(data: unknown): unknown { + if (typeof data !== 'string') return data; + try { + return JSON.parse(data); + } catch { + return data; + } +} + +// Native HTTP rather than fetch: the probe goes to a server of the user's +// choosing, which has no reason to answer this page's origin with CORS. The +// app's own request comes first: it shows a stored client certificate and +// reports whether the server asked for one. A web preview has only Capacitor's. +const get: ProbeGet = async (url) => { + try { + const response = await TrekShell.requestServer({ url, timeoutMs: PROBE_TIMEOUT_MS }); + return { + status: response.status, + data: parseBody(response.data), + url: response.url, + headers: response.headers, + clientCert: { requested: response.certRequested, sent: response.certSent }, + }; + } catch { + const response = await CapacitorHttp.get({ url, connectTimeout: PROBE_TIMEOUT_MS, readTimeout: PROBE_TIMEOUT_MS }); + return { status: response.status, data: response.data, url: response.url, headers: response.headers }; + } +}; + +function failureMessage(reason: ProbeFailure): string { + switch (reason) { + case 'invalid': + return t('native.connect.errorInvalid'); + case 'unreachable': + return t('native.connect.errorUnreachable'); + case 'notTrek': + return t('native.connect.errorNotTrek'); + case 'authGate': + return t('native.gate.titleUnknown'); + case 'clientCert': + return t('native.cert.title'); + case 'tooOld': + return t('native.connect.errorTooOld'); + } +} + +// ── Tiny DOM + haptics helpers ────────────────────────────────────────────── +function el( + tag: K, + props: Partial & { dataset?: Record } = {}, + ...children: (Node | string)[] +): HTMLElementTagNameMap[K] { + const { dataset, ...rest } = props; + const node = document.createElement(tag); + Object.assign(node, rest); + if (dataset) for (const [k, v] of Object.entries(dataset)) node.dataset[k] = v; + node.append(...children.filter((c) => c !== null && c !== undefined)); + return node; +} + +function icon(path: string, size = 18, className?: string): SVGSVGElement { + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('width', String(size)); + svg.setAttribute('height', String(size)); + svg.setAttribute('fill', 'none'); + svg.setAttribute('stroke', 'currentColor'); + svg.setAttribute('stroke-width', '2'); + svg.setAttribute('stroke-linecap', 'round'); + svg.setAttribute('stroke-linejoin', 'round'); + svg.setAttribute('aria-hidden', 'true'); + if (className) svg.setAttribute('class', className); + const p = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + p.setAttribute('d', path); + svg.appendChild(p); + return svg; +} +const I = { + back: 'M15 18l-6-6 6-6', + globe: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20M2 12h20M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20', + image: + 'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM21 15l-5-5L5 21', + spark: 'M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z', + people: + 'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75', + shield: 'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10', + check: 'M20 6 9 17l-5-5', + lock: 'M6 11h12a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2zM8 11V8a4 4 0 0 1 8 0v3', + key: 'M7.5 20a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9zM10.7 12.3 21 2M16 7l3 3M14 9l2 2', + alert: 'M12 21.5a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19zM12 7.5v5.5M12 16.5h.01', + wifiOff: + 'M2 2l20 20M8.5 16.5a5 5 0 0 1 7 0M5 13a10 10 0 0 1 5.2-2.8M19 13a10 10 0 0 0-2.2-1.6M2 8.8a15 15 0 0 1 4.4-2.8M22 8.8A15 15 0 0 0 11 5M12 20h.01', + gate: 'M6.5 10h11a2.5 2.5 0 0 1 2.5 2.5v6a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 4 18.5v-6A2.5 2.5 0 0 1 6.5 10zM8 10V7a4 4 0 0 1 8 0v3M12 14.5V17', + cloud: 'M7 18a4.5 4.5 0 0 1-.6-8.96A6 6 0 0 1 18 9.5a4 4 0 0 1-.5 8.5z', + clock: 'M12 21.5a9.5 9.5 0 1 0 0-19 9.5 9.5 0 0 0 0 19zM12 7v5l3 2', + update: 'M12 3v12M7 10l5 5 5-5M5 21h14', + eye: 'M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z', + out: 'M7 17 17 7M9 7h8v8', +}; + +async function tap(style: ImpactStyle = ImpactStyle.Light): Promise { + try { + await Haptics.impact({ style }); + } catch { + /* web / unavailable */ + } +} +async function notify(type: NotificationType): Promise { + try { + await Haptics.notification({ type }); + } catch { + /* web / unavailable */ + } +} + +function externalLink(text: string, href: string, className?: string): HTMLAnchorElement { + return el('a', { href, target: '_blank', rel: 'noopener noreferrer', ...(className ? { className } : {}) }, text); +} + +// ── Screens ───────────────────────────────────────────────────────────────── +let current: HTMLElement | null = null; + +/** The layout with the landscape beside the content: an iPad, an unfolded phone, a phone on its side. */ +const wideLayout = matchMedia('(min-width: 900px), (orientation: landscape) and (max-height: 500px)'); + +/** + * A screen: the landscape on top (beside, on a wide screen) and the content. + * The landscape starts drawing once the screen is on the page, from `camera`. + */ +interface Screen { + node: HTMLElement; + hero: HTMLElement; + body: HTMLElement; + scenery: Scenery | null; +} + +type HeroKind = 'welcome' | 'plain' | 'tall'; +const FRAME: Record = { welcome: 376, plain: 300, tall: 320 }; + +function backButton(onBack: () => void): HTMLButtonElement { + const back = el('button', { type: 'button', className: 'back' }, icon(I.back, 20)); + back.setAttribute('aria-label', t('native.back')); + back.addEventListener('click', () => { + void tap(); + onBack(); + }); + return back; +} + +function show( + kind: HeroKind, + camera: Camera, + parts: { overlay?: Node[]; content: Node[]; back?: () => void }, + opts: { back?: boolean } = {} +): Screen { + const hero = el('div', { className: kind === 'plain' ? 'hero' : `hero ${kind}` }); + if (parts.back) hero.append(backButton(parts.back)); + hero.append(...(parts.overlay ?? [])); + const body = el('div', { className: 'body' }, ...parts.content); + const node = el('div', { className: `scr enter${opts.back ? ' reverse' : ''}` }, hero, body); + current?.remove(); + root.append(node); + current = node; + const scenery = startScenery(hero, { frame: FRAME[kind], camera, haze: kind === 'welcome' && !wideLayout.matches }); + return { node, hero, body, scenery }; +} + +/** The glass card over the landscape: what this screen is about, an address in large type. */ +interface GlassCard { + node: HTMLElement; + kicker: HTMLElement; + glyph: HTMLElement; + text: HTMLElement; + /** Shrinks the type until the whole address fits on one line. */ + fit(): void; +} +function glassCard(kicker: string, glyph: string, text: Node[]): GlassCard { + const kick = el('small', {}, kicker); + const mark = el('i', {}, icon(glyph, 16)); + const line = el('span', { className: 'url-text', dir: 'ltr' }, ...text); + const node = el('div', { className: 'card' }, kick, el('div', { className: 'url' }, mark, line)); + return { + node, + kicker: kick, + glyph: mark, + text: line, + fit() { + let size = 22; + line.style.fontSize = `${size}px`; + while (size > 13 && line.scrollWidth > line.clientWidth) { + size -= 1; + line.style.fontSize = `${size}px`; + } + }, + }; +} +function setKicker( + card: GlassCard, + text: string, + opts: { busy?: boolean; tone?: 'ok' | 'bad'; glyph?: string } = {} +): void { + card.kicker.replaceChildren(...(opts.busy ? [el('span', { className: 'spin' })] : []), text); + card.node.classList.toggle('ok', opts.tone === 'ok'); + card.node.classList.toggle('bad', opts.tone === 'bad'); + if (opts.glyph) card.glyph.replaceChildren(icon(opts.glyph, 16)); +} + +function notice(text: string): HTMLElement { + const box = el('div', { className: 'notice', role: 'alert' }); + setNotice(box, text); + return box; +} +function setNotice(box: HTMLElement, text: string): void { + box.replaceChildren(...(text ? [el('i', {}, icon(I.alert, 18)), el('span', {}, text)] : [])); +} + +function shake(field: HTMLElement): void { + void notify(NotificationType.Error); + field.classList.remove('bad'); + void field.offsetWidth; + field.classList.add('bad'); + setTimeout(() => field.classList.remove('bad'), 900); +} + +/** A field on a white card: its label above, the input, an optional badge on the card's edge. */ +function field( + label: string, + input: HTMLInputElement, + extra: { after?: Node[]; edge?: HTMLElement; below?: Node[] } = {} +): HTMLLabelElement { + return el( + 'label', + { className: 'fld' }, + el('span', { className: 'lab' }, label), + el('span', { className: 'row' }, input, ...(extra.after ?? [])), + ...(extra.edge ? [extra.edge] : []), + ...(extra.below ?? []) + ); +} + +// ── Welcome ───────────────────────────────────────────────────────────────── +function showWelcome(opts: { back?: boolean } = {}): void { + const perk = (glyph: string, title: string, sub: string) => + el('div', {}, el('i', {}, icon(glyph, 17)), el('span', {}, el('b', {}, title), el('small', {}, sub))); + + const discover = el('button', { type: 'button', className: 'cta' }, t('native.welcome.discover')); + discover.addEventListener('click', () => { + void tap(); + showPlans(); + }); + const have = el('button', { type: 'button', className: 'cta2' }, t('native.cloud.haveServer')); + have.addEventListener('click', () => { + void tap(); + showConnect(); + }); + + show( + 'welcome', + WELCOME_CAMERA, + { + overlay: [el('img', { src: logoWhite, alt: 'TREK', className: 'logo' })], + content: [ + el( + 'div', + { className: 'pad grow' }, + el('h1', {}, t('native.welcome.title')), + el('p', { className: 'lead' }, t('native.welcome.lead')), + el( + 'div', + { className: 'perks' }, + perk(I.globe, t('native.welcome.routeTitle'), t('native.welcome.routeSub')), + perk(I.people, t('native.welcome.togetherTitle'), t('native.welcome.togetherSub')), + perk(I.image, t('native.welcome.photosTitle'), t('native.welcome.photosSub')) + ), + el('div', { className: 'push' }), + el('div', { className: 'btns' }, discover, have) + ), + ], + }, + opts + ); +} + +// ── Connect (address) ─────────────────────────────────────────────────────── +/** + * `recheck`: an app update needs a newer server than the one it remembered, so + * the address screen comes back once with it filled in, says why and checks it + * right away. A server that is new enough loads again without another tap. + */ +function showConnect(prefill = '', opts: { back?: boolean; recheck?: boolean } = {}): void { + const host = el('b', { className: 'ph' }, 'trek.example.com'); + const caret = el('span', { className: 'caret', ariaHidden: 'true' }); + const card = glassCard(t('native.connect.yourTrek'), I.globe, [caret, host]); + + const input = el('input', { + type: 'url', + placeholder: t('native.connect.placeholder'), + value: prefill, + autocapitalize: 'off', + spellcheck: false, + }); + input.setAttribute('inputmode', 'url'); + input.setAttribute('autocomplete', 'url'); + // An address reads left to right in every language, Arabic too. + input.dir = 'ltr'; + // The on-screen keyboard's return key submits the address; it reads "Go", not a newline. + input.setAttribute('enterkeyhint', 'go'); + const found = el('span', { className: 'edge on', hidden: true }, icon(I.check, 12), t('native.connect.found')); + const addressField = field(t('native.connect.addressField'), input, { edge: found }); + + const error = notice(''); + const panel = el('div', { className: 'panel', role: 'alert', hidden: true }); + // The check offers a certificate when the proxy asks for one during the + // handshake. This adds one up front: for someone who knows their proxy wants + // it, and for a proxy that refuses without asking, which the check cannot tell. + const addCert = el( + 'button', + { type: 'button', className: 'side' }, + icon(I.shield, 18), + el('span', {}, t('native.connect.addCert')) + ); + const submit = el('button', { type: 'button', className: 'cta' }, t('native.connect.submit')); + const demo = el('button', { type: 'button', className: 'link' }, t('native.connect.tryDemo')); + const form = el( + 'form', + { className: 'pad form', noValidate: true }, + el('h1', { className: 'title' }, t('native.connect.title')), + el('p', { className: 'sub' }, t(opts.recheck ? 'native.connect.recheckHint' : 'native.connect.hint')), + addressField, + error, + panel, + addCert + ); + + const screen = show( + 'tall', + cameraForPlan(1), + { + back: () => showWelcome({ back: true }), + overlay: [card.node], + content: [form, el('div', { className: 'dock' }, submit, demo)], + }, + opts + ); + // The button sits in the dock at the foot of the screen, outside the form; Return in the field submits as well. + submit.addEventListener('click', () => form.requestSubmit()); + + const bare = (v: string) => + v + .trim() + .replace(/^https?:\/\//i, '') + .replace(/\/+$/, ''); + const paintHost = () => { + const h = bare(input.value); + host.textContent = h || 'trek.example.com'; + host.classList.toggle('ph', !h); + if (h) host.after(caret); + else host.before(caret); + card.fit(); + }; + const reset = () => { + setNotice(error, ''); + panel.hidden = true; + panel.replaceChildren(); + addCert.hidden = false; + found.hidden = true; + screen.node.classList.remove('compact'); + setKicker(card, t('native.connect.yourTrek'), { glyph: I.globe }); + }; + input.addEventListener('focus', () => card.node.classList.add('typing')); + input.addEventListener('blur', () => card.node.classList.remove('typing')); + input.addEventListener('input', () => { + paintHost(); + reset(); + submit.textContent = t('native.connect.submit'); + }); + paintHost(); + + // What the card says when the check fails, and its mark. + const KICKER: Partial> = { + unreachable: { labelKey: 'native.connect.kickerUnreachable', glyph: I.wifiOff }, + notTrek: { labelKey: 'native.connect.kickerNotTrek', glyph: I.alert }, + tooOld: { labelKey: 'native.connect.kickerTooOld', glyph: I.update }, + authGate: { labelKey: 'native.connect.kickerGate', glyph: I.gate }, + clientCert: { labelKey: 'native.connect.kickerCert', glyph: I.key }, + }; + const fail = (reason: ProbeFailure, gate?: AuthGate, server?: string, cert?: ClientCertDemand): void => { + void notify(NotificationType.Error); + input.disabled = false; + submit.disabled = false; + addCert.disabled = false; + submit.textContent = t('native.connect.recheck'); + const kicker = KICKER[reason]; + if (kicker) setKicker(card, t(kicker.labelKey), { tone: 'bad', glyph: kicker.glyph }); + if (reason === 'authGate' && gate && server) { + fillGatePanel(panel, gate, server); + } else if (reason === 'clientCert' && cert) { + fillCertPanel(panel, cert, () => form.requestSubmit()); + } else { + if (reason === 'invalid') shake(addressField); + setNotice(error, failureMessage(reason)); + } + // A panel with its own next step stays in view, with the room it needs; the keyboard would cover it. + const withPanel = !panel.hidden; + addCert.hidden = withPanel; + screen.node.classList.toggle('compact', withPanel); + if (!withPanel) input.focus(); + }; + + addCert.addEventListener('click', async () => { + if (submit.disabled) return; // a check is running + const target = certificateTargetFor(input.value); + if (!target) { + setNotice(error, failureMessage('invalid')); + shake(addressField); + input.focus(); + return; + } + void tap(); + setNotice(error, ''); + addCert.disabled = true; + const outcome = await importCertificate(target.host, target.port); + addCert.disabled = false; + if (outcome === 'imported') { + void notify(NotificationType.Success); + form.requestSubmit(); + } else if (outcome !== 'cancelled') { + void notify(NotificationType.Error); + setNotice(error, certFailureMessage(outcome)); + } + }); + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + if (submit.disabled) return; + void tap(ImpactStyle.Medium); + reset(); + input.disabled = true; + submit.disabled = true; + addCert.disabled = true; + input.blur(); + submit.replaceChildren(el('span', { className: 'spin' }), t('native.connect.checking')); + setKicker(card, t('native.connect.checking'), { busy: true }); + const result = await probeServer(input.value, get); + if (result.ok) { + setKicker(card, t('native.connect.connected'), { tone: 'ok', glyph: I.lock }); + found.hidden = false; + submit.textContent = t('native.connect.connected'); + await connected(result.url); + return; + } + fail(result.reason, result.gate, result.url, result.cert); + }); + + demo.addEventListener('click', () => runDemo(demo, error)); + + if (opts.recheck && prefill) form.requestSubmit(); + else if (!prefill) requestAnimationFrame(() => input.focus()); +} + +/** A small panel with a mark, a title, what to do, and the help page. */ +function panelHead(glyph: string, title: string): HTMLElement { + return el('div', { className: 'panel-head' }, el('i', {}, icon(glyph, 18)), el('b', {}, title)); +} +function helpLink(text: string, href: string): HTMLAnchorElement { + const link = externalLink(text, href, 'panel-help'); + link.append(icon(I.out, 13, 'flip')); + return link; +} + +/** + * A sign-in page of the user's own stands in front of the server (authGate.ts): + * say which one, offer to sign in to it inside the app, which keeps its session + * as a browser would, and how to let the app through instead. + */ +function fillGatePanel(panel: HTMLElement, gate: AuthGate, server: string): void { + const name = gate.kind === 'unknown' || gate.kind === 'basic' ? null : AUTH_GATE_NAMES[gate.kind]; + const title = + gate.kind === 'basic' + ? t('native.gate.titleBasic') + : name + ? t('native.gate.title', { name }) + : t('native.gate.titleUnknown'); + const children: Node[] = [panelHead(I.gate, title)]; + if (canSignInInApp(gate)) { + const signIn = el( + 'button', + { type: 'button', className: 'panel-btn' }, + name ? t('native.gate.signIn', { name }) : t('native.gate.signInGeneric') + ); + signIn.addEventListener('click', () => { + void tap(ImpactStyle.Medium); + void connected(server, gate.loginHost ? [gate.loginHost] : []); + }); + children.push( + el('p', {}, t('native.gate.hint')), + signIn, + el('p', { className: 'panel-note' }, t('native.gate.googleNote')) + ); + } else { + children.push(el('p', {}, t('native.gate.basicHint'))); + } + children.push(helpLink(t('native.gate.help'), AUTH_PROXY_DOCS_URL)); + panel.replaceChildren(...children); + panel.hidden = false; +} + +/** + * A proxy in front of the server lets only devices with a client certificate + * through (mutual TLS: Cloudflare, nginx, Caddy, Traefik). The panel offers to + * add the certificate file for it, or another one when the proxy refused the + * one shown; `retry` checks the server again once it is added. + */ +function fillCertPanel(panel: HTMLElement, cert: ClientCertDemand, retry: () => void): void { + const status = el('p', { className: 'panel-status', role: 'status' }); + const choose = el( + 'button', + { type: 'button', className: 'panel-btn' }, + cert.sent ? t('native.cert.chooseOther') : t('native.cert.choose') + ); + choose.addEventListener('click', async () => { + void tap(ImpactStyle.Medium); + choose.disabled = true; + status.textContent = ''; + const outcome = await importCertificate(cert.host, cert.port); + choose.disabled = false; + if (outcome === 'imported') { + void notify(NotificationType.Success); + retry(); + } else if (outcome !== 'cancelled') { + void notify(NotificationType.Error); + status.textContent = certFailureMessage(outcome); + } + }); + const hint = cert.sent ? t('native.cert.hintRefused') : t('native.cert.hint', { host: cert.host }); + panel.replaceChildren( + panelHead(I.key, cert.sent ? t('native.cert.titleRefused') : t('native.cert.title')), + el('p', {}, hint), + choose, + status, + helpLink(t('native.cert.help'), CLIENT_CERT_DOCS_URL) + ); + panel.hidden = false; +} + +/** Imports a certificate file for host and port: 'imported', 'cancelled', or why it failed. */ +async function importCertificate( + host: string, + port: number +): Promise<'imported' | 'cancelled' | ClientCertificateFailure> { + try { + const result = await TrekShell.importClientCertificate({ + host, + port, + labels: { + title: t('native.cert.passwordTitle'), + message: t('native.cert.passwordMessage'), + placeholder: t('native.cert.passwordPlaceholder'), + ok: t('native.cert.passwordOk'), + cancel: t('native.cert.passwordCancel'), + wrongPassword: t('native.cert.passwordWrong'), + }, + }); + if (result.result === 'failed') return result.failure ?? 'format'; + return result.result; + } catch { + return 'store'; + } +} + +function certFailureMessage(failure: ClientCertificateFailure): string { + switch (failure) { + case 'no_key': + return t('native.cert.errorNoKey'); + case 'expired': + return t('native.cert.errorExpired'); + case 'not_yet_valid': + return t('native.cert.errorNotYetValid'); + case 'store': + return t('native.cert.errorStore'); + case 'format': + return t('native.cert.errorFormat'); + } +} + +// ── Choose a plan (TREK Cloud) ────────────────────────────────────────────── +interface CloudPlan { + id: string; + name: string; + /** Absent while orders are closed: the cloud names its plans but no price leaves it then. */ + monthlyCents?: number; + yearlyCents?: number; + aiDocuments: number; + storageGb: number; +} + +function money(cents: number): string { + return new Intl.NumberFormat(locale, { style: 'currency', currency: 'EUR' }).format(cents / 100); +} +function count(n: number): string { + return new Intl.NumberFormat(locale).format(n); +} + +// A sample catalogue for the dev preview only: the cloud site is behind a gate +// during development, so its /api/plans is unreachable from a local build. Never +// used in a real build (see the import.meta.env.DEV guard below). +const SAMPLE_PLANS: CloudPlan[] = [ + { id: 'start', name: 'Start', monthlyCents: 490, yearlyCents: 4900, aiDocuments: 0, storageGb: 10 }, + { id: 'basis', name: 'Basis', monthlyCents: 790, yearlyCents: 7900, aiDocuments: 25, storageGb: 10 }, + { id: 'plus', name: 'Plus', monthlyCents: 1290, yearlyCents: 12900, aiDocuments: 100, storageGb: 25 }, + { id: 'pro', name: 'Pro', monthlyCents: 1990, yearlyCents: 19900, aiDocuments: 150, storageGb: 50 }, +]; + +interface CloudPlans { + plans: CloudPlan[]; + /** Orders are closed: only a test build may buy, and the store charges it nothing. */ + closed: boolean; +} + +async function fetchPlans(): Promise { + try { + const res = await get(`${CLOUD_URL}/api/plans`); + const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; + const body = (data ?? {}) as { plans?: CloudPlan[]; ordering?: string }; + if (Array.isArray(body.plans) && body.plans.length) + return { plans: body.plans, closed: body.ordering === 'closed' }; + } catch { + // Fall through to the preview fallback. + } + if (import.meta.env?.DEV) return { plans: SAMPLE_PLANS, closed: false }; + return null; +} + +/** + * What the plan picker can sell. With the store, a plan is offered at the price + * string the App Store gives for its product, in the buyer's currency, and only + * when the store knows that product. The fake (development, preview) sells + * every plan at the plan list's price. Without either, nothing is for sale. + */ +interface Offer { + canBuy: boolean; + storePrices: Map | null; + /** Orders are closed and this is no test build: the plans show, nothing is for sale yet. */ + opensSoon: boolean; +} + +function offerFor(offer: Offer, plan: CloudPlan, interval: 'month' | 'year'): { label: string; buyable: boolean } { + const cents = interval === 'year' ? plan.yearlyCents : plan.monthlyCents; + const ours = typeof cents === 'number' ? money(cents) : ''; + const storePrice = offer.storePrices?.get(productIdFor(plan.id, interval)); + if (offer.storePrices) return { label: storePrice ?? ours, buyable: offer.canBuy && !!storePrice }; + return { label: ours, buyable: offer.canBuy && ours !== '' }; +} + +async function loadOffer(list: CloudPlans): Promise { + const available = await iapReady; + // Closed: a real purchase is refused at the cloud, so only a test build may buy on iOS; + // Android keeps the button for the licence testers (see cloudOrders.ts). + const sandbox = list.closed && !onPlay ? await iap.isSandbox().catch(() => false) : false; + const soon = opensSoon({ available, closed: list.closed, sandbox, onPlay }); + const canBuy = available && !soon; + if (!canBuy || iap === fakeIapClient) return { canBuy, storePrices: null, opensSoon: soon }; + const ids = list.plans.flatMap((p) => [productIdFor(p.id, 'month'), productIdFor(p.id, 'year')]); + return { canBuy, storePrices: await iap.prices(ids), opensSoon: soon }; +} + +/** The plan the picker starts on and marks: the smallest one with AI documents, the one most trips want. */ +function recommendedPlan(plans: CloudPlan[]): CloudPlan | undefined { + return plans.find((p) => p.aiDocuments > 0) ?? plans[0]; +} + +/** The kind of trip each plan is for: a weekend away, a round trip, a long journey, the whole world. */ +const TRIPS: Record = { + start: { titleKey: 'native.trip.start.title', textKey: 'native.trip.start.text' }, + basis: { titleKey: 'native.trip.basis.title', textKey: 'native.trip.basis.text' }, + plus: { titleKey: 'native.trip.plus.title', textKey: 'native.trip.plus.text' }, + pro: { titleKey: 'native.trip.pro.title', textKey: 'native.trip.pro.text' }, +}; +/** A plan's trip, its title and one line; a plan the app does not know keeps its own name. */ +function tripOf(plan: CloudPlan): { title: string; text: string } { + const trip = TRIPS[plan.id]; + return trip ? { title: t(trip.titleKey), text: t(trip.textKey) } : { title: plan.name, text: '' }; +} + +function per(interval: 'month' | 'year'): string { + return interval === 'year' ? t('native.plans.perYear') : t('native.plans.perMonth'); +} + +/** The restore button of the plans on screen, which redeems a payment that cleared later. */ +let resumeRestore: (() => void) | null = null; +let watchingTransactions = false; +/** Where the camera stood on the plan chosen last, for the screens that follow it. */ +let chosenCamera: Camera = cameraForPlan(1); +/** The plan chosen last, so coming back to the plans finds it still chosen. */ +let chosenPlanId: string | null = null; +let chosenInterval: 'month' | 'year' = 'month'; + +/** + * Restoring a purchase this store account already made (a reinstall, a new + * phone). Found and redeemed: the instance it belongs to opens. Paid but never + * set up: the claim screen takes the purchase as it is, so nothing is bought twice. + */ +function restoreButton(offer: Offer, plans: CloudPlan[]): HTMLButtonElement { + const restore = el('button', { type: 'button', className: 'link' }, t('native.plans.restore')); + const say = (text: string) => { + restore.classList.add('msg'); + restore.textContent = text; + }; + restore.addEventListener('click', async () => { + void tap(); + restore.disabled = true; + say(t('native.plans.restoring')); + const purchase = await iap.restore(); + if (!purchase) { + restore.disabled = false; + say(t(onPlay ? 'native.plans.restoreNoneAndroid' : 'native.plans.restoreNone')); + return; + } + // A restore finds the instance the purchase was first redeemed for; address and email are not asked again. + const redeemed = await redeemPurchase('', '', purchase); + if (redeemed.ok && redeemed.instanceUrl) { + await iap.finish(purchase); + showProvisioning(redeemed.instanceUrl); + return; + } + // Paid but never set up (Ask to Buy approved later, the app closed mid-purchase). + const unclaimed = redeemed.code === 'email-invalid' || (redeemed.code ?? '').startsWith('slug-'); + const match = /^cloud\.([a-z0-9-]+)\.(monthly|yearly)$/.exec(purchase.productId); + const plan = match ? plans.find((p) => p.id === match[1]) : undefined; + if (unclaimed && match && plan) { + const interval = match[2] === 'yearly' ? 'year' : 'month'; + const { label } = offerFor(offer, plan, interval); + showClaim(plan, interval, label, { bought: purchase }); + return; + } + void notify(NotificationType.Error); + restore.disabled = false; + // Bought before the opening: refused, unacknowledged, and refunded by Google Play. + say( + refundedBeforeOpening(redeemed.code, onPlay) ? t('native.claim.closedRefund') : t('native.plans.restoreFailed') + ); + }); + + // A payment that was pending (cash, some carrier billing) and has cleared since: + // redeemed right away, as the restore would, before Google Play refunds it. + resumeRestore = () => { + if (!restore.disabled && restore.isConnected) restore.click(); + }; + if (!watchingTransactions) { + watchingTransactions = true; + iap.onTransaction(() => resumeRestore?.()); + } + void iap.unfinished().then((purchase) => { + if (purchase) resumeRestore?.(); + }); + return restore; +} + +function showPlans(opts: { back?: boolean } = {}): void { + let interval: 'month' | 'year' = chosenInterval; + let plans: CloudPlan[] = []; + let offer: Offer = { canBuy: false, storePrices: null, opensSoon: false }; + let selectedId: string | null = null; + + const tiers = el('div', { className: 'tiers', role: 'radiogroup', hidden: true }); + tiers.setAttribute('aria-label', t('native.plans.title')); + const title = el('h1', {}); + const text = el('p', {}); + const trip = el('div', { className: 'trip' }, title, text); + + const monthBtn = el('button', { type: 'button', role: 'radio' }, t('native.plans.monthly')); + const yearBtn = el('button', { type: 'button', role: 'radio' }, t('native.plans.yearly')); + const cycle = el( + 'div', + { className: 'cycle', role: 'radiogroup' }, + el('span', { className: 'thumb' }), + monthBtn, + yearBtn + ); + cycle.setAttribute('aria-label', t('native.plans.billing')); + // The price is figures and a currency sign: one left-to-right run, so Arabic keeps "4,90 €" whole. + const priceValue = el('b', { dir: 'ltr' }); + const pricePer = el('span', {}); + const price = el('div', { className: 'price' }, priceValue, pricePer); + const equals = el('div', { className: 'equals' }); + const pricebox = el('div', { className: 'pricebox' }, cycle, price, equals); + const specs = el('div', { className: 'specs' }); + const foot = el('div', { className: 'pad', hidden: true }); + + const loading = el('div', { className: 'loading' }, el('span', { className: 'spin' })); + const details = el('div', { className: 'stack', hidden: true }, trip, pricebox, specs); + const choose = el('button', { type: 'button', className: 'cta', hidden: true }); + const dock = el('div', { className: 'dock' }, choose); + + const screen = show( + 'plain', + chosenCamera, + { + back: () => showWelcome({ back: true }), + content: [el('div', { className: 'pad lift' }, tiers, loading, details), foot, dock], + }, + opts + ); + + const selected = (): CloudPlan | undefined => plans.find((p) => p.id === selectedId); + let shown: number | null = null; + let tween = 0; + /** The price counts to its new amount, as a figure does on a display, in the store's own format. */ + const paintPrice = (label: string, animate: boolean) => { + const amount = amountIn(label); + cancelAnimationFrame(tween); + if (!amount || shown === null || !animate) { + priceValue.textContent = label; + shown = amount ? amount.value : null; + return; + } + const from = shown; + const start = performance.now(); + const step = (now: number) => { + const k = Math.min(1, (now - start) / 420); + const e = 1 - Math.pow(1 - k, 3); + priceValue.textContent = amount.render(from + (amount.value - from) * e); + if (k < 1) tween = requestAnimationFrame(step); + }; + shown = amount.value; + tween = requestAnimationFrame(step); + }; + + const paint = (animate: boolean) => { + const plan = selected(); + if (!plan) return; + const index = plans.indexOf(plan); + tiers + .querySelectorAll('button') + .forEach((b) => b.setAttribute('aria-checked', String(b.dataset.plan === plan.id))); + monthBtn.setAttribute('aria-checked', String(interval === 'month')); + yearBtn.setAttribute('aria-checked', String(interval === 'year')); + cycle.dataset.year = String(interval === 'year'); + + const { title: tripTitle, text: tripText } = tripOf(plan); + const recommended = recommendedPlan(plans)?.id === plan.id; + title.replaceChildren( + tripTitle, + ...(recommended ? [el('span', { className: 'badge' }, t('native.plans.recommended'))] : []) + ); + text.textContent = tripText; + text.hidden = !tripText; + + const { label, buyable } = offerFor(offer, plan, interval); + // No price yet (orders not open): the plan shows without one rather than with an empty one. + price.hidden = !label; + pricePer.textContent = per(interval); + if (label) paintPrice(label, animate); + const year = offerFor(offer, plan, 'year').label; + // Without a price in either period (orders not open yet) the switch would choose between nothing. + pricebox.hidden = !label && !year; + const yearAmount = amountIn(year); + equals.textContent = + !label || !year + ? '' + : interval === 'month' + ? t('native.plans.yearlyIs', { price: year }) + : yearAmount + ? t('native.plans.monthlyIs', { price: yearAmount.render(yearAmount.value / 12) }) + : ''; + + const gb = plan.storageGb >= 1000 ? `${count(plan.storageGb / 1000)} TB` : `${count(plan.storageGb)} GB`; + const tile = (glyph: string, big: string, small: string, off = false) => + el( + 'span', + { className: off ? 'spec off' : 'spec' }, + el('i', {}, icon(glyph, 17)), + el('span', {}, el('b', {}, big), el('small', {}, small)) + ); + specs.replaceChildren( + // About 3 MB a photo, as a phone takes them: a size people can picture. + tile(I.image, gb, t('native.plans.photos', { n: count(plan.storageGb * 300) })), + plan.aiDocuments > 0 + ? tile(I.spark, t('native.plans.aiPerMonth', { n: count(plan.aiDocuments) }), t('native.plans.aiLabel')) + : tile(I.spark, t('native.plans.aiNone'), t('native.plans.aiLabel'), true), + el( + 'span', + { className: 'spec wide' }, + el('i', {}, icon(I.people, 17)), + el('span', {}, el('b', {}, t('native.plans.unlimited')), el('small', {}, t('native.plans.unlimitedSub'))), + el('em', {}, t('native.plans.inEveryPlan')) + ) + ); + + choose.hidden = !buyable; + choose.textContent = t('native.plans.choose', { trip: tripTitle }); + chosenCamera = cameraForPlan(index); + chosenPlanId = plan.id; + chosenInterval = interval; + if (animate) screen.scenery?.flyTo(chosenCamera); + }; + + monthBtn.addEventListener('click', () => { + if (interval === 'month') return; + void tap(); + interval = 'month'; + paint(true); + }); + yearBtn.addEventListener('click', () => { + if (interval === 'year') return; + void tap(); + interval = 'year'; + paint(true); + }); + + choose.addEventListener('click', async () => { + const plan = selected(); + if (!plan) return; + void tap(ImpactStyle.Medium); + // A store account with a running subscription buys nothing more: say so before the form. + choose.disabled = true; + const held = await iap.held(); + choose.disabled = false; + if (held) { + showSubscribed(); + return; + } + showClaim(plan, interval, offerFor(offer, plan, interval).label); + }); + + const load = async () => { + loading.replaceChildren(el('span', { className: 'spin' })); + loading.hidden = false; + const list = await fetchPlans(); + if (!list) { + const retry = el('button', { type: 'button', className: 'cta2' }, t('native.plans.retry')); + retry.addEventListener('click', () => { + void tap(); + void load(); + }); + loading.replaceChildren(el('div', { className: 'stack' }, notice(t('native.plans.loadError')), retry)); + return; + } + offer = await loadOffer(list); + plans = list.plans; + selectedId = plans.find((p) => p.id === chosenPlanId)?.id ?? recommendedPlan(plans)?.id ?? null; + tiers.replaceChildren( + ...plans.map((p) => { + const b = el('button', { type: 'button', role: 'radio', dataset: { plan: p.id } }, p.name); + b.addEventListener('click', () => { + if (selectedId === p.id) return; + void tap(); + selectedId = p.id; + paint(true); + }); + return b; + }) + ); + loading.hidden = true; + tiers.hidden = false; + details.hidden = false; + // The store's terms below the plans; a shop that cannot sell yet says only that. + if (offer.opensSoon || !offer.canBuy) { + foot.replaceChildren( + el('p', { className: 'legal' }, t(offer.opensSoon ? 'native.plans.closed' : 'native.plans.soon')) + ); + } else { + foot.replaceChildren( + el('p', { className: 'legal' }, t(onPlay ? 'native.plans.legalAndroid' : 'native.plans.legal')), + el( + 'div', + { className: 'legal-links' }, + externalLink(t('native.plans.ourTerms'), CLOUD_TERMS_URL), + ...(onPlay ? [] : [externalLink(t('native.plans.termsShort'), STORE_TERMS_URL)]), + externalLink(t('native.plans.privacyShort'), PRIVACY_URL) + ) + ); + dock.append(restoreButton(offer, plans)); + } + foot.hidden = false; + paint(true); + }; + void load(); +} + +// ── Claim a TREK Cloud instance (choose address, buy, provision) ──────────── +type SlugStatus = 'available' | 'taken' | 'invalid' | 'reserved' | 'error'; + +async function slugStatus(slug: string): Promise { + try { + const res = await get(`${CLOUD_URL}/api/slug/check?slug=${encodeURIComponent(slug)}`); + const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; + const status = (data as { status?: string })?.status; + if (status === 'available' || status === 'taken' || status === 'invalid' || status === 'reserved') return status; + return 'error'; + } catch { + return 'error'; + } +} + +/** + * The separate agreement on how a cloud instance differs from a self-run TREK + * (terms § 2 (1a), § 327h BGB), as the control plane words and versions it. The + * app shows the server's text, never its own, and sends back the version it showed. + */ +interface DeviationsConsent { + version: string; + text: string; +} +async function fetchConsent(): Promise { + try { + const res = await CapacitorHttp.get({ + url: `${CLOUD_URL}/api/iap/consent`, + connectTimeout: PROBE_TIMEOUT_MS, + readTimeout: PROBE_TIMEOUT_MS, + }); + const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; + const body = (data ?? {}) as { version?: unknown; deviations?: unknown }; + if (res.status !== 200 || typeof body.version !== 'string' || typeof body.deviations !== 'string') return null; + if (!body.version || !body.deviations) return null; + return { version: body.version, text: body.deviations }; + } catch { + return null; + } +} + +interface RedeemResult { + ok: boolean; + /** Set when ok: the address the app loads. */ + instanceUrl?: string; + /** Set when ok and a password was chosen: the one-time code that signs the buyer in once the instance answers. */ + welcome?: string; + /** Set when not ok: a stable refusal code. */ + code?: string; +} +async function redeemPurchase( + slug: string, + email: string, + purchase: Purchase, + password = '', + consentVersion: string | null = null +): Promise { + try { + const res = await CapacitorHttp.post({ + url: `${CLOUD_URL}/api/iap/redeem`, + headers: { 'content-type': 'application/json' }, + connectTimeout: PROBE_TIMEOUT_MS, + readTimeout: PROBE_TIMEOUT_MS, + // The language of the contract confirmation mail. + data: { + platform: purchase.platform, + productId: purchase.productId, + receipt: purchase.receipt, + slug, + email, + // Hashed by the control plane on arrival and set on the new instance; empty for a restore. + ...(password ? { password } : {}), + // Only a new contract carries the agreement; a restore finds one that already holds it. + ...(consentVersion ? { consent: { acceptedDeviations: true, version: consentVersion } } : {}), + locale, + }, + }); + const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; + const body = (data ?? {}) as { instanceUrl?: string; code?: string; welcome?: string }; + if ((res.status === 200 || res.status === 201) && typeof body.instanceUrl === 'string') { + const welcome = + typeof body.welcome === 'string' && /^[A-Za-z0-9_-]{43}$/.test(body.welcome) ? body.welcome : undefined; + return { ok: true, instanceUrl: body.instanceUrl, ...(welcome ? { welcome } : {}) }; + } + return { ok: false, code: body.code ?? 'redeem-failed' }; + } catch { + return { ok: false, code: 'redeem-failed' }; + } +} + +function showClaim( + plan: CloudPlan, + interval: 'month' | 'year', + priceLabel: string, + opts: { back?: boolean; bought?: Purchase } = {} +): void { + /** A purchase that went through but whose redeem did not: a retry redeems it again instead of buying twice. */ + let bought: Purchase | null = opts.bought ?? null; + + // The address on the glass card, written as it is typed. + const slugShown = el('b', { className: 'ph' }, t('native.claim.slugPlaceholder')); + const caret = el('span', { className: 'caret', ariaHidden: 'true' }); + const card = glassCard(t('native.claim.addressLabel'), I.lock, [caret, slugShown, el('span', {}, cloudSuffix())]); + + const slugInput = el('input', { + type: 'text', + autocapitalize: 'off', + spellcheck: false, + value: '', + placeholder: t('native.claim.slugPlaceholder'), + }); + slugInput.setAttribute('inputmode', 'url'); + slugInput.setAttribute('autocomplete', 'off'); + slugInput.setAttribute('maxlength', '40'); + slugInput.setAttribute('enterkeyhint', 'next'); + slugInput.dir = 'ltr'; + const free = el('span', { className: 'edge on', hidden: true }, icon(I.check, 12), t('native.claim.freeBadge')); + const slugNote = el('p', { className: 'note', role: 'status' }); + // "name.liketrek.com" is one address, left to right in every language. + const slugField = field(t('native.claim.addressField'), slugInput, { + after: [el('em', { dir: 'ltr' }, cloudSuffix())], + edge: free, + below: [slugNote], + }); + + const emailInput = el('input', { + type: 'email', + value: '', + autocapitalize: 'off', + spellcheck: false, + placeholder: t('native.claim.emailPlaceholder'), + }); + emailInput.setAttribute('inputmode', 'email'); + emailInput.setAttribute('autocomplete', 'email'); + emailInput.setAttribute('enterkeyhint', 'next'); + emailInput.dir = 'ltr'; + const emailField = field(t('native.claim.emailLabel'), emailInput); + + // The password for the new TREK, chosen here so the buyer lands signed in (no password by mail). + const passwordInput = el('input', { + type: 'password', + value: '', + autocapitalize: 'off', + spellcheck: false, + placeholder: t('native.claim.passwordPlaceholder'), + }); + passwordInput.setAttribute('autocomplete', 'new-password'); + passwordInput.setAttribute('enterkeyhint', 'go'); + passwordInput.setAttribute('maxlength', '128'); + passwordInput.dir = 'ltr'; + const eye = el('button', { type: 'button', className: 'eye' }, icon(I.eye, 18)); + eye.setAttribute('aria-label', t('native.claim.showPassword')); + eye.addEventListener('click', (e) => { + e.preventDefault(); + passwordInput.type = passwordInput.type === 'password' ? 'text' : 'password'; + }); + // The length on the card's edge, the other rules beneath, each ticked off as it is met. + // The number outside the words: it is always the same, and the word reads after it in every language. + const lengthRule = el('span', { className: 'edge' }, `${PASSWORD_MIN_LENGTH}+ ${t('native.claim.ruleLength')}`); + const RULES = [ + { rule: 'upper', labelKey: 'native.claim.ruleUpper' }, + { rule: 'lower', labelKey: 'native.claim.ruleLower' }, + { rule: 'digit', labelKey: 'native.claim.ruleDigit' }, + { rule: 'special', labelKey: 'native.claim.ruleSpecial' }, + ] as const; + const ruleItems = RULES.map(({ rule, labelKey }) => ({ rule, node: el('span', {}, t(labelKey)) })); + const passwordField = field(t('native.claim.passwordLabel'), passwordInput, { + after: [eye], + edge: lengthRule, + below: [el('div', { className: 'rules' }, ...ruleItems.map((r) => r.node))], + }); + const paintRules = () => { + const states = passwordRuleStates(passwordInput.value); + lengthRule.classList.toggle('on', states.length); + for (const { rule, node } of ruleItems) node.classList.toggle('met', states[rule]); + }; + + // The § 327h agreement, asked on its own before anything is bought. + let consent: DeviationsConsent | null = null; + const consentBox = el('input', { type: 'checkbox' }); + const consentText = el('span', { className: 'consent-text' }, t('native.claim.consentLoading')); + const consentField = el( + 'label', + { className: 'consent' }, + consentBox, + el('span', {}, el('strong', {}, t('native.claim.consentTitle')), consentText) + ); + const loadConsent = async (): Promise => { + consentBox.checked = false; + consentBox.disabled = true; + consentText.textContent = t('native.claim.consentLoading'); + consent = await fetchConsent(); + consentBox.disabled = consent === null; + consentText.textContent = consent ? consent.text : t('native.claim.consentUnavailable'); + return consent; + }; + void loadConsent(); + + const subscribeLabel = () => t('native.claim.subscribe', { price: priceLabel }); + const submit = el('button', { type: 'button', className: 'cta' }, subscribeLabel()); + // What is about to be bought, so nobody pays for a plan they did not mean. + const change = el('button', { type: 'button' }, t('native.claim.change')); + change.addEventListener('click', () => { + void tap(); + showPlans({ back: true }); + }); + const planRow = el( + 'div', + { className: 'plan-row' }, + el('span', {}, el('b', {}, plan.name), el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`)), + // A purchase already made is not a choice any more. + ...(bought ? [] : [change]) + ); + const error = notice(''); + const form = el( + 'form', + { className: 'pad form', noValidate: true }, + el('h1', { className: 'title' }, t('native.claim.almost')), + planRow, + slugField, + emailField, + passwordField, + // Our terms govern the instance (terms § 5a): named before the purchase, not only in the confirmation mail. + el( + 'p', + { className: 'agree' }, + t('native.claim.agree'), + ' ', + externalLink(t('native.plans.ourTerms'), CLOUD_TERMS_URL) + ), + consentField, + error + ); + + show( + 'tall', + chosenCamera, + { + back: () => showPlans({ back: true }), + overlay: [card.node], + content: [ + form, + el('div', { className: 'dock' }, submit, el('p', { className: 'fine' }, t('native.claim.renews'))), + ], + }, + opts + ); + + // "Next" moves on to the next field instead of sending the form half filled; "Go" on the password sends it. + const nextOnEnter = (from: HTMLInputElement, to: HTMLInputElement) => + from.addEventListener('keydown', (e) => { + if (e.key !== 'Enter' || e.isComposing) return; + e.preventDefault(); + to.focus(); + }); + nextOnEnter(slugInput, emailInput); + nextOnEnter(emailInput, passwordInput); + passwordInput.addEventListener('keydown', (e) => { + if (e.key !== 'Enter' || e.isComposing) return; + e.preventDefault(); + submit.click(); + }); + + slugInput.addEventListener('focus', () => card.node.classList.add('typing')); + slugInput.addEventListener('blur', () => card.node.classList.remove('typing')); + + let status: SlugStatus | null = null; + let timer: ReturnType | undefined; + const noteFor: Partial> = { + taken: t('native.claim.taken'), + invalid: t('native.claim.invalid'), + reserved: t('native.claim.reserved'), + }; + slugInput.addEventListener('input', () => { + clearTimeout(timer); + status = null; + free.hidden = true; + slugNote.textContent = ''; + const value = slugInput.value.trim().toLowerCase(); + slugShown.textContent = value || t('native.claim.slugPlaceholder'); + slugShown.classList.toggle('ph', !value); + if (value) slugShown.after(caret); + else slugShown.before(caret); + card.fit(); + if (value.length < 3) return; + timer = setTimeout(async () => { + const result = await slugStatus(value); + if (slugInput.value.trim().toLowerCase() !== value) return; + status = result; + free.hidden = result !== 'available'; + slugNote.textContent = noteFor[result] ?? ''; + }, 350); + }); + passwordInput.addEventListener('input', () => { + paintRules(); + setNotice(error, ''); + }); + card.fit(); + + submit.addEventListener('click', async () => { + setNotice(error, ''); + const slug = slugInput.value.trim().toLowerCase(); + const email = emailInput.value.trim(); + if (slug.length < 3 || status === 'taken' || status === 'invalid' || status === 'reserved') { + shake(slugField); + slugInput.focus(); + return; + } + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { + shake(emailField); + emailInput.focus(); + return; + } + // Before anything is bought: a password TREK would refuse must not cost a purchase first. + const password = passwordInput.value; + if (passwordProblem(password) || password.length > 128) { + shake(passwordField); + setNotice(error, t('native.claim.passwordHint')); + passwordInput.focus(); + return; + } + // Nothing is bought without the agreement on the text the server holds today. + if (!consent && !(await loadConsent())) { + shake(consentField); + setNotice(error, t('native.claim.consentUnavailable')); + return; + } + if (!consentBox.checked) { + shake(consentField); + setNotice(error, t('native.claim.consentRequired')); + consentBox.focus(); + return; + } + const consentVersion = consent ? consent.version : null; + + void tap(ImpactStyle.Medium); + // The purchase sheet and the progress want the whole screen, not the keyboard. + passwordInput.blur(); + const lock = (on: boolean) => { + slugInput.disabled = on; + emailInput.disabled = on; + passwordInput.disabled = on; + consentBox.disabled = on || consent === null; + submit.disabled = on; + }; + lock(true); + submit.replaceChildren(el('span', { className: 'spin' }), t('native.connect.checking')); + const restore = () => { + lock(false); + submit.replaceChildren(subscribeLabel()); + }; + + if (!bought) { + const outcome = await iap.purchase(productIdFor(plan.id, interval)); + if (outcome.kind === 'cancelled') { + restore(); + setNotice(error, t('native.claim.cancelled')); + return; + } + if (outcome.kind === 'pending') { + restore(); + setNotice(error, t('native.claim.pending')); + return; + } + if (outcome.kind === 'failed') { + void notify(NotificationType.Error); + restore(); + setNotice(error, t('native.claim.failed')); + return; + } + if (outcome.kind === 'subscribed') { + showSubscribed(); + return; + } + bought = outcome.purchase; + } + + const redeemed = await redeemPurchase(slug, email, bought, password, consentVersion); + if (redeemed.ok && redeemed.instanceUrl) { + await iap.finish(bought); + showProvisioning(redeemed.instanceUrl, redeemed.welcome); + return; + } + void notify(NotificationType.Error); + restore(); + if (redeemed.code === 'slug-taken') { + shake(slugField); + free.hidden = true; + slugNote.textContent = t('native.claim.taken'); + } else if (redeemed.code === 'consent-outdated' || redeemed.code === 'consent-deviations') { + // The text changed since it was shown: the purchase waits, unredeemed, for the agreement on today's. + await loadConsent(); + shake(consentField); + setNotice(error, t('native.claim.consentChanged')); + } else if (redeemed.code === 'password-weak') { + // A common password the list on the server knows: the purchase waits, unredeemed, for a better one. + shake(passwordField); + setNotice(error, t('native.claim.passwordHint')); + } else { + setNotice( + error, + refundedBeforeOpening(redeemed.code, onPlay) ? t('native.claim.closedRefund') : t('native.claim.redeemFailed') + ); + } + }); +} + +// ── States of their own ───────────────────────────────────────────────────── +/** A screen that says where things stand: the landscape, the card, a title, what to do. */ +function stateScreen(o: { + camera: Camera; + kicker: string; + glyph: string; + host: string; + tone?: 'ok' | 'bad'; + busy?: boolean; + title: string; + text: string; + extra?: Node[]; + dock: Node[]; + back?: () => void; +}): { screen: Screen; card: GlassCard; title: HTMLElement; text: HTMLElement; dock: HTMLElement } { + const card = glassCard(o.kicker, o.glyph, [el('b', {}, o.host)]); + setKicker(card, o.kicker, { tone: o.tone, busy: o.busy }); + const title = el('h1', { className: 'title' }, o.title); + const text = el('p', { className: 'sub' }, o.text); + const dock = el('div', { className: 'dock' }, ...o.dock); + const screen = show('tall', o.camera, { + back: o.back, + overlay: [card.node], + content: [el('div', { className: 'pad form' }, title, text, ...(o.extra ?? [])), dock], + }); + card.fit(); + return { screen, card, title, text, dock }; +} + +/** + * The store account already holds a TREK Cloud subscription: one per Apple ID or + * Google account. Another plan would change it on the App Store and run beside + * it on Google Play, so the app buys nothing and says why. Offered instead: the + * TREK the subscription belongs to, and the store's own page to manage or end + * it. Once it has ended, a new one can be taken out, at a new address too. + */ +function showSubscribed(): void { + void notify(NotificationType.Warning); + const status = el('p', { className: 'status-line', role: 'status' }); + const open = el('button', { type: 'button', className: 'cta' }, t('native.subscribed.open')); + open.addEventListener('click', async () => { + void tap(ImpactStyle.Medium); + open.disabled = true; + status.className = 'status-line'; + status.textContent = t('native.plans.restoring'); + const purchase = await iap.restore(); + const redeemed = purchase ? await redeemPurchase('', '', purchase) : null; + if (purchase && redeemed?.ok && redeemed.instanceUrl) { + await iap.finish(purchase); + showProvisioning(redeemed.instanceUrl); + return; + } + void notify(NotificationType.Error); + open.disabled = false; + status.className = 'status-line bad'; + status.textContent = t('native.plans.restoreFailed'); + }); + const manage = externalLink( + t('native.subscribed.manage'), + onPlay ? PLAY_SUBSCRIPTIONS_URL : APP_STORE_SUBSCRIPTIONS_URL, + 'cta2' + ); + stateScreen({ + camera: cameraForPlan(0), + kicker: t('native.subscribed.kicker'), + glyph: I.cloud, + host: 'TREK Cloud', + tone: 'ok', + title: t('native.subscribed.title'), + text: t(onPlay ? 'native.subscribed.textAndroid' : 'native.subscribed.text'), + extra: [status], + dock: [open, manage], + back: () => showPlans({ back: true }), + }); +} + +function hostOf(url: string): string { + try { + return new URL(url).host; + } catch { + return url; + } +} + +/** + * The build runs on the server; the app waits on the new address, ticks off + * the steps, and opens it once it answers: "Arrived", then on to the trip. + */ +function showProvisioning(instanceUrl: string, welcome?: string): void { + const host = hostOf(instanceUrl); + const stepServer = el('span', {}, t('native.provisioning.stepServer')); + const stepReady = el('span', {}, t('native.provisioning.stepReady')); + const steps = el( + 'div', + { className: 'steps' }, + el('span', { className: 'on' }, t('native.provisioning.stepAddress')), + stepServer, + stepReady + ); + // The address set in bold inside the sentence, wherever the language puts it. + const sentence = t('native.provisioning.sub', { host: '\u0000' }); + const sub = el('span', {}); + sub.append(...sentence.split('\u0000').flatMap((part, i) => (i ? [el('b', { dir: 'ltr' }, host), part] : [part]))); + const view = stateScreen({ + camera: chosenCamera, + kicker: t('native.provisioning.kicker'), + glyph: I.lock, + host, + busy: true, + title: t('native.provisioning.title'), + text: '', + extra: [steps], + dock: [], + }); + view.text.replaceChildren(sub); + setTimeout(() => stepServer.classList.add('on'), 1300); + + const ready = async (url: string) => { + stepServer.classList.add('on'); + stepReady.classList.add('on'); + void notify(NotificationType.Success); + setKicker(view.card, t('native.provisioning.stepReady'), { tone: 'ok' }); + view.title.textContent = t('native.provisioning.readyTitle'); + view.text.textContent = t('native.provisioning.readySub'); + const go = el('button', { type: 'button', className: 'cta' }, t('native.provisioning.open')); + go.addEventListener('click', () => { + void tap(ImpactStyle.Medium); + go.disabled = true; + void connected(url, [], welcome); + }); + view.dock.replaceChildren(go); + }; + + const deadline = Date.now() + 180_000; + const poll = async (): Promise => { + if (!view.screen.node.isConnected) return; + const result = await probeServer(instanceUrl, get); + if (result.ok) { + await ready(result.url); + return; + } + if (Date.now() > deadline) { + showProvisioningSlow(instanceUrl, welcome); + return; + } + setTimeout(() => void poll(), 4000); + }; + setTimeout(() => void poll(), 3000); +} + +function showProvisioningSlow(instanceUrl: string, welcome?: string): void { + void notify(NotificationType.Warning); + const retry = el('button', { type: 'button', className: 'cta' }, t('native.provisioning.retry')); + retry.addEventListener('click', () => { + void tap(); + showProvisioning(instanceUrl, welcome); + }); + stateScreen({ + camera: cameraForPlan(3), + kicker: t('native.provisioning.failedTitle'), + glyph: I.clock, + host: hostOf(instanceUrl), + title: t('native.provisioning.failedTitle'), + text: t('native.provisioning.failedSub'), + dock: [retry], + }); +} + +async function runDemo(button: HTMLButtonElement, error?: HTMLElement): Promise { + void tap(); + if (error) setNotice(error, ''); + button.disabled = true; + const result = await probeDemo(get); + if (result.ok) { + await connected(result.url); + return; + } + button.disabled = false; + if (error) { + setNotice(error, failureMessage(result.reason)); + } else { + void notify(NotificationType.Error); + } +} + +/** + * The server takes over: a beat so the success registers, then the web view goes + * there. With a welcome code (a purchase with a chosen password) the app opens + * the instance's welcome page once, which signs the buyer in; an app build + * without that option opens the sign-in page instead, where the chosen password works. + */ +async function connected(url: string, signInHosts: string[] = [], welcome?: string): Promise { + void notify(NotificationType.Success); + await new Promise((r) => setTimeout(r, 700)); + await TrekShell.setServer({ + url, + labels: { + signInHint: t('native.signInBar.hint'), + changeServer: t('native.changeServer'), + errorPageHint: t('native.errorPageBar.hint'), + }, + ...(signInHosts.length ? { signInHosts } : {}), + ...(welcome ? { welcome } : {}), + }); +} + +function showUnreachable(server: string, cert?: ClientCertDemand, failure?: string): void { + const host = hostOf(server); + const panel = el('div', { className: 'panel', role: 'alert', hidden: true }); + if (cert) fillCertPanel(panel, cert, () => void TrekShell.reload()); + const retry = el('button', { type: 'button', className: cert ? 'cta2' : 'cta' }, t('native.offline.retry')); + retry.addEventListener('click', () => { + void tap(); + retry.disabled = true; + retry.replaceChildren(el('span', { className: 'spin' }), t('native.connect.checking')); + void TrekShell.reload(); + }); + const change = el('button', { type: 'button', className: 'link' }, t('native.changeServer')); + change.addEventListener('click', () => { + void tap(); + void TrekShell.resetServer(); + }); + stateScreen({ + camera: cameraForPlan(2), + kicker: cert ? t('native.cert.unreachableTitle') : t('native.connect.kickerUnreachable'), + glyph: cert ? I.key : I.wifiOff, + host, + tone: 'bad', + title: cert ? t('native.cert.unreachableTitle') : t('native.offline.title'), + text: cert ? t('native.cert.unreachableHint', { server: host }) : t('native.offline.hint', { server: host }), + extra: cert ? [panel] : [], + dock: [ + retry, + change, + // The cause in the web view's own terms, small: what a report needs, not a second message. + ...(failure ? [el('p', { className: 'diag', dir: 'ltr' }, failure.slice(0, 120))] : []), + ], + }); +} + +// ── Start ─────────────────────────────────────────────────────────────────── +/** + * On a phone the status bar sits on the landscape's sea, which a soft shade at + * the top keeps dark: light clock and icons. On a wide screen it also crosses + * the light column beside the landscape, where light icons would vanish, so the + * first screens hide it there. The server's UI sets its own style once it loads + * (native/nativeApp.ts). Fails quietly where there is no status bar. + */ +async function paintStatusBar(): Promise { + try { + await StatusBar.setStyle({ style: Style.Dark }); + if (wideLayout.matches) await StatusBar.hide(); + else await StatusBar.show(); + } catch { + /* web / unavailable: no native status bar to style */ + } +} + +/** + * Android's back gesture steps back through the first screens as their own + * back button does, and only leaves the app from a screen that has none. + */ +function followBackGesture(): void { + try { + void App.addListener('backButton', () => { + const back = current?.querySelector('.back'); + if (back) back.click(); + else void App.minimizeApp(); + }); + } catch { + /* web / unavailable: no system back gesture */ + } +} + +/** + * The keyboard closes the ways it does in an iOS app: a tap beside the fields, + * or a drag of the screen. A web view keeps it open for both, and on the claim + * screen the keyboard covered the terms with no way to put it away. + */ +function letKeyboardClose(): void { + const isField = (target: EventTarget | null) => + target instanceof Element && !!target.closest('input, textarea, select, [contenteditable="true"], .fld'); + const close = () => { + const active = document.activeElement; + if (active instanceof HTMLElement && isField(active)) active.blur(); + }; + document.addEventListener( + 'pointerdown', + (e) => { + if (!isField(e.target)) close(); + }, + true + ); + let startY: number | null = null; + document.addEventListener( + 'touchstart', + (e) => { + startY = isField(e.target) ? null : (e.touches[0]?.clientY ?? null); + }, + { passive: true } + ); + document.addEventListener( + 'touchmove', + (e) => { + const y = e.touches[0]?.clientY; + if (startY !== null && y !== undefined && Math.abs(y - startY) > 10) { + startY = null; + close(); + } + }, + { passive: true } + ); +} + +/** + * Whether the remembered server failed for want of a client certificate. Asked + * only when the app saw that server ask for one in this run, and then checked + * once more, so a server that is merely offline is not taken for one that + * refused the certificate. + */ +async function certificateDemand(server: string): Promise { + try { + const { request } = await TrekShell.clientCertificate(); + if (!request || request.host !== new URL(server).hostname.toLowerCase()) return null; + const result = await probeServer(server, get); + return result.ok ? null : (result.cert ?? null); + } catch { + return null; + } +} + +async function start(): Promise { + void paintStatusBar(); + wideLayout.addEventListener('change', () => void paintStatusBar()); + followBackGesture(); + letKeyboardClose(); + let url: string | null; + let previousUrl: string | null | undefined; + let failure: string | null | undefined; + try { + ({ url, previousUrl, failure } = await TrekShell.getServer()); + } catch { + // No native shell under us (a web preview, or a simulator without the + // plugin): there is no remembered server, so start at the welcome screen + // rather than leaving a blank page. + showWelcome(); + await SplashScreen.hide().catch(() => {}); + return; + } + if (!url && previousUrl) { + // An update asks to check the server once more. Out of reach (a trip, a + // server at home), that check cannot run: with a stored copy of the UI the + // app starts on that and checks on a later launch. Only for a server that + // did not answer, never for one that answered with a reason to stop. + const probe = await probeServer(previousUrl, get).catch(() => null); + if (!probe || (!probe.ok && probe.reason === 'unreachable')) { + const opened = await TrekShell.openOfflineCopy().then( + (r) => r.opened, + () => false + ); + if (opened) return; + } + showConnect(previousUrl, { recheck: true }); + } else if (!url) { + showWelcome(); + } else { + // Only reached when loading the server failed. A proxy that wanted a client + // certificate says so here, before the offline copy would start a UI that + // cannot reach its server. + const cert = await certificateDemand(url); + if (cert) { + showUnreachable(url, cert); + } else { + // On iOS the stored copy of its start page brings the offline-capable UI up anyway. + const { opened } = await TrekShell.openOfflineCopy(); + if (opened) return; + showUnreachable(url, undefined, failure ?? undefined); + } + } + await SplashScreen.hide(); +} + +void start(); diff --git a/client/native-shell/scenery.ts b/client/native-shell/scenery.ts new file mode 100644 index 000000000..89a4dea47 --- /dev/null +++ b/client/native-shell/scenery.ts @@ -0,0 +1,585 @@ +/** + * The landscape behind the first screens of the app: one world seen from above, + * an island out at sea, the coast with its town, the farmland behind it and the + * mountains at the back. A fragment shader draws it every frame (water, surf, + * boats, a car on the road), so it is never a photo and never the same twice. + * + * The plan picker moves the camera through that world, one place per plan, so + * choosing reads as travelling further inland. The scenes are framed for a phone + * 390 px wide: a wider or taller box (iPad, an unfolded phone) shows more of the + * world around the same centre. + * + * Kept light for the phone it runs on: the device pixel ratio is capped at 2, + * the picture drops to a lower resolution when frames come slow, the loop stops + * while the app is in the background or the canvas has left the page, and with + * reduced motion it is one still frame. Without WebGL the box keeps its plain + * sea colour from the stylesheet. + */ + +/** Where the camera stands for a place, in world pixels, for a 390 px frame. */ +export type Camera = readonly [number, number]; +export const WELCOME_CAMERA: Camera = [0, 0]; +/** One place per plan, in the order the plans come: island, coast, farmland, mountains. */ +const PLAN_CAMERAS: readonly Camera[] = [ + [62, -392], + [0, 24], + [60, 290], + [70, 660], +]; +export function cameraForPlan(index: number): Camera { + return PLAN_CAMERAS[Math.max(0, Math.min(PLAN_CAMERAS.length - 1, index))]; +} + +const FRAME_WIDTH = 390; + +const FRAGMENT = ` + precision highp float; + uniform vec2 uRes; uniform float uDpr; uniform float uT; uniform vec2 uCam; uniform float uHaze; + float coast(float x) { return 128.0 + 12.0 * sin(x * 0.018 + 0.6) + 7.0 * sin(x * 0.051 + 2.1) + 4.0 * sin(x * 0.11); } + float riverX(float y) { return 168.0 - (y - 120.0) * 0.30 + 9.0 * sin(y * 0.035 + 0.8) + 4.0 * sin(y * 0.09); } + float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); } + vec2 hash2(vec2 p) { return fract(sin(vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)))) * 43758.5453); } + float noise(vec2 p) { vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); + return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y); } + float fbm(vec2 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 5; i++) { v += a * noise(p); p = p * 2.03 + vec2(1.7, 9.2); a *= 0.5; } return v; } + float fbm3(vec2 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 3; i++) { v += a * noise(p); p = p * 2.03 + vec2(1.7, 9.2); a *= 0.5; } return v; } + float wave(vec2 p, float t) { + return 0.55 * sin(dot(p, vec2(0.040, 0.085)) - t * 1.10) + 0.35 * sin(dot(p, vec2(-0.070, 0.050)) - t * 1.45) + + 0.22 * sin(dot(p, vec2(0.110, 0.130)) - t * 2.10) + 0.12 * sin(dot(p, vec2(-0.170, 0.190)) - t * 2.90) + + 0.90 * fbm(p * 0.055 + vec2(t * 0.18, t * 0.32)); + } + float ridged(vec2 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 5; i++) { float n = 1.0 - abs(noise(p) * 2.0 - 1.0); v += a * n * n; p = p * 2.07 + vec2(3.1, 1.7); a *= 0.5; } return v; } + /* Height: gentle near the shore, sharp ridges further inland. */ + float peaks(vec2 p) { float v = 0.0, a = 0.55; for (int i = 0; i < 7; i++) { v += a * (1.0 - abs(noise(p) * 2.0 - 1.0)); p = p * 2.13 + vec2(1.3, 4.7); a *= 0.5; } return v; } + float ground(vec2 p) { + float inland = smoothstep(10.0, 170.0, p.y - coast(p.x)); + return fbm(p * 0.011) * 0.4 + ridged(p * 0.014 + 5.0) * 1.15 * inland + fbm3(p * 0.06) * 0.08; + } + /* The island out at sea: signed distance to its shore in px (> 0 on land), + a round main body with an uneven coast and a headland to the east. */ + float islD(vec2 p) { + vec2 q = (p - vec2(230.0, -250.0)) / vec2(1.5, 1.0); + float r = length(q); + float rad = 66.0 + 46.0 * (fbm(q * 0.016 + 4.0) - 0.5) + 30.0 * (fbm(q * 0.045 + 8.0) - 0.5) + 10.0 * (fbm(p * 0.09) - 0.5); + vec2 q2 = (p - vec2(372.0, -222.0)) / vec2(1.6, 1.0); + float head = 15.0 + 10.0 * (fbm(p * 0.04 + 9.0) - 0.5) - length(q2); + return max(rad - r, head); + } + float islH(vec2 p) { + float s = islD(p); + return smoothstep(0.0, 60.0, s) * (0.5 + 0.7 * fbm(p * 0.018 + 2.0)) + ridged(p * 0.03) * 0.22 * smoothstep(8.0, 50.0, s); + } + /* Trees: one per cell at most, a round crown of varying size. Returns the + crown's cover (0..1) and how far from its centre, for the shading. */ + vec3 tree(vec2 p, float cell) { + vec2 c = floor(p / cell); + float best = 9.0; vec2 off = vec2(0.0); float sz = 0.0; + for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) { + vec2 g = c + vec2(float(i), float(j)); + vec2 h = hash2(g); + vec2 o = (g + 0.15 + 0.7 * h) * cell; + float r = cell * (0.38 + 0.22 * hash(g + 3.1)); + float d = length(p - o) / r; + if (d < best) { best = d; off = (p - o) / r; sz = r; } + } + return vec3(1.0 - smoothstep(0.86, 1.0, best), off); + } + /* A Mediterranean town: one house per cell, a rectangle turned the way + the lane runs there (the direction drifts across town, so lanes curve), + sized at random and packed close. Whitewashed cubes with a parapet and + now and then a water tank, pastel walls, terracotta roofs pitched along + the long side, and the odd blue dome. */ + float town(vec2 p, out vec3 roof, out vec2 hid) { + float cell = 9.0; + vec2 c = floor(p / cell); + roof = vec3(0.0); + hid = c; + float got = 0.0; + for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) { + vec2 g = c + vec2(float(i), float(j)); + if (hash(g + 2.7) < 0.07) continue; + vec2 o = (g + 0.5 + 0.35 * (hash2(g) - 0.5)) * cell; + float ang = (noise(o * 0.018) - 0.5) * 2.4 + (hash(g + 7.7) - 0.5) * 0.25; + vec2 cs = vec2(cos(ang), sin(ang)); + vec2 rel = p - o; + vec2 l = vec2(dot(rel, cs), dot(rel, vec2(-cs.y, cs.x))); + vec2 hs = cell * vec2(0.36 + 0.16 * hash(g + 1.3), 0.27 + 0.14 * hash(g + 4.1)); + if (abs(l.x) < hs.x && abs(l.y) < hs.y) { + float k = hash(g + 5.3); + vec3 col = k < 0.44 ? vec3(0.96, 0.95, 0.91) : k < 0.68 ? vec3(0.80, 0.46, 0.32) : k < 0.80 ? vec3(0.93, 0.79, 0.56) : k < 0.90 ? vec3(0.94, 0.75, 0.67) : vec3(0.88, 0.86, 0.80); + float rim = min(hs.x - abs(l.x), hs.y - abs(l.y)); + if (k >= 0.44 && k < 0.68) { + // pitched roof: the ridge runs along the long side, one slope lit, one shaded + float lit = dot(vec2(-cs.y, cs.x), vec2(-0.67, -0.73)) * sign(l.y); + col *= lit > 0.0 ? 1.08 : 0.80; + col *= 0.95 + 0.05 * sin(l.x * 3.6); + col *= 1.0 - 0.25 * (1.0 - smoothstep(0.0, 0.5, abs(l.y))); + } else { + // flat roof: a parapet round the edge, a water tank on some + col *= 1.0 - 0.13 * (1.0 - smoothstep(0.4, 1.1, rim)); + vec2 tk = vec2(hs.x * 0.45, -hs.y * 0.35); + if (hash(g + 6.2) < 0.35 && length(l - tk) < 0.95) col = vec3(0.45, 0.47, 0.50) + 0.25 * step(0.0, -(l - tk).x - (l - tk).y); + if (k < 0.44 && hash(g + 4.4) < 0.08 && length(l) < min(hs.x, hs.y) * 0.85) { + col = mix(vec3(0.12, 0.30, 0.64), vec3(0.58, 0.76, 0.98), clamp(0.55 - dot(rel / (min(hs.x, hs.y) * 0.85), vec2(-0.67, -0.73)) * 0.6, 0.0, 1.0)); + } + } + col *= 0.93 + 0.1 * hash(g + 9.9); + roof = col; + hid = g; + got = 1.0; + } + } + return got; + } + void main() { + vec2 sp = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y) / uDpr; + vec2 p = sp + uCam; + float t = uT; + vec3 L = normalize(vec3(-0.55, -0.6, 0.62)); + float d = coast(p.x) - p.y; // > 0 at sea, < 0 inland, in px + float wash = 6.0 + 4.0 * sin(t * 1.2 + p.x * 0.045) + 3.0 * fbm3(vec2(p.x * 0.08, t * 0.6)); + vec3 col; + if (d > -2.0) { + /* ── sea ── */ + float e = 0.9, h = wave(p, t); + vec3 n = normalize(vec3(-(wave(p + vec2(e, 0.0), t) - h) * 1.6, -(wave(p + vec2(0.0, e), t) - h) * 1.6, 1.0)); + float depth = smoothstep(0.0, 120.0, d); + col = mix(vec3(0.47, 0.83, 0.82), vec3(0.17, 0.58, 0.72), smoothstep(0.0, 0.45, depth)); + col = mix(col, vec3(0.07, 0.33, 0.55), smoothstep(0.45, 1.0, depth)); + col *= 0.78 + 0.32 * clamp(dot(n, -vec3(L.x, L.y, -L.z)), 0.0, 1.0); + vec3 Ls = normalize(vec3(0.45, -0.55, 0.70)); + vec3 R = reflect(-Ls, n); + col += vec3(1.0, 0.97, 0.9) * (pow(clamp(R.z, 0.0, 1.0), 90.0) * 0.45 + pow(clamp(R.z, 0.0, 1.0), 900.0) * step(0.55, noise(p * 0.6 + t * 2.0)) * 1.4); + float ca = pow(1.0 - abs(sin(fbm(p * 0.09 + vec2(t * 0.35, -t * 0.25)) * 9.0)), 6.0); + col += vec3(0.85, 1.0, 0.95) * ca * 0.22 * (1.0 - smoothstep(0.0, 40.0, d)); + float runs = smoothstep(0.82, 1.0, sin(d * 0.32 + t * 2.2 + fbm3(p * 0.05) * 3.0)) * (1.0 - smoothstep(6.0, 46.0, d)); + float lace = smoothstep(0.45, 0.75, fbm3(p * 0.22 + vec2(t * 0.5, 0.0))); + float foam = max(1.0 - smoothstep(wash - 4.0, wash + 3.0, d), runs * lace * 0.8); + col = mix(col, vec3(0.97, 0.99, 1.0), clamp(foam, 0.0, 1.0) * 0.92); + // boats crossing, each in a lane of its own (46 px apart, wider than any + // wake), at a speed that swells and eases but never turns back + for (int k = 0; k < 2; k++) { + float fk = float(k); + float dir = fk < 0.5 ? 1.0 : -1.0; + float speed = 10.0 + fk * 4.0; + float run = speed * t + 14.0 * sin(t * 0.23 + fk * 2.0) + 6.0 * sin(t * 0.61 + fk * 4.0); + float lane = 36.0 + fk * 46.0; + float drift = 2.6 * sin(t * 0.31 + fk * 1.7); + vec2 bp = vec2(mod(fk * 190.0 + run * dir, 480.0) - 45.0, lane + drift); + float yaw = 2.6 * 0.31 * cos(t * 0.31 + fk * 1.7) / speed; + vec2 q = p - bp; + q = vec2(q.x * dir, q.y); + q = vec2(q.x + yaw * q.y, q.y - yaw * q.x); + float back = -q.x; + float open = 0.29 + 0.05 * sin(t * 1.3 + fk * 3.0 + back * 0.05); + float spread = back * open; + float churn = smoothstep(0.25, 0.65, noise(vec2(back * 0.35 - t * 1.6, q.y * 0.45 + fk * 7.0))); + float edgeW = 0.7 + 0.8 * noise(vec2(back * 0.2 + fk * 3.0, t * 0.8)); + float fade = step(0.0, back) * (1.0 - smoothstep(8.0, 64.0, back)); + float wake = (1.0 - smoothstep(edgeW * 0.6, edgeW * 1.8, abs(abs(q.y) - spread))) * fade * (0.55 + 0.45 * churn); + wake += (1.0 - smoothstep(0.0, 2.4, abs(q.y))) * step(0.0, back) * (1.0 - smoothstep(4.0, 30.0, back)) * 0.7 * churn; + col = mix(col, vec3(0.96, 0.98, 1.0), clamp(wake, 0.0, 1.0) * 0.78); + float hull = length(q / vec2(6.5, 2.4)); + col = mix(col, vec3(0.20, 0.30, 0.40), (1.0 - smoothstep(1.0, 1.5, length((q - vec2(-1.0, 1.4)) / vec2(6.5, 2.4)))) * 0.25); + col = mix(col, mix(vec3(0.98), vec3(0.80, 0.82, 0.85), step(0.0, q.y)), 1.0 - smoothstep(0.92, 1.0, hull)); + col = mix(col, vec3(0.55, 0.36, 0.24), 1.0 - smoothstep(0.9, 1.0, length((q - vec2(-1.0, 0.0)) / vec2(2.4, 1.2)))); + } + // the island: a shelf of shallow water, a reef, surf, a beach, a wooded hill + if (abs(p.y + 250.0) < 175.0 && abs(p.x - 265.0) < 310.0) { + float sI = islD(p); + if (sI < 0.0) { + float sd = -sI; + float shelf = 1.0 - smoothstep(4.0, 78.0, sd); + float ripple = 0.5 + 0.5 * sin(dot(p, vec2(0.42, 0.25)) + fbm(p * 0.05) * 6.0); + vec3 sh = mix(vec3(0.13, 0.52, 0.66), vec3(0.40, 0.83, 0.81), smoothstep(62.0, 10.0, sd)); + sh = mix(sh, vec3(0.80, 0.86, 0.74), smoothstep(26.0, 0.0, sd) * 0.4); + sh *= 0.95 + 0.08 * ripple * smoothstep(50.0, 4.0, sd); + float swell = sin(sd * 0.3 + t * 1.8 + fbm3(p * 0.03) * 4.0); + sh *= 1.0 + 0.09 * swell * smoothstep(70.0, 20.0, sd) * smoothstep(0.0, 8.0, sd); + float reef = smoothstep(0.57, 0.68, fbm(p * 0.045 + 13.0)) * smoothstep(12.0, 22.0, sd) * (1.0 - smoothstep(46.0, 60.0, sd)); + sh = mix(sh, vec3(0.18, 0.40, 0.42) * (0.82 + 0.3 * noise(p * 0.5)), reef * 0.75); + float lw = 0.85 + 0.3 * clamp(dot(n, -vec3(L.x, L.y, -L.z)), 0.0, 1.0); + col = mix(col, sh * lw, shelf); + float cs = pow(1.0 - abs(sin(fbm(p * 0.12 + vec2(t * 0.4, -t * 0.3)) * 10.0)), 7.0); + col += vec3(0.9, 1.0, 0.95) * cs * 0.24 * smoothstep(45.0, 4.0, sd); + // surf breaking along the reef edge, in pieces + float reefLine = 44.0 + 12.0 * (fbm(p * 0.02 + 5.0) - 0.5); + float brk = (1.0 - smoothstep(0.0, 2.0 + 2.5 * fbm3(p * 0.04 + vec2(t * 0.25, 0.0)), abs(sd - reefLine - 2.5 * sin(t * 0.8 + p.x * 0.03)))); + brk *= smoothstep(0.35, 0.62, noise(p * 0.08 + vec2(t * 0.6, 0.0))) * smoothstep(0.42, 0.56, fbm(p * 0.03 + 13.0)); + col = mix(col, vec3(0.96, 0.99, 1.0), brk * 0.6); + // waves rolling in, foam lines thinning out as they come, the swash on the sand + float lace2 = smoothstep(0.42, 0.72, fbm3(p * 0.25 + vec2(t * 0.4, 0.0))); + float roll = smoothstep(0.9, 1.0, swell) * (1.0 - smoothstep(5.0, 26.0, sd)); + float iw = 4.5 + 3.5 * sin(t * 1.1 + fbm(p * 0.03) * 6.0); + float swash = 1.0 - smoothstep(iw - 3.0, iw + 2.5, sd); + col = mix(col, vec3(0.97, 0.99, 1.0), clamp(max(swash * (0.55 + 0.45 * lace2), roll * lace2 * 0.8), 0.0, 1.0) * 0.9); + } else { + float hI = islH(p); + vec3 nI = normalize(vec3(-(islH(p + vec2(1.0, 0.0)) - hI) * 110.0, -(islH(p + vec2(0.0, 1.0)) - hI) * 110.0, 1.0)); + float shI = clamp(dot(nI, normalize(vec3(-L.x, -L.y, L.z))), 0.0, 1.0); + float bwI = 5.0 + 15.0 * fbm(p * 0.03 + 2.0); + vec3 sandI = vec3(0.95, 0.89, 0.74) + (hash(floor(p * 3.0)) - 0.5) * 0.05; + sandI = mix(sandI, vec3(0.76, 0.69, 0.56), (1.0 - smoothstep(0.0, 4.5, sI)) * 0.75); + float big = step(0.55, fbm(p * 0.025 + 6.0)); + vec3 tr = big > 0.5 ? tree(p, 8.0) : tree(p, 4.6); + vec3 trS = big > 0.5 ? tree(p - vec2(2.6, 3.0), 8.0) : tree(p - vec2(1.7, 2.0), 4.6); + float lit = clamp(0.62 - dot(tr.yz, vec2(L.x, L.y)) * 0.55, 0.0, 1.0); + float jung = smoothstep(bwI, bwI + 8.0, sI); + vec3 under = mix(vec3(0.46, 0.55, 0.28), vec3(0.28, 0.42, 0.19), noise(p * 0.1)) * (1.0 - 0.35 * trS.x); + vec3 canopy = mix(vec3(0.09, 0.27, 0.12), vec3(0.42, 0.62, 0.28), lit) * (0.9 + 0.2 * noise(p * 2.0)); + vec3 landI = mix(sandI, under, jung); + landI *= 1.0 - 0.3 * trS.x * smoothstep(bwI - 4.0, bwI, sI) * (1.0 - jung); + landI = mix(landI, canopy, tr.x * smoothstep(bwI - 3.0, bwI + 5.0, sI) * (0.35 + 0.65 * smoothstep(0.22, 0.36, fbm(p * 0.035 + 1.0)))); + // bare rock on the steep top and boulders where the headland meets the sea + float slI = 1.0 - nI.z; + landI = mix(landI, vec3(0.62, 0.58, 0.50) * (0.9 + 0.15 * noise(p * 0.8)), smoothstep(0.7, 0.88, slI) * 0.6); + vec3 bo = tree(p, 4.0); + float blit = clamp(0.6 - dot(bo.yz, vec2(L.x, L.y)) * 0.6, 0.0, 1.0); + vec3 rocks = mix(vec3(0.30, 0.29, 0.27), mix(vec3(0.52, 0.50, 0.46), vec3(0.80, 0.77, 0.71), blit), bo.x); + float rk = smoothstep(0.6, 0.7, fbm(p * 0.05 + 4.0)) * (1.0 - smoothstep(bwI - 2.0, bwI + 4.0, sI)); + landI = mix(landI, rocks, rk); + landI *= 0.5 + 0.7 * shI; + col = mix(vec3(0.90, 0.95, 0.93), landI, smoothstep(0.0, 1.4, sI)); + } + // a sailboat going round, well outside the reef + float sa = t * 0.06; + vec2 sb = vec2(230.0, -250.0) + vec2(cos(sa) * 1.5, sin(sa)) * 140.0; + vec2 tang = normalize(vec2(-sin(sa) * 1.5, cos(sa))); + vec2 q = p - sb; + q = vec2(dot(q, tang), dot(q, vec2(-tang.y, tang.x))); + float back = -q.x; + float wk = (1.0 - smoothstep(0.5, 1.6, abs(abs(q.y) - back * 0.22))) * step(0.0, back) * (1.0 - smoothstep(6.0, 44.0, back)); + col = mix(col, vec3(0.96, 0.98, 1.0), wk * 0.7); + col = mix(col, vec3(0.10, 0.22, 0.32), (1.0 - smoothstep(1.0, 1.4, length((q - vec2(-1.5, 2.6)) / vec2(5.0, 3.0)))) * 0.25); + col = mix(col, vec3(0.98), 1.0 - smoothstep(0.9, 1.0, length(q / vec2(4.8, 1.7)))); + float sail = max(abs(q.x + 0.4) - 2.6, abs(q.y + 1.2 - (q.x + 0.4) * 0.15) - 0.7); + col = mix(col, vec3(0.88, 0.86, 0.82), 1.0 - smoothstep(-0.2, 0.3, sail)); + } + } else { + /* ── land: hillside, macchia, and the town down at the water ── */ + float e = 1.2, h = ground(p); + vec3 n = normalize(vec3(-(ground(p + vec2(e, 0.0)) - h) * 17.0, -(ground(p + vec2(0.0, e)) - h) * 17.0, 1.0)); + float shade = clamp(dot(n, normalize(vec3(-L.x, -L.y, L.z))), 0.0, 1.0); + float slope = 1.0 - n.z; + float veg = fbm(p * 0.03 + 2.0); + vec3 base = mix(vec3(0.78, 0.72, 0.53), vec3(0.50, 0.56, 0.33), smoothstep(0.42, 0.58, veg)); + base = mix(base, vec3(0.36, 0.45, 0.25), smoothstep(0.6, 0.7, veg) * 0.8); + base *= 0.9 + 0.16 * noise(p * 1.4) + 0.06 * (hash(floor(p * 2.0)) - 0.5); + float shrub = smoothstep(0.42, 0.6, fbm(p * 0.022 + 11.0)); + vec3 shT = tree(p - vec2(2.0, 2.4), 6.0); + base *= 1.0 - 0.34 * shT.x * shrub; + vec3 tr = tree(p, 6.0); + float lit = clamp(0.62 - dot(tr.yz, vec2(L.x, L.y)) * 0.55, 0.0, 1.0); + vec3 leaf = mix(vec3(0.16, 0.27, 0.14), vec3(0.45, 0.55, 0.30), lit) * (0.9 + 0.2 * noise(p * 2.3)); + base = mix(base, leaf, tr.x * shrub * (1.0 - smoothstep(0.35, 0.6, slope))); + vec3 limestone = mix(vec3(0.70, 0.66, 0.58), vec3(0.88, 0.85, 0.78), noise(p * 0.7)) * (0.92 + 0.12 * noise(p * 3.1)); + base = mix(base, limestone, smoothstep(0.3, 0.6, slope) * 0.75); + // the town: dense by the water, thinning out up the hill, house by house + vec3 roof, tmpRoof; vec2 hid, tmpId; + float occ = town(p, roof, hid); + float occS = town(p - vec2(2.4, 3.0), tmpRoof, tmpId); + float near = exp(d / 150.0); + float want = fbm(p * 0.011 + 3.0) * 0.75 * exp(d / 420.0) + near * 0.6; + float here = step(0.55 + 0.12 * hash(hid + 6.6), want); + float hereS = step(0.55 + 0.12 * hash(tmpId + 6.6), want); + // lanes are paved only in the dense heart; where no house stands the hillside shows + float dense = smoothstep(0.62, 0.7, want); + vec3 stone = vec3(0.87, 0.84, 0.77) * (0.95 + 0.07 * noise(p * 1.6)); + vec3 open = roof.x < -0.5 ? mix(stone, vec3(0.48, 0.57, 0.34), step(0.5, hash(hid + 3.0))) : stone; + col = mix(base, open, dense); + if (occ * here > 0.5) col = roof; + else if (occS * hereS > 0.5) col *= 0.64; + // the hinterland: parcels with their own crop and row direction, hedges between + float farm = smoothstep(150.0, 200.0, -d) * (1.0 - smoothstep(450.0, 510.0, -d)); + if (farm > 0.0) { + vec2 fp = (p + vec2(fbm(p * 0.015), fbm(p * 0.015 + 7.0)) * 10.0) * vec2(0.62, 1.0); + vec2 fc = floor(fp / 58.0); + float b1 = 99.0, b2 = 99.0; vec2 fid = vec2(0.0); + for (int fj = -1; fj <= 1; fj++) for (int fi = -1; fi <= 1; fi++) { + vec2 g = fc + vec2(float(fi), float(fj)); + float dd = length(fp - (g + 0.25 + 0.5 * hash2(g)) * 58.0); + if (dd < b1) { b2 = b1; b1 = dd; fid = g; } else if (dd < b2) { b2 = dd; } + } + float kind = hash(fid + 1.7); + float ang = hash(fid + 4.2) * 3.1416; + vec2 dir = vec2(cos(ang), sin(ang)); + float u = dot(p, dir), v = dot(p, vec2(-dir.y, dir.x)); + vec3 parcel; + if (kind < 0.36) { + float r = smoothstep(-0.2, 0.6, sin(u * 6.2831 / 4.0)); + vec3 vine = mix(vec3(0.24, 0.36, 0.16), vec3(0.44, 0.54, 0.25), noise(p * 1.4)) * (0.85 + 0.2 * noise(vec2(u * 0.3, v * 1.6))); + parcel = mix(vec3(0.67, 0.57, 0.42), vine, r); + } else if (kind < 0.56) { + parcel = mix(vec3(0.88, 0.78, 0.52), vec3(0.80, 0.68, 0.43), 0.5 + 0.5 * sin(u * 6.2831 / 2.4)) * (0.94 + 0.1 * noise(p * 0.5)); + } else if (kind < 0.74) { + vec2 q = vec2(u, v) / 9.0; + vec2 qc = fract(q) - 0.5 + (hash2(floor(q)) - 0.5) * 0.18; + float olive = 1.0 - smoothstep(0.2, 0.33, length(qc)); + float oshadow = 1.0 - smoothstep(0.2, 0.36, length(qc - vec2(0.12, 0.16))); + vec3 soil = vec3(0.76, 0.68, 0.52) * (1.0 - 0.28 * oshadow); + parcel = mix(soil, mix(vec3(0.36, 0.42, 0.28), vec3(0.56, 0.60, 0.42), clamp(0.6 - dot(qc, vec2(L.x, L.y)) * 1.4, 0.0, 1.0)), olive); + } else if (kind < 0.88) { + parcel = mix(vec3(0.50, 0.39, 0.28), vec3(0.63, 0.51, 0.37), 0.5 + 0.5 * sin(u * 6.2831 / 1.9)) * (0.95 + 0.08 * noise(p * 0.6)); + } else { + parcel = mix(vec3(0.47, 0.57, 0.29), vec3(0.58, 0.63, 0.33), noise(p * 0.08)); + } + // hedgerows and the odd cypress along the field edges + float edgeD = (b2 - b1) * 0.5; + parcel *= 0.92 + 0.16 * hash(fid + 5.5); + float hedge = 1.0 - smoothstep(0.5, 1.5, edgeD); + vec3 cy = tree(p, 5.0); + parcel = mix(parcel, vec3(0.30, 0.35, 0.20), hedge * 0.75); + parcel = mix(parcel, vec3(0.12, 0.20, 0.10), cy.x * (1.0 - smoothstep(1.5, 3.5, edgeD)) * step(0.7, hash(fid + 9.0))); + float level = 1.0 - smoothstep(0.38, 0.6, slope); + col = mix(col, parcel, farm * level * (1.0 - step(0.5, occ * here))); + // a country road winding through, a car on it + float ry = 425.0 + 26.0 * sin(p.x * 0.011 + 1.0) + 9.0 * sin(p.x * 0.029); + float rd = abs(p.y - ry); + col = mix(col, vec3(0.86, 0.82, 0.72), (1.0 - smoothstep(4.6, 5.6, rd)) * farm); + col = mix(col, vec3(0.36, 0.36, 0.37) * (0.95 + 0.08 * noise(p * 2.0)), (1.0 - smoothstep(3.4, 4.2, rd)) * farm); + col = mix(col, vec3(0.95), (1.0 - smoothstep(0.25, 0.6, rd)) * step(0.5, fract(p.x / 9.0)) * farm); + float cx = mod(t * 22.0 + 6.0 * sin(t * 0.4), 760.0) - 120.0; + float cyy = 425.0 + 26.0 * sin(cx * 0.011 + 1.0) + 9.0 * sin(cx * 0.029) - 1.6; + float slopeR = 26.0 * 0.011 * cos(cx * 0.011 + 1.0) + 9.0 * 0.029 * cos(cx * 0.029); + vec2 cq = p - vec2(cx, cyy); + float ca = atan(slopeR); + cq = vec2(cq.x * cos(ca) + cq.y * sin(ca), -cq.x * sin(ca) + cq.y * cos(ca)); + float body = max(abs(cq.x) - 3.4, abs(cq.y) - 1.4); + col = mix(col, vec3(0.14, 0.14, 0.15), (1.0 - smoothstep(0.0, 1.4, max(abs(cq.x - 0.8) - 3.6, abs(cq.y - 0.9) - 1.6))) * 0.35); + col = mix(col, vec3(0.78, 0.16, 0.13), 1.0 - smoothstep(-0.2, 0.4, body)); + col = mix(col, vec3(0.20, 0.24, 0.30), (1.0 - smoothstep(-0.2, 0.3, max(abs(cq.x - 0.9) - 1.0, abs(cq.y) - 1.0)))); + } + col *= 0.64 + 0.5 * shade; + col *= 1.0 - 0.1 * smoothstep(0.55, 0.0, h); + // the high country: broad massifs, conifers in the valley, snow on the tops + float alpine = smoothstep(470.0, 590.0, -d); + if (alpine > 0.0) { + float lakeD = length((p - vec2(250.0, 790.0)) / vec2(2.3, 1.0)); + float valley = mix(0.35, 1.0, smoothstep(26.0, 80.0, lakeD)); + float hA = (peaks(p * 0.006 + 5.0) * 1.3 - 0.2 + fbm(p * 0.035) * 0.05) * valley; + float hX = (peaks((p + vec2(1.5, 0.0)) * 0.006 + 5.0) * 1.3 - 0.2 + fbm((p + vec2(1.5, 0.0)) * 0.035) * 0.05) * valley; + float hY = (peaks((p + vec2(0.0, 1.5)) * 0.006 + 5.0) * 1.3 - 0.2 + fbm((p + vec2(0.0, 1.5)) * 0.035) * 0.05) * valley; + vec3 nA = normalize(vec3(-(hX - hA) * 95.0, -(hY - hA) * 95.0, 1.0)); + float shA = clamp(dot(nA, normalize(vec3(-L.x, -L.y, L.z))), 0.0, 1.0); + float slA = 1.0 - nA.z; + vec3 rockA = mix(vec3(0.46, 0.43, 0.39), vec3(0.62, 0.58, 0.52), noise(p * 0.05)) * (0.94 + 0.08 * noise(p * 0.9)); + vec3 trA = tree(p, 4.4); + vec3 trS = tree(p - vec2(1.6, 2.0), 4.4); + float conifer = (1.0 - smoothstep(0.40, 0.50, hA + (noise(p * 0.06) - 0.5) * 0.08)) * (1.0 - smoothstep(0.5, 0.75, slA)); + vec3 meadow = mix(vec3(0.42, 0.50, 0.28), vec3(0.52, 0.56, 0.32), noise(p * 0.1)); + vec3 forestA = meadow * (1.0 - 0.4 * trS.x); + forestA = mix(forestA, mix(vec3(0.07, 0.15, 0.09), vec3(0.20, 0.33, 0.18), clamp(0.6 - dot(trA.yz, vec2(L.x, L.y)) * 0.6, 0.0, 1.0)), trA.x * smoothstep(0.2, 0.5, fbm(p * 0.02 + 3.0) + 0.25)); + vec3 alp = mix(rockA, forestA, conifer); + float snowA = smoothstep(0.75, 0.81, hA + (noise(p * 0.09) - 0.5) * 0.1) * (1.0 - smoothstep(0.55, 0.8, slA)); + snowA = max(snowA, smoothstep(0.86, 0.94, hA)); + alp *= 0.36 + 0.86 * shA; + alp = mix(alp * vec3(0.8, 0.87, 1.05), alp * vec3(1.04, 1.0, 0.95), smoothstep(0.35, 0.8, shA)); + vec3 snowC = mix(vec3(0.70, 0.77, 0.88), vec3(0.98, 0.98, 0.97), smoothstep(0.2, 0.75, shA)) * (0.96 + 0.05 * noise(p * 0.6)); + alp = mix(alp, snowC, snowA); + col = mix(col, alp, alpine); + } + // a mountain lake in a valley + vec2 lc = vec2(250.0, 790.0); + float ld = length((p - lc) / vec2(2.3, 1.0)) + (fbm(p * 0.05) - 0.5) * 14.0; + if (ld < 34.0) { + float lw = wave(p * 1.3, t * 0.6); + vec3 lake = mix(vec3(0.12, 0.36, 0.48), vec3(0.24, 0.55, 0.62), smoothstep(34.0, 12.0, ld)); + lake *= 0.86 + 0.12 * lw; + lake += vec3(1.0, 0.98, 0.92) * pow(noise(p * 0.6 + t * 1.2), 14.0) * 0.7; + col = mix(col, lake, smoothstep(34.0, 31.0, ld)); + col = mix(col, vec3(0.82, 0.80, 0.74), (1.0 - smoothstep(0.0, 1.8, abs(ld - 32.0))) * 0.8); + } + // the shore: small coves of sand between rocks, wet where the wash runs + float bw = 17.0 + 10.0 * fbm3(vec2(p.x * 0.03, 1.0)); + float shore = 1.0 - smoothstep(bw - 3.0, bw + 2.0, -d); + float rock = smoothstep(0.56, 0.66, fbm(p * 0.05 + 4.0)); + vec3 sand = vec3(0.93, 0.86, 0.71) + (hash(floor(p * 3.0)) - 0.5) * 0.06; + float wet = 1.0 - smoothstep(0.0, 6.0 + wash * 0.4, -d); + sand = mix(sand, vec3(0.74, 0.67, 0.55), wet * 0.8); + // boulders: round stones lit from the top left, darker in the cracks between + vec3 bo = tree(p, 4.5); + float blit = clamp(0.6 - dot(bo.yz, vec2(L.x, L.y)) * 0.6, 0.0, 1.0); + vec3 rocks = mix(vec3(0.30, 0.29, 0.27), mix(vec3(0.52, 0.50, 0.46), vec3(0.80, 0.77, 0.71), blit), bo.x); + vec3 edgeCol = mix(sand, rocks, rock); + col = mix(col, edgeCol, shore); + } + // haze into the page below: a long, uneven edge that drifts slowly + float H = uRes.y / uDpr; + float edge = H - 118.0 + 42.0 * (fbm3(vec2(sp.x * 0.011, t * 0.04)) - 0.5) * 2.0 + 22.0 * (fbm(sp * 0.028 + vec2(t * 0.05, 0.0)) - 0.5) * 2.0; + float mist = smoothstep(edge - 34.0, edge + 84.0, sp.y); + mist = clamp(mist + smoothstep(H - 24.0, H, sp.y), 0.0, 1.0); + col = mix(col, vec3(1.0, 0.98, 0.961), mist * uHaze); + gl_FragColor = vec4(col, 1.0); + }`; + +const VERTEX = 'attribute vec2 a; void main(){ gl_Position = vec4(a, 0.0, 1.0); }'; + +export interface Scenery { + /** Glides the camera to another place; a still picture jumps there. */ + flyTo(camera: Camera): void; +} + +interface SceneryOptions { + /** The height the scene is framed for; the box may be taller or shorter. */ + frame: number; + camera?: Camera; + /** The soft fade into the page at the foot of the picture; off beside a column. */ + haze?: boolean; +} + +const reducedMotion = (): boolean => + typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; + +export function startScenery(box: HTMLElement, opts: SceneryOptions): Scenery | null { + const canvas = document.createElement('canvas'); + canvas.className = 'scenery'; + canvas.setAttribute('aria-hidden', 'true'); + box.prepend(canvas); + const gl = canvas.getContext('webgl', { antialias: false, premultipliedAlpha: false, powerPreference: 'low-power' }); + if (!gl) { + canvas.remove(); + return null; + } + const compile = (type: number, src: string): WebGLShader | null => { + const shader = gl.createShader(type); + if (!shader) return null; + gl.shaderSource(shader, src); + gl.compileShader(shader); + return shader; + }; + const program = gl.createProgram(); + const vs = compile(gl.VERTEX_SHADER, VERTEX); + const fs = compile(gl.FRAGMENT_SHADER, FRAGMENT); + if (!program || !vs || !fs) { + canvas.remove(); + return null; + } + gl.attachShader(program, vs); + gl.attachShader(program, fs); + gl.linkProgram(program); + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + canvas.remove(); + return null; + } + gl.useProgram(program); + gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW); + const position = gl.getAttribLocation(program, 'a'); + gl.enableVertexAttribArray(position); + gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0); + const uRes = gl.getUniformLocation(program, 'uRes'); + const uDpr = gl.getUniformLocation(program, 'uDpr'); + const uT = gl.getUniformLocation(program, 'uT'); + const uCam = gl.getUniformLocation(program, 'uCam'); + gl.uniform1f(gl.getUniformLocation(program, 'uHaze'), opts.haze === false ? 0 : 1); + + // The picture's resolution: the screen's, capped at 2, scaled down when frames come slow. + let quality = 1; + let offset: [number, number] = [0, 0]; + const resize = () => { + const cssWidth = box.clientWidth || FRAME_WIDTH; + const cssHeight = box.clientHeight || opts.frame; + const ratio = Math.min(2, Math.max(1, window.devicePixelRatio || 1)) * quality; + canvas.width = Math.max(1, Math.round(cssWidth * ratio)); + canvas.height = Math.max(1, Math.round(cssHeight * ratio)); + canvas.style.height = `${cssHeight}px`; + gl.viewport(0, 0, canvas.width, canvas.height); + gl.uniform2f(uRes, canvas.width, canvas.height); + gl.uniform1f(uDpr, canvas.width / cssWidth); + // The scene is framed for a phone: a bigger box shows more around the same + // centre, a smaller one (a small iPhone) the middle of it. + offset = [(cssWidth - FRAME_WIDTH) / 2, (cssHeight - opts.frame) / 2]; + }; + resize(); + + const still = reducedMotion(); + const born = performance.now(); + let camera: [number, number] = [opts.camera?.[0] ?? 0, opts.camera?.[1] ?? 0]; + let flight: { from: [number, number]; to: Camera; start: number; duration: number } | null = null; + let running = false; + let lastFrame = 0; + let measured = 0; + let slowFrames = 0; + + const draw = (now: number) => { + if (flight) { + const k = Math.min(1, (now - flight.start) / flight.duration); + const e = k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2; + camera = [ + flight.from[0] + (flight.to[0] - flight.from[0]) * e, + flight.from[1] + (flight.to[1] - flight.from[1]) * e, + ]; + if (k >= 1) flight = null; + } + gl.uniform2f(uCam, camera[0] - offset[0], camera[1] - offset[1]); + gl.uniform1f(uT, still ? 4 : (now - born) / 1000 + 4); + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + }; + + const frame = (now: number) => { + if (!canvas.isConnected || document.hidden) { + running = false; + return; + } + // A device that cannot keep up gets a smaller picture once, rather than a stutter. + if (lastFrame && quality === 1 && measured < 90) { + measured += 1; + if (now - lastFrame > 24) slowFrames += 1; + if (measured === 90 && slowFrames > 45) { + quality = 0.7; + resize(); + } + } + lastFrame = now; + draw(now); + if (!still || flight) requestAnimationFrame(frame); + else running = false; + }; + const run = () => { + if (running) return; + running = true; + lastFrame = 0; + requestAnimationFrame(frame); + }; + run(); + + // The loop stops in the background (document.hidden) and starts again on return. + const wake = () => { + if (!document.hidden && canvas.isConnected) run(); + }; + document.addEventListener('visibilitychange', wake); + if (typeof ResizeObserver === 'function') { + const observer = new ResizeObserver(() => { + if (!canvas.isConnected) { + observer.disconnect(); + document.removeEventListener('visibilitychange', wake); + return; + } + resize(); + if (still) run(); + }); + observer.observe(box); + } + canvas.addEventListener('webglcontextlost', (event) => { + event.preventDefault(); + canvas.remove(); + }); + + return { + flyTo(to: Camera) { + if (still) { + camera = [to[0], to[1]]; + run(); + return; + } + const distance = Math.hypot(to[0] - camera[0], to[1] - camera[1]); + flight = { + from: [camera[0], camera[1]], + to, + start: performance.now(), + duration: Math.min(1700, 700 + distance * 1.1), + }; + run(); + }, + }; +} diff --git a/client/native-shell/shell.css b/client/native-shell/shell.css new file mode 100644 index 000000000..2e64792af --- /dev/null +++ b/client/native-shell/shell.css @@ -0,0 +1,1414 @@ +/* + * The first screens the app ships itself: welcome, plans, address, an own + * server, and the states between. Light, on a landscape seen from above + * (scenery.ts). Everything past them is the UI the chosen server delivers. + * + * Every side is a logical one (inline start and end), so Arabic and Hebrew + * mirror the layout without rules of their own. + */ + +/* + * TREK's own type, self-hosted (latin subset, bundled: the shell loads offline + * and hotlinks nothing). Poppins sets the headlines and prices. Poppins has no + * Cyrillic, so Russian and Ukrainian get Montserrat under the same family name, + * loaded only when a Cyrillic letter is on screen. + */ +@font-face { + font-family: 'Poppins'; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url('./fonts/poppins-latin-500.woff2') format('woff2'); +} +@font-face { + font-family: 'Poppins'; + font-style: normal; + font-weight: 600; + font-display: swap; + src: url('./fonts/poppins-latin-600.woff2') format('woff2'); +} +@font-face { + font-family: 'Poppins'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url('./fonts/poppins-latin-700.woff2') format('woff2'); +} +@font-face { + font-family: 'Poppins'; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url('./fonts/montserrat-cyrillic-500.woff2') format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +@font-face { + font-family: 'Poppins'; + font-style: normal; + font-weight: 600; + font-display: swap; + src: url('./fonts/montserrat-cyrillic-600.woff2') format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +@font-face { + font-family: 'Poppins'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url('./fonts/montserrat-cyrillic-700.woff2') format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* + * Plus Jakarta Sans, the text face of the first screens: Latin and Latin + * Extended (Czech, Polish, Turkish, Vietnamese letters), each loaded only when + * a letter of its range is on screen. Cyrillic borrows Montserrat under the same + * family name, as Poppins does. + */ +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url('./fonts/plus-jakarta-sans-latin-400.woff2') format('woff2'); + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, + U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url('./fonts/plus-jakarta-sans-latin-500.woff2') format('woff2'); + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, + U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 600; + font-display: swap; + src: url('./fonts/plus-jakarta-sans-latin-600.woff2') format('woff2'); + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, + U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url('./fonts/plus-jakarta-sans-latin-700.woff2') format('woff2'); + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, + U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 800; + font-display: swap; + src: url('./fonts/plus-jakarta-sans-latin-800.woff2') format('woff2'); + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, + U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url('./fonts/plus-jakarta-sans-latin-ext-400.woff2') format('woff2'); + unicode-range: + U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, + U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url('./fonts/plus-jakarta-sans-latin-ext-500.woff2') format('woff2'); + unicode-range: + U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, + U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 600; + font-display: swap; + src: url('./fonts/plus-jakarta-sans-latin-ext-600.woff2') format('woff2'); + unicode-range: + U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, + U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url('./fonts/plus-jakarta-sans-latin-ext-700.woff2') format('woff2'); + unicode-range: + U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, + U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 800; + font-display: swap; + src: url('./fonts/plus-jakarta-sans-latin-ext-800.woff2') format('woff2'); + unicode-range: + U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, + U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url('./fonts/montserrat-cyrillic-500.woff2') format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 600; + font-display: swap; + src: url('./fonts/montserrat-cyrillic-600.woff2') format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url('./fonts/montserrat-cyrillic-700.woff2') format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} + +:root { + --page: #fffaf5; + --ink: #1f1a17; + --text: #6b5f57; + --muted: #8a7b6f; + --faint: #b9ab9e; + --line: #efe4d8; + --line-soft: #f3ebe1; + --sand: #f6efe6; + --dark: #111827; + --good: #1d7a46; + --bad: #b42318; + --sea: #cfe3ef; + --text-face: 'Plus Jakarta Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; + --display-face: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; + /* The insets of the device, from the web view or, on iOS, from the native side. */ + --safe-top: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px)); + --safe-bottom: max(env(safe-area-inset-bottom, 0px), var(--trek-native-safe-bottom, 0px)); + --safe-start: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px)); + --safe-end: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px)); + color-scheme: light; + -webkit-text-size-adjust: 100%; +} + +* { + box-sizing: border-box; + -webkit-tap-highlight-color: transparent; +} +html, +body { + margin: 0; + height: 100%; + background: var(--page); + color: var(--ink); + font-family: var(--text-face); + overscroll-behavior: none; +} +button, +input { + font: inherit; +} +:focus-visible { + outline: 2px solid var(--dark); + outline-offset: 2px; +} + +/* The page: one screen at a time, each its own scroller. */ +.shell { + position: fixed; + inset: 0; + overflow-x: clip; +} +.scr { + position: absolute; + inset: 0; + overflow-x: hidden; + overflow-y: auto; + scrollbar-width: none; + display: flex; + flex-direction: column; + padding-bottom: 30px; + background: var(--page); +} +.scr::-webkit-scrollbar { + display: none; +} +.scr.enter { + animation: scrIn 0.42s cubic-bezier(0.2, 0.8, 0.2, 1) both; +} +.scr.enter.reverse { + animation-name: scrInBack; +} +:root[dir='rtl'] .scr.enter { + animation-name: scrInBack; +} +:root[dir='rtl'] .scr.enter.reverse { + animation-name: scrIn; +} +@keyframes scrIn { + from { + opacity: 0; + transform: translateX(22px); + } + to { + opacity: 1; + transform: none; + } +} +@keyframes scrInBack { + from { + opacity: 0; + transform: translateX(-22px); + } + to { + opacity: 1; + transform: none; + } +} +/* On a phone the content flows in the screen's own column. */ +.body { + display: contents; +} + +/* ── The landscape at the top ── */ +.hero { + position: relative; + flex: none; + overflow: hidden; + background: var(--sea); + margin-bottom: -1px; + height: min(300px, 36svh); +} +.hero.tall { + height: min(320px, 38svh); +} +.hero.welcome { + height: min(376px, 44.5svh); + min-height: 250px; +} +.hero .scenery { + position: absolute; + inset: 0; + width: 100%; + height: 100%; +} +/* The status bar's clock and icons stay readable on the sea. */ +.hero::before { + content: ''; + position: absolute; + z-index: 1; + inset-inline: 0; + top: 0; + height: calc(var(--safe-top) + 36px); + background: linear-gradient(180deg, rgba(8, 24, 40, 0.28), rgba(8, 24, 40, 0)); + pointer-events: none; +} +.hero::after { + content: ''; + position: absolute; + inset-inline: 0; + bottom: -2px; + height: 110px; + background: linear-gradient( + 180deg, + rgba(255, 250, 245, 0) 0%, + rgba(255, 250, 245, 0.8) 55%, + #fffaf5 82%, + #fffaf5 100% + ); + pointer-events: none; +} +.hero.welcome::after { + height: 18px; + background: linear-gradient(180deg, rgba(255, 250, 245, 0), #fffaf5 88%); +} +.logo { + position: absolute; + z-index: 2; + top: calc(var(--safe-top) + 10px); + inset-inline-start: calc(24px + var(--safe-start)); + height: 40px; + filter: drop-shadow(0 1px 6px rgba(7, 40, 70, 0.45)); +} +.back { + position: absolute; + z-index: 3; + top: calc(var(--safe-top) + 8px); + inset-inline-start: calc(20px + var(--safe-start)); + width: 40px; + height: 40px; + display: grid; + place-items: center; + border: 0; + border-radius: 999px; + background: #fff; + color: var(--ink); + cursor: pointer; + box-shadow: 0 6px 16px -8px rgba(0, 0, 0, 0.5); +} +:root[dir='rtl'] .back svg, +:root[dir='rtl'] .flip { + transform: scaleX(-1); +} + +/* ── The glass card over the landscape ── */ +.card { + position: absolute; + z-index: 2; + inset-inline: calc(20px + var(--safe-start)) calc(20px + var(--safe-end)); + /* Lower in a short landscape (the keyboard is up), so it never meets the back button. */ + bottom: clamp(18px, calc(100% - 242px), 78px); + padding: 12px 16px 14px; + border-radius: 18px; + background: rgba(255, 255, 255, 0.8); + -webkit-backdrop-filter: blur(16px) saturate(1.5); + backdrop-filter: blur(16px) saturate(1.5); + box-shadow: + 0 18px 36px -18px rgba(17, 24, 39, 0.55), + inset 0 0 0 1px rgba(255, 255, 255, 0.6); +} +.card small { + display: flex; + align-items: center; + gap: 6px; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.1em; + text-transform: uppercase; + color: var(--text); +} +.card.ok small { + color: var(--good); +} +.card.bad small, +.card.bad .url i { + color: var(--bad); +} +.url { + display: flex; + align-items: center; + gap: 8px; + margin-top: 6px; + min-width: 0; +} +.url i { + display: flex; + flex: none; + color: var(--dark); +} +.url-text { + font-family: var(--display-face); + font-size: 22px; + font-weight: 600; + letter-spacing: -0.02em; + white-space: nowrap; + overflow: hidden; + min-width: 0; +} +.url-text b { + font-weight: 600; + color: var(--dark); +} +.url-text b.ph { + color: #a99a8c; +} +.url-text span { + color: var(--muted); + font-weight: 500; +} +.caret { + display: inline-block; + width: 2px; + height: 1.05em; + margin: 0 1px; + vertical-align: -0.17em; + background: var(--dark); + border-radius: 2px; + animation: blink 1.1s steps(1) infinite; +} +.card:not(.typing) .caret { + display: none; +} +@keyframes blink { + 50% { + opacity: 0; + } +} +.spin { + width: 10px; + height: 10px; + border-radius: 50%; + border: 2px solid var(--text); + border-top-color: transparent; + animation: spin 0.8s linear infinite; +} +.cta .spin { + width: 16px; + height: 16px; + border-color: #fff; + border-top-color: transparent; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +/* ── Content ── */ +.pad { + position: relative; + z-index: 2; + display: flex; + flex-direction: column; + gap: 14px; + padding-inline: calc(24px + var(--safe-start)) calc(24px + var(--safe-end)); +} +.pad.grow { + flex: 1; + margin-top: -30px; +} +.pad.lift { + margin-top: -34px; + gap: 16px; +} +.pad.lift + .pad { + margin-top: 16px; +} +.stack { + display: flex; + flex-direction: column; + gap: 16px; + width: 100%; +} +.pad.form { + margin-top: 2px; + gap: 12px; +} +.push { + flex: 1; + min-height: 0; +} +h1 { + margin: 0; + font-family: var(--display-face); + font-weight: 600; + font-size: 36px; + letter-spacing: -0.025em; + line-height: 1.08; + text-wrap: balance; +} +.lead { + margin: 0; + font-size: 16px; + line-height: 1.55; + color: var(--text); +} +.title { + font-size: 26px; + letter-spacing: -0.02em; +} +.sub { + margin: -4px 0 0; + font-size: 14.5px; + line-height: 1.5; + color: var(--text); +} +.sub b { + color: var(--ink); +} +.perks { + display: flex; + flex-direction: column; + margin-top: 4px; + padding: 2px 16px; + border-radius: 18px; + background: #fff; + box-shadow: + 0 0 0 1px var(--line), + 0 14px 28px -24px rgba(31, 26, 23, 0.6); +} +.perks div { + display: flex; + align-items: center; + gap: 13px; + padding: 8px 0; +} +.perks div + div { + border-top: 1px solid var(--line-soft); +} +.perks i { + width: 34px; + height: 34px; + flex: none; + border-radius: 10px; + background: var(--dark); + color: #fff; + display: grid; + place-items: center; +} +.perks b { + display: block; + font-size: 14.5px; + font-weight: 800; +} +.perks small { + display: block; + font-size: 12.5px; + color: var(--muted); + margin-top: 1px; +} +.btns { + display: flex; + flex-direction: column; + gap: 8px; +} + +/* ── Buttons ── */ +.cta, +.cta2 { + width: 100%; + border: 0; + border-radius: 16px; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + text-align: center; + text-decoration: none; + transition: transform 0.15s; +} +.cta { + min-height: 58px; + background: var(--dark); + color: #fff; + font: 700 17px var(--text-face); + box-shadow: 0 14px 28px -14px rgba(17, 24, 39, 0.55); +} +.cta2 { + min-height: 52px; + background: #fff; + color: var(--dark); + font: 700 16px var(--text-face); + box-shadow: 0 0 0 1.5px var(--ink); +} +.cta:active, +.cta2:active { + transform: scale(0.985); +} +.cta:disabled { + opacity: 0.7; + cursor: default; +} +.link { + display: block; + margin: 6px auto 0; + padding: 8px; + border: 0; + background: none; + color: var(--text); + font: 600 15px var(--text-face); + cursor: pointer; +} +.link.msg { + font-size: 12.5px; + color: var(--muted); +} +.dock { + position: sticky; + bottom: -30px; + z-index: 3; + margin-top: auto; + padding-block: 22px calc(30px + var(--safe-bottom)); + padding-inline: calc(24px + var(--safe-start)) calc(24px + var(--safe-end)); + background: linear-gradient(180deg, rgba(255, 250, 245, 0), #fffaf5 34%); +} +.dock .cta2 { + margin-top: 8px; +} +.fine { + margin: 10px 0 0; + text-align: center; + font-size: 12px; + font-weight: 500; + color: var(--muted); +} +.diag { + margin: 10px 0 0; + text-align: center; + font: + 500 11px ui-monospace, + 'SF Mono', + Menlo, + monospace; + color: #a99a8c; + overflow-wrap: anywhere; +} + +/* ── Plans ── */ +.tiers { + display: grid; + grid-auto-flow: column; + grid-auto-columns: minmax(0, 1fr); + gap: 4px; + padding: 4px; + border-radius: 16px; + background: var(--line-soft); +} +.tiers button { + border: 0; + border-radius: 12px; + padding: 10px 0; + background: transparent; + font: 700 14px var(--text-face); + color: var(--text); + cursor: pointer; + transition: + background 0.2s, + color 0.2s; +} +.tiers button[aria-checked='true'] { + background: #fff; + color: var(--ink); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12); +} +.trip { + min-width: 0; + margin-top: 10px; +} +.trip h1 { + font-size: 28px; + display: flex; + align-items: center; + gap: 10px; + white-space: nowrap; +} +.trip p { + margin: 6px 0 0; + color: var(--text); + font-size: 14px; + line-height: 1.4; +} +.badge { + font-family: var(--text-face); + font-size: 11px; + font-weight: 700; + letter-spacing: 0.04em; + padding: 4px 10px; + border-radius: 999px; + background: var(--dark); + color: #fff; +} +.pricebox { + display: flex; + flex-direction: column; + padding: 6px 6px 16px; + border-radius: 20px; + background: #fff; + box-shadow: + 0 0 0 1px var(--line), + 0 16px 30px -24px rgba(31, 26, 23, 0.55); +} +.cycle { + position: relative; + display: grid; + grid-template-columns: 1fr 1fr; + padding: 4px; + border-radius: 15px; + background: var(--sand); +} +.cycle .thumb { + position: absolute; + top: 4px; + bottom: 4px; + inset-inline-start: 4px; + width: calc(50% - 4px); + border-radius: 11px; + background: var(--dark); + box-shadow: 0 4px 10px -4px rgba(17, 24, 39, 0.5); + transition: transform 0.32s cubic-bezier(0.2, 0.8, 0.2, 1); +} +.cycle[data-year='true'] .thumb { + transform: translateX(100%); +} +:root[dir='rtl'] .cycle[data-year='true'] .thumb { + transform: translateX(-100%); +} +.cycle button { + position: relative; + z-index: 1; + border: 0; + background: transparent; + padding: 9px 0; + font: 600 14px var(--text-face); + color: var(--text); + cursor: pointer; + transition: color 0.25s; +} +.cycle button[aria-checked='true'] { + color: #fff; +} +.price { + display: flex; + align-items: baseline; + justify-content: center; + gap: 8px; + margin-top: 18px; +} +.price b { + font-family: var(--display-face); + font-size: 40px; + font-weight: 600; + letter-spacing: -0.02em; + line-height: 1; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} +.price span { + color: var(--text); + font-size: 14px; + font-weight: 600; +} +.equals { + margin-top: 6px; + text-align: center; + font-size: 13px; + font-weight: 600; + color: var(--muted); +} +.equals:empty { + display: none; +} +.specs { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; +} +.spec { + display: flex; + align-items: center; + gap: 10px; + min-width: 0; + padding: 10px 12px; + border-radius: 14px; + background: #fff; + box-shadow: 0 0 0 1px var(--line); +} +.spec i { + width: 32px; + height: 32px; + flex: none; + border-radius: 10px; + display: grid; + place-items: center; + background: var(--sand); + color: var(--dark); +} +.spec b { + display: block; + font-size: 14px; + font-weight: 800; + line-height: 1.2; + white-space: nowrap; +} +.spec small { + display: block; + font-size: 11.5px; + color: var(--muted); + font-weight: 600; + line-height: 1.25; + white-space: nowrap; +} +.spec.off i { + color: var(--faint); +} +.spec.off b { + color: var(--muted); +} +.spec.wide { + grid-column: 1 / -1; +} +.spec.wide em { + margin-inline-start: auto; + font-style: normal; + font-size: 11.5px; + font-weight: 700; + color: var(--text); + background: var(--sand); + padding: 4px 9px; + border-radius: 999px; + white-space: nowrap; +} +.legal { + margin: 2px 0 0; + font-size: 11.5px; + line-height: 1.5; + color: var(--muted); + text-align: center; + text-wrap: pretty; +} +.legal-links { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 4px 12px; + margin-top: -4px; +} +.legal-links a, +.agree a { + font-size: 11.5px; + font-weight: 600; + color: var(--text); + text-decoration: underline; + text-underline-offset: 2px; + text-decoration-color: #d9cbbb; +} +.loading { + display: grid; + place-items: center; + min-height: 160px; +} +.loading .spin { + width: 22px; + height: 22px; +} + +/* ── Address and sign-up ── */ +.plan-row { + display: flex; + align-items: center; + justify-content: space-between; + padding-block: 10px; + padding-inline: 16px 10px; + border-radius: 14px; + background: var(--sand); +} +.plan-row > span { + display: flex; + align-items: center; + gap: 10px; + min-width: 0; +} +.plan-row b { + font-size: 12.5px; + font-weight: 700; + letter-spacing: 0.02em; + color: #fff; + background: var(--dark); + padding: 4px 11px; + border-radius: 999px; +} +.plan-row small { + font-size: 13.5px; + font-weight: 600; + color: var(--text); +} +.plan-row button { + border: 0; + background: #fff; + border-radius: 10px; + padding: 7px 12px; + font: 700 13px var(--text-face); + color: var(--dark); + cursor: pointer; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); +} +.fld { + position: relative; + margin-top: 8px; + display: flex; + flex-direction: column; + gap: 2px; + padding: 10px 16px 11px; + border-radius: 16px; + background: #fff; + box-shadow: 0 0 0 1px var(--line); + cursor: text; + transition: box-shadow 0.2s; +} +.fld:focus-within { + box-shadow: 0 0 0 2px var(--dark); +} +.fld.bad { + box-shadow: 0 0 0 2px var(--bad); + animation: shake 0.35s; +} +@keyframes shake { + 25% { + transform: translateX(-4px); + } + 75% { + transform: translateX(4px); + } +} +.fld .lab { + font-size: 12px; + font-weight: 700; + color: var(--muted); +} +.fld .row { + display: flex; + align-items: center; + gap: 4px; + min-width: 0; +} +.fld input { + flex: 1; + min-width: 0; + border: 0; + outline: none; + background: transparent; + padding: 0; + font: 600 16px var(--text-face); + color: var(--ink); +} +.fld input::placeholder { + color: var(--faint); +} +.fld input:disabled { + opacity: 0.6; +} +.fld em { + font-style: normal; + font-weight: 600; + font-size: 15px; + color: var(--muted); +} +/* A badge on the card's edge: free, a rule met. */ +.fld .edge { + position: absolute; + top: -10px; + inset-inline-end: 14px; + display: inline-flex; + align-items: center; + gap: 4px; + padding: 3px 9px; + border-radius: 999px; + font-size: 11px; + font-weight: 700; + color: var(--muted); + background: #f1e7db; + box-shadow: 0 0 0 3px var(--page); + transition: + background 0.2s, + color 0.2s; +} +.fld .edge.on { + color: #fff; + background: var(--good); + animation: pop 0.3s cubic-bezier(0.2, 0.8, 0.2, 1); +} +@keyframes pop { + from { + opacity: 0; + transform: translateY(4px); + } + to { + opacity: 1; + transform: none; + } +} +.fld .note { + margin: 4px 0 0; + font-size: 12.5px; + font-weight: 600; + color: var(--bad); +} +.fld .note:empty { + display: none; +} +.rules { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 8px; +} +.rules span { + font-size: 11px; + font-weight: 700; + color: var(--muted); + background: var(--sand); + padding: 3px 9px; + border-radius: 999px; + transition: + background 0.2s, + color 0.2s; +} +.rules span.met { + color: #fff; + background: var(--good); +} +.eye { + display: flex; + padding: 2px; + border: 0; + background: transparent; + color: var(--muted); + cursor: pointer; +} +.agree { + margin: 2px 0 0; + font-size: 11.5px; + line-height: 1.5; + color: var(--muted); + text-align: center; + text-wrap: pretty; +} +.consent { + display: flex; + gap: 12px; + align-items: flex-start; + padding: 14px 16px; + border-radius: 16px; + background: #fff; + box-shadow: 0 0 0 1px var(--line); + font-size: 12.5px; + line-height: 1.5; + color: var(--text); + cursor: pointer; +} +.consent.bad { + box-shadow: 0 0 0 2px var(--bad); + animation: shake 0.35s; +} +.consent input { + appearance: none; + -webkit-appearance: none; + flex: none; + width: 22px; + height: 22px; + margin: 1px 0 0; + border-radius: 7px; + box-shadow: inset 0 0 0 2px #e6dccf; + background: #fff center / 14px no-repeat; + cursor: pointer; + transition: + background-color 0.2s, + box-shadow 0.2s; +} +.consent input:checked { + background-color: var(--dark); + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='3.2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M5 12.5l4.5 4.5L19 7.5'/%3E%3C/svg%3E"); + box-shadow: none; +} +.consent strong { + display: block; + color: var(--ink); + font-weight: 800; + margin-bottom: 2px; +} +.consent-text { + display: block; + max-height: 140px; + overflow-y: auto; + white-space: pre-line; +} + +/* ── Own server ── */ +.notice { + display: flex; + gap: 10px; + align-items: flex-start; + margin: 0; + padding: 12px 14px; + border-radius: 14px; + background: #fbeeec; + color: #8f2a1d; + font-size: 13.5px; + font-weight: 600; + line-height: 1.45; +} +.notice:empty { + display: none; +} +.notice i { + display: flex; + flex: none; + margin-top: 1px; +} +.side { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + padding: 13px 16px; + border: 0; + border-radius: 16px; + background: #fff; + box-shadow: 0 0 0 1px var(--line); + font: 600 14.5px var(--text-face); + color: var(--ink); + text-align: start; + cursor: pointer; +} +.side svg { + flex: none; + color: var(--dark); +} +.panel { + display: flex; + flex-direction: column; + gap: 10px; + padding: 16px; + border-radius: 18px; + background: #fff; + box-shadow: + 0 0 0 1px var(--line), + 0 16px 30px -26px rgba(31, 26, 23, 0.6); +} +.panel[hidden], +[hidden] { + display: none !important; +} +.panel-head { + display: flex; + gap: 12px; + align-items: center; +} +.panel-head i { + width: 36px; + height: 36px; + flex: none; + border-radius: 11px; + background: var(--dark); + color: #fff; + display: grid; + place-items: center; +} +.panel-head b { + font-size: 15px; + font-weight: 800; + line-height: 1.3; +} +.panel p { + margin: 0; + font-size: 13.5px; + line-height: 1.5; + color: var(--text); +} +.panel p b { + color: var(--ink); +} +.panel .panel-note { + font-size: 12px; + color: var(--muted); +} +.panel .panel-status { + color: var(--bad); + font-weight: 600; +} +.panel .panel-status:empty { + display: none; +} +.panel-btn { + min-height: 46px; + border: 0; + border-radius: 13px; + background: var(--dark); + color: #fff; + font: 700 15px var(--text-face); + cursor: pointer; +} +.panel-btn:disabled { + opacity: 0.7; +} +.panel-help { + display: inline-flex; + align-items: center; + gap: 4px; + align-self: flex-start; + font-size: 13px; + font-weight: 700; + color: var(--ink); + text-decoration: none; +} +.status-line { + margin: 0; + font-size: 13.5px; + font-weight: 600; + color: var(--text); +} +.status-line:empty { + display: none; +} +.status-line.bad { + color: var(--bad); +} +/* A panel needs the room: the landscape steps back while it is open. */ +.hero.tall { + transition: height 0.45s cubic-bezier(0.2, 0.8, 0.2, 1); +} +.scr.compact .hero.tall { + height: min(214px, 26svh); +} +.scr.compact .card { + bottom: 30px; +} +.scr.compact .sub { + display: none; +} + +/* ── Setting up ── */ +.steps { + display: flex; + flex-direction: column; + padding: 4px 16px; + border-radius: 18px; + background: #fff; + box-shadow: 0 0 0 1px var(--line); +} +.steps span { + display: flex; + align-items: center; + gap: 12px; + padding: 11px 0; + font-size: 14.5px; + font-weight: 700; + color: var(--faint); + transition: color 0.3s; +} +.steps span + span { + border-top: 1px solid var(--line-soft); +} +.steps span::before { + content: ''; + flex: none; + width: 18px; + height: 18px; + border-radius: 50%; + box-shadow: inset 0 0 0 2px #e6dccf; + transition: all 0.3s; +} +.steps span.on { + color: var(--ink); +} +.steps span.on::before { + background: var(--good) + url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='3.2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M5 12.5l4.5 4.5L19 7.5'/%3E%3C/svg%3E") + center / 12px no-repeat; + box-shadow: none; +} + +/* + * Wide screens (an iPad, an unfolded phone) and a phone on its side: two + * columns, the landscape at full height on one side, the content beside it in + * a column of its own that scrolls on its own. + */ +@media (min-width: 900px), (orientation: landscape) and (max-height: 500px) { + .scr { + flex-direction: row; + padding: 0; + overflow: hidden; + } + .hero, + .hero.tall, + .hero.welcome, + .scr.compact .hero.tall { + flex: 1 1 auto; + height: 100%; + min-height: 0; + margin: 0; + } + .hero::after { + display: none; + } + .body { + flex: none; + width: 460px; + height: 100%; + display: flex; + flex-direction: column; + overflow-x: hidden; + overflow-y: auto; + scrollbar-width: none; + padding-top: calc(var(--safe-top) + 48px); + background: var(--page); + box-shadow: -1px 0 0 rgba(31, 26, 23, 0.06); + } + .body::-webkit-scrollbar { + display: none; + } + .pad.grow, + .pad.lift, + .pad.form { + margin-top: 0; + } + .pad.grow { + justify-content: center; + } + .pad.grow .push { + flex: 0 0 18px; + } + .scr.compact .sub { + display: block; + } + .card { + inset-inline: calc(32px + var(--safe-start)) auto; + width: min(420px, calc(100% - 64px)); + bottom: 40px; + } + .logo { + top: calc(var(--safe-top) + 24px); + inset-inline-start: calc(32px + var(--safe-start)); + height: 46px; + } + .back { + top: calc(var(--safe-top) + 20px); + inset-inline-start: calc(28px + var(--safe-start)); + } + .pad, + .dock { + padding-inline: 24px calc(24px + var(--safe-end)); + } +} +/* A phone on its side has little height: the column is narrower and starts higher. */ +@media (orientation: landscape) and (max-height: 500px) { + .body { + width: min(420px, 52vw); + padding-top: calc(var(--safe-top) + 20px); + } +} +/* Two screens with a hinge between them: the landscape on one, the content on the other. */ +@media (horizontal-viewport-segments: 2) { + .hero, + .hero.tall, + .hero.welcome, + .scr.compact .hero.tall { + flex: none; + width: env(viewport-segment-width 0 0); + } + .body { + width: env(viewport-segment-width 1 0); + margin-inline-start: calc(env(viewport-segment-left 1 0) - env(viewport-segment-right 0 0)); + } +} + +@media (prefers-reduced-motion: reduce) { + .scr.enter, + .scr * { + animation: none !important; + transition: none !important; + } +} diff --git a/client/package.json b/client/package.json index ad95d896b..ede6a4105 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "@trek/client", - "version": "5.1.0", + "version": "5.1.4", "engines": { "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, @@ -9,7 +9,16 @@ "scripts": { "dev": "vite", "prebuild": "node scripts/generate-icons.mjs", + "icons:native": "node scripts/generate-native-icons.mjs", + "icons:app": "node scripts/generate-app-icons.mjs && npx @capacitor/assets generate --android --ios --iconBackgroundColor #09090b --iconBackgroundColorDark #09090b --splashBackgroundColor #09090b --splashBackgroundColorDark #09090b && node scripts/generate-adaptive-icons.mjs", + "build:native": "vite build --config vite.native.config.js", + "cap:sync": "npm run build:native && cap sync", + "store:shots": "playwright test --project=store", + "store:promote": "node scripts/store-screenshots.mjs", + "store:graphic": "node scripts/generate-feature-graphic.mjs", + "store:check": "node scripts/check-store-metadata.mjs", "build": "vite build", + "postbuild": "node scripts/precompress.mjs", "build:analyze": "vite build --mode analyze", "preview": "vite preview", "typecheck": "tsc --noEmit", @@ -44,7 +53,19 @@ "format:check": "prettier --check \"src/**/*.tsx\" \"src/**/*.css\"" }, "dependencies": { - "@assistant-ui/react": "0.15.25", + "@assistant-ui/react": "0.15.36", + "@capacitor/action-sheet": "^8.1.1", + "@capacitor/android": "^8.6.2", + "@capacitor/app": "^8.1.1", + "@capacitor/core": "^8.6.2", + "@capacitor/dialog": "^8.0.1", + "@capacitor/filesystem": "^8.1.3", + "@capacitor/haptics": "^8.0.2", + "@capacitor/ios": "^8.6.2", + "@capacitor/keyboard": "^8.0.5", + "@capacitor/share": "^8.0.1", + "@capacitor/splash-screen": "^8.0.2", + "@capacitor/status-bar": "^8.0.3", "@fontsource/abril-fatface": "^5.3.0", "@fontsource/alfa-slab-one": "^5.3.0", "@fontsource/allura": "^5.3.0", @@ -80,23 +101,23 @@ "@fontsource/satisfy": "^5.3.0", "@fontsource/shrikhand": "^5.3.0", "@fontsource/yellowtail": "^5.3.0", - "@mapbox/mapbox-gl-rtl-text": "^0.4.0", "@maplibre/maplibre-gl-leaflet": "0.1.4", + "@noble/hashes": "^1.8.0", "@simplewebauthn/browser": "^13.3.0", "@trek/shared": "*", - "axios": "^1.20.0", - "dexie": "^4.4.6", + "axios": "^1.21.0", + "dexie": "^4.4.7", "drag-drop-touch": "^1.3.1", - "heic-to": "^1.5.2", + "heic-to": "^1.6.7", "iso-3166-2": "^1.0.0", "leaflet": "^1.9.4", "lucide-react": "^0.577.0", - "mapbox-gl": "^3.31.0", - "maplibre-gl": "6.15.0", + "mapbox-gl": "^3.35.0", + "maplibre-gl": "6.18.0", "modern-screenshot": "4.7.0", - "plyr": "^3.8.4", - "react": "^19.3.0", - "react-dom": "^19.3.0", + "plyr": "^3.8.5", + "react": "^19.3.1", + "react-dom": "^19.3.1", "react-dropzone": "^14.4.1", "react-leaflet": "^5.0.0", "react-leaflet-cluster": "^4.1.3", @@ -110,40 +131,41 @@ "zustand": "^5.0.15" }, "devDependencies": { + "@capacitor/cli": "^8.6.2", "@eslint/js": "^10.0.1", "@jscpd/core": "^4.2.5", "@jscpd/tokenizer": "^4.2.6", - "@playwright/test": "^1.63.0", + "@playwright/test": "^1.65.0", "@testing-library/jest-dom": "^6.10.0", "@testing-library/react": "^16.3.3", - "@testing-library/user-event": "^14.6.7", + "@testing-library/user-event": "^14.6.10", "@trivago/prettier-plugin-sort-imports": "^6.0.2", "@types/leaflet": "^1.9.22", "@types/node": "^25.9.8", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", - "@vitejs/plugin-react": "^6.1.1", - "@vitest/coverage-v8": "^4.1.11", - "autoprefixer": "^10.6.1", + "@vitejs/plugin-react": "^6.2.1", + "@vitest/coverage-v8": "^4.1.12", + "autoprefixer": "^10.6.2", "eslint": "^10.11.0", "eslint-config-flat-gitignore": "^2.4.0", "eslint-config-prettier": "^10.1.8", "eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-refresh": "^0.5.7", - "fake-indexeddb": "^6.2.5", + "fake-indexeddb": "^6.2.7", "jsdom": "^29.1.1", "msw": "^2.15.0", "postcss": "^8.5.28", - "prettier": "^3.9.8", + "prettier": "^3.10.1", "prettier-plugin-organize-imports": "^4.3.0", "prettier-plugin-tailwindcss": "^0.8.1", - "rollup-plugin-visualizer": "^7.1.1", + "rollup-plugin-visualizer": "^7.1.2", "sharp": "^0.35.5", "tailwindcss": "^3.4.19", "typescript": "^6.0.3", - "typescript-eslint": "^8.70.0", - "vite": "8.3.0", - "vite-plugin-pwa": "^1.3.0", - "vitest": "^4.1.11" + "typescript-eslint": "^8.72.1", + "vite": "8.3.8", + "vite-plugin-pwa": "^2.0.0", + "vitest": "^4.1.12" } } diff --git a/client/playwright.config.ts b/client/playwright.config.ts index 0f5303c82..7edc98986 100644 --- a/client/playwright.config.ts +++ b/client/playwright.config.ts @@ -94,6 +94,15 @@ export default defineConfig({ }, dependencies: ['shot-fixtures'], }, + // App Store and Google Play screenshots (`npm run store:shots`): the + // seeded demo trip at every device size the listings need. Each device sets + // its own viewport and scale in e2e/store/capture.store.ts. Not part of CI. + { + name: 'store', + testMatch: /\.store\.ts/, + use: { ...devices['Desktop Chrome'], storageState: E2E_STATE_FILE }, + dependencies: ['shot-fixtures'], + }, // Help-center media (`npm run help:media`): pictures and walkthroughs for // the in-app guides, generated from the guide definitions in src/help/. // Same seed as the wiki screenshots; its own match so neither run pays diff --git a/client/plyrSpriteAlias.js b/client/plyrSpriteAlias.js new file mode 100644 index 000000000..a0e6d5012 --- /dev/null +++ b/client/plyrSpriteAlias.js @@ -0,0 +1,21 @@ +import { createRequire } from 'node:module'; +import path from 'node:path'; + +/** + * Plyr's icon sprite. The package publishes its JS and CSS entries and nothing + * else, so `plyr/dist/plyr.svg` is refused by the resolver although the file is + * right there. Resolving the entry it does publish and stepping across keeps this + * working wherever npm hoists the package. + * + * Shared by vite.config.js and vitest.config.ts: the build needs it to emit the + * asset, and the test run needs it because a component reaches the same + * specifier. The pattern is a regex so a `?url` suffix survives the rewrite. The player has to point at a copy on this origin + * (#2341): its default is the sprite on cdn.plyr.io, which the CSP refuses. + */ +export const plyrSpriteAlias = { + find: /^plyr\/dist\/plyr\.svg/, + replacement: path.join( + path.dirname(createRequire(import.meta.url).resolve('plyr')), + 'plyr.svg', + ), +}; diff --git a/client/postcss.config.js b/client/postcss.config.js index 2e7af2b7f..81984497d 100644 --- a/client/postcss.config.js +++ b/client/postcss.config.js @@ -1,6 +1,8 @@ +import autoprefixer from 'autoprefixer'; +import tailwindcss from 'tailwindcss'; +import touchHover from './postcss/touchHover.js'; + export default { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -} + // touchHover last: it guards the :hover rules Tailwind has just written too. + plugins: [tailwindcss(), autoprefixer(), touchHover()], +}; diff --git a/client/postcss/touchHover.js b/client/postcss/touchHover.js new file mode 100644 index 000000000..782bc64df --- /dev/null +++ b/client/postcss/touchHover.js @@ -0,0 +1,49 @@ +/** + * Hover styles only while a pointer drives the UI. + * + * A finger has no hover, yet WebKit and Chrome apply :hover to whatever was + * tapped and keep it there until the next tap lands somewhere else. In the + * iOS and Android app that left buttons and rows tinted after every tap, a + * tell of a web page that no native app has. The app marks with + * data-touch-input while a finger is in use (src/native/touchInput.ts), and + * this plugin makes every :hover rule, Tailwind's and our own, wait for that + * mark to be gone. A browser never sets it, so nothing changes there, and an + * iPad with a trackpad clears it on the first pointer move. + * + * The condition sits on the hovered element itself, wrapped in :where(), so a + * rule keeps its specificity and still wins or loses where it did before. A + * :hover after a pseudo-element (::-webkit-slider-thumb:hover) stays as it is: + * nothing may follow it there, and a rule with an invalid selector is dropped + * whole. + */ + +export const TOUCH_INPUT_ATTR = 'data-touch-input'; +const GUARD = `:where(:root:not([${TOUCH_INPUT_ATTR}]) *)`; +// :hover itself, not the escaped `hover\:` inside a Tailwind class name, and not :hover-something. +const HOVER = /(?+~(,]/; + +function compoundBefore(selector, index) { + let i = index - 1; + while (i >= 0 && !COMPOUND_START.test(selector[i])) i--; + return selector.slice(i + 1, index); +} + +export function guardHover(selector) { + if (selector.includes(GUARD)) return selector; + return selector.replace(HOVER, (match, offset) => + compoundBefore(selector, offset).includes('::') ? match : `${match}${GUARD}` + ); +} + +export default function touchHover() { + return { + postcssPlugin: 'trek-touch-hover', + Rule(rule) { + if (!rule.selector.includes(':hover')) return; + const next = rule.selectors.map(guardHover); + if (next.some((s, i) => s !== rule.selectors[i])) rule.selectors = next; + }, + }; +} +touchHover.postcss = true; diff --git a/client/public/native-handoff.js b/client/public/native-handoff.js new file mode 100644 index 000000000..61d8fb827 --- /dev/null +++ b/client/public/native-handoff.js @@ -0,0 +1,43 @@ +// The page /api/auth/native/start answers with runs this (see NativeAuthController.start). +// A browser that ran an older TREK keeps that version's app in its service worker, and +// the worker would answer the handoff page with an app that has no such page. So the +// worker goes first, and the handoff page loads from the server. +(function () { + var script = document.currentScript; + var target = script && script.getAttribute('data-target'); + if (!target || target.indexOf('/native-handoff?') !== 0) return; + var gone = false; + var go = function () { + if (gone) return; + gone = true; + location.replace(target); + }; + // Until the sign-in is handed back to the app, no worker is registered and no + // new version reloads the page (src/native/browserSignInFlag.ts): a tab still + // open on the older TREK keeps its worker alive, and either would bring it back. + try { + localStorage.setItem('trek_native_signin', String(Date.now())); + } catch (e) { + /* site data blocked: the worker is still taken off below */ + } + if (!('serviceWorker' in navigator) || !navigator.serviceWorker.getRegistrations) { + go(); + return; + } + // Never stuck here: whatever the browser does with the workers, the page moves on. + var timer = setTimeout(go, 3000); + navigator.serviceWorker + .getRegistrations() + .then(function (registrations) { + return Promise.all( + registrations.map(function (registration) { + return registration.unregister(); + }) + ); + }) + .catch(function () {}) + .then(function () { + clearTimeout(timer); + go(); + }); +})(); diff --git a/client/public/registerSW.js b/client/public/registerSW.js new file mode 100644 index 000000000..f33c88e72 --- /dev/null +++ b/client/public/registerSW.js @@ -0,0 +1,18 @@ +// Registers the service worker, as vite-plugin-pwa's own registerSW.js does; this +// file in public/ takes its place. Not while the app's sign-in runs in this browser +// (src/native/browserSignInFlag.ts): a tab still open on an older TREK keeps that +// version's worker alive, and registering now would bring it back to answer the +// sign-in's next page with an app that has no handoff page. +(function () { + if (!('serviceWorker' in navigator)) return; + try { + var started = Number(localStorage.getItem('trek_native_signin')); + var age = Date.now() - started; + if (started > 0 && age >= 0 && age < 15 * 60 * 1000) return; + } catch (e) { + /* site data blocked: register as usual */ + } + window.addEventListener('load', function () { + navigator.serviceWorker.register('/sw.js', { scope: '/' }); + }); +})(); diff --git a/client/rtlTextAlias.js b/client/rtlTextAlias.js deleted file mode 100644 index 9709c55b1..000000000 --- a/client/rtlTextAlias.js +++ /dev/null @@ -1,39 +0,0 @@ -import { createRequire } from 'node:module'; -import path from 'node:path'; - -/** - * setRTLTextPlugin() takes the URL of a classic script that the GL worker pulls in - * with importScripts. mapbox-gl-rtl-text ships exactly that as - * dist/mapbox-gl-rtl-text.js, but its "exports" field publishes only the ESM/WASM - * entry, so the resolver refuses the subpath. Resolving the entry it does publish - * and stepping across to dist keeps this working wherever npm hoists the package. - * - * Shared by vite.config.js and vitest.config.ts: the build needs it to emit the - * asset, and the test run needs it because a lazily imported engine module reaches - * the same specifier. - * - * The pattern is a regex, not a string key: the import carries a `?url` suffix, - * which a string alias will not match. It is left unanchored on purpose so the - * query survives the rewrite and Vite still emits an asset URL. - */ -export const rtlTextAlias = { - find: /^@mapbox\/mapbox-gl-rtl-text\/dist\/mapbox-gl-rtl-text\.js/, - replacement: path.join( - path.dirname(createRequire(import.meta.url).resolve('@mapbox/mapbox-gl-rtl-text')), - '../dist/mapbox-gl-rtl-text.js', - ), -}; - -/** - * Same shape for Plyr's icon sprite. The package publishes its JS and CSS entries - * and nothing else, so `plyr/dist/plyr.svg` is refused by the resolver although - * the file is right there. The player has to point at a copy on this origin - * (#2341): its default is the sprite on cdn.plyr.io, which the CSP refuses. - */ -export const plyrSpriteAlias = { - find: /^plyr\/dist\/plyr\.svg/, - replacement: path.join( - path.dirname(createRequire(import.meta.url).resolve('plyr')), - 'plyr.svg', - ), -}; diff --git a/client/scripts/android-strings.json b/client/scripts/android-strings.json new file mode 100644 index 000000000..74bcc58b1 --- /dev/null +++ b/client/scripts/android-strings.json @@ -0,0 +1,254 @@ +{ + "en": { + "push_channel_chat": "Trip chat", + "push_channel_trips": "Trip updates", + "push_channel_invites": "Invitations and shares", + "push_channel_name": "General", + "push_channel_tripday": "Travel day", + "push_fallback_body": "New notification", + "push_channel_tripday_description": "The day of a running trip and its next stop." + }, + "ar": { + "push_channel_chat": "دردشة الرحلة", + "push_channel_trips": "تحديثات الرحلة", + "push_channel_invites": "الدعوات والمشاركات", + "push_channel_name": "عام", + "push_channel_tripday": "يوم السفر", + "push_fallback_body": "إشعار جديد", + "push_channel_tripday_description": "يوم الرحلة الجارية ومحطتها التالية." + }, + "az": { + "push_channel_chat": "Səyahət söhbəti", + "push_channel_trips": "Səyahət yenilikləri", + "push_channel_invites": "Dəvətlər və paylaşımlar", + "push_channel_name": "Ümumi", + "push_channel_tripday": "Səyahət günü", + "push_fallback_body": "Yeni bildiriş", + "push_channel_tripday_description": "Davam edən səyahətin günü və növbəti dayanacağı." + }, + "ca": { + "push_channel_chat": "Xat del viatge", + "push_channel_trips": "Novetats del viatge", + "push_channel_invites": "Invitacions i comparticions", + "push_channel_name": "General", + "push_channel_tripday": "Dia de viatge", + "push_fallback_body": "Notificació nova", + "push_channel_tripday_description": "El dia d'un viatge en curs i la seva propera parada." + }, + "cs": { + "push_channel_chat": "Chat výletu", + "push_channel_trips": "Novinky z výletu", + "push_channel_invites": "Pozvánky a sdílení", + "push_channel_name": "Obecné", + "push_channel_tripday": "Cestovní den", + "push_fallback_body": "Nové oznámení", + "push_channel_tripday_description": "Den probíhajícího výletu a jeho další zastávka." + }, + "de": { + "push_channel_chat": "Reise-Chat", + "push_channel_trips": "Neues zur Reise", + "push_channel_invites": "Einladungen und Freigaben", + "push_channel_name": "Allgemein", + "push_channel_tripday": "Reisetag", + "push_fallback_body": "Neue Benachrichtigung", + "push_channel_tripday_description": "Der Tag einer laufenden Reise und der nächste Stopp." + }, + "el": { + "push_channel_chat": "Συνομιλία ταξιδιού", + "push_channel_trips": "Ενημερώσεις ταξιδιού", + "push_channel_invites": "Προσκλήσεις και κοινοποιήσεις", + "push_channel_name": "Γενικά", + "push_channel_tripday": "Ημέρα ταξιδιού", + "push_fallback_body": "Νέα ειδοποίηση", + "push_channel_tripday_description": "Η ημέρα ενός ταξιδιού σε εξέλιξη και η επόμενη στάση του." + }, + "es": { + "push_channel_chat": "Chat del viaje", + "push_channel_trips": "Novedades del viaje", + "push_channel_invites": "Invitaciones y compartidos", + "push_channel_name": "General", + "push_channel_tripday": "Día de viaje", + "push_fallback_body": "Notificación nueva", + "push_channel_tripday_description": "El día de un viaje en curso y su próxima parada." + }, + "et": { + "push_channel_chat": "Reisi vestlus", + "push_channel_trips": "Reisi uudised", + "push_channel_invites": "Kutsed ja jagamised", + "push_channel_name": "Üldine", + "push_channel_tripday": "Reisipäev", + "push_fallback_body": "Uus teavitus", + "push_channel_tripday_description": "Käimasoleva reisi päev ja järgmine peatus." + }, + "fr": { + "push_channel_chat": "Discussion du voyage", + "push_channel_trips": "Nouvelles du voyage", + "push_channel_invites": "Invitations et partages", + "push_channel_name": "Général", + "push_channel_tripday": "Jour de voyage", + "push_fallback_body": "Nouvelle notification", + "push_channel_tripday_description": "La journée d'un voyage en cours et sa prochaine étape." + }, + "he": { + "push_channel_chat": "צ׳אט הטיול", + "push_channel_trips": "עדכוני הטיול", + "push_channel_invites": "הזמנות ושיתופים", + "push_channel_name": "כללי", + "push_channel_tripday": "יום טיול", + "push_fallback_body": "התראה חדשה", + "push_channel_tripday_description": "היום של טיול פעיל והעצירה הבאה שלו." + }, + "hu": { + "push_channel_chat": "Utazási csevegés", + "push_channel_trips": "Utazási hírek", + "push_channel_invites": "Meghívások és megosztások", + "push_channel_name": "Általános", + "push_channel_tripday": "Utazási nap", + "push_fallback_body": "Új értesítés", + "push_channel_tripday_description": "Egy folyamatban lévő utazás napja és a következő megálló." + }, + "id": { + "push_channel_chat": "Obrolan perjalanan", + "push_channel_trips": "Kabar perjalanan", + "push_channel_invites": "Undangan dan berbagi", + "push_channel_name": "Umum", + "push_channel_tripday": "Hari perjalanan", + "push_fallback_body": "Notifikasi baru", + "push_channel_tripday_description": "Hari dari perjalanan yang berlangsung dan perhentian berikutnya." + }, + "it": { + "push_channel_chat": "Chat del viaggio", + "push_channel_trips": "Novità del viaggio", + "push_channel_invites": "Inviti e condivisioni", + "push_channel_name": "Generali", + "push_channel_tripday": "Giorno di viaggio", + "push_fallback_body": "Nuova notifica", + "push_channel_tripday_description": "La giornata di un viaggio in corso e la prossima tappa." + }, + "ja": { + "push_channel_chat": "旅行チャット", + "push_channel_trips": "旅行の更新", + "push_channel_invites": "招待と共有", + "push_channel_name": "一般", + "push_channel_tripday": "旅行日", + "push_fallback_body": "新しい通知", + "push_channel_tripday_description": "進行中の旅行の一日と次の立ち寄り先。" + }, + "ko": { + "push_channel_chat": "여행 채팅", + "push_channel_trips": "여행 소식", + "push_channel_invites": "초대 및 공유", + "push_channel_name": "일반", + "push_channel_tripday": "여행일", + "push_fallback_body": "새 알림", + "push_channel_tripday_description": "진행 중인 여행의 하루와 다음 장소." + }, + "nl": { + "push_channel_chat": "Reischat", + "push_channel_trips": "Reisupdates", + "push_channel_invites": "Uitnodigingen en delen", + "push_channel_name": "Algemeen", + "push_channel_tripday": "Reisdag", + "push_fallback_body": "Nieuwe melding", + "push_channel_tripday_description": "De dag van een lopende reis en de volgende stop." + }, + "pl": { + "push_channel_chat": "Czat podróży", + "push_channel_trips": "Nowości o podróży", + "push_channel_invites": "Zaproszenia i udostępnienia", + "push_channel_name": "Ogólne", + "push_channel_tripday": "Dzień podróży", + "push_fallback_body": "Nowe powiadomienie", + "push_channel_tripday_description": "Dzień trwającej podróży i jej następny przystanek." + }, + "pt-BR": { + "push_channel_chat": "Chat da viagem", + "push_channel_trips": "Novidades da viagem", + "push_channel_invites": "Convites e compartilhamentos", + "push_channel_name": "Geral", + "push_channel_tripday": "Dia de viagem", + "push_fallback_body": "Nova notificação", + "push_channel_tripday_description": "O dia de uma viagem em andamento e sua próxima parada." + }, + "ru": { + "push_channel_chat": "Чат поездки", + "push_channel_trips": "Новости поездки", + "push_channel_invites": "Приглашения и доступ", + "push_channel_name": "Общие", + "push_channel_tripday": "День поездки", + "push_fallback_body": "Новое уведомление", + "push_channel_tripday_description": "День текущей поездки и следующая остановка." + }, + "sk": { + "push_channel_chat": "Chat výletu", + "push_channel_trips": "Novinky z výletu", + "push_channel_invites": "Pozvánky a zdieľania", + "push_channel_name": "Všeobecné", + "push_channel_tripday": "Cestovný deň", + "push_fallback_body": "Nové upozornenie", + "push_channel_tripday_description": "Deň prebiehajúceho výletu a jeho ďalšia zastávka." + }, + "sv": { + "push_channel_chat": "Resechatt", + "push_channel_trips": "Nytt om resan", + "push_channel_invites": "Inbjudningar och delningar", + "push_channel_name": "Allmänt", + "push_channel_tripday": "Resdag", + "push_fallback_body": "Ny avisering", + "push_channel_tripday_description": "Dagen för en pågående resa och nästa stopp." + }, + "th": { + "push_channel_chat": "แชทการเดินทาง", + "push_channel_trips": "อัปเดตการเดินทาง", + "push_channel_invites": "คำเชิญและการแชร์", + "push_channel_name": "ทั่วไป", + "push_channel_tripday": "วันเดินทาง", + "push_fallback_body": "การแจ้งเตือนใหม่", + "push_channel_tripday_description": "วันของทริปที่กำลังดำเนินอยู่และจุดหมายถัดไป" + }, + "tr": { + "push_channel_chat": "Seyahat sohbeti", + "push_channel_trips": "Seyahat güncellemeleri", + "push_channel_invites": "Davetler ve paylaşımlar", + "push_channel_name": "Genel", + "push_channel_tripday": "Seyahat günü", + "push_fallback_body": "Yeni bildirim", + "push_channel_tripday_description": "Süren bir seyahatin günü ve sonraki durağı." + }, + "uk": { + "push_channel_chat": "Чат подорожі", + "push_channel_trips": "Новини подорожі", + "push_channel_invites": "Запрошення та доступ", + "push_channel_name": "Загальні", + "push_channel_tripday": "День подорожі", + "push_fallback_body": "Нове сповіщення", + "push_channel_tripday_description": "День поточної подорожі та наступна зупинка." + }, + "vi": { + "push_channel_chat": "Trò chuyện chuyến đi", + "push_channel_trips": "Cập nhật chuyến đi", + "push_channel_invites": "Lời mời và chia sẻ", + "push_channel_name": "Chung", + "push_channel_tripday": "Ngày đi", + "push_fallback_body": "Thông báo mới", + "push_channel_tripday_description": "Ngày của chuyến đi đang diễn ra và điểm dừng tiếp theo." + }, + "zh-Hans": { + "push_channel_chat": "行程聊天", + "push_channel_trips": "行程动态", + "push_channel_invites": "邀请与共享", + "push_channel_name": "常规", + "push_channel_tripday": "旅行日", + "push_fallback_body": "新通知", + "push_channel_tripday_description": "进行中行程的当天安排和下一站。" + }, + "zh-Hant": { + "push_channel_chat": "行程聊天", + "push_channel_trips": "行程動態", + "push_channel_invites": "邀請與共享", + "push_channel_name": "一般", + "push_channel_tripday": "旅行日", + "push_fallback_body": "新通知", + "push_channel_tripday_description": "進行中行程的當天安排與下一站。" + } +} \ No newline at end of file diff --git a/client/scripts/check-store-metadata.mjs b/client/scripts/check-store-metadata.mjs new file mode 100644 index 000000000..26818f490 --- /dev/null +++ b/client/scripts/check-store-metadata.mjs @@ -0,0 +1,102 @@ +/** + * Checks the store listings in fastlane/ before anything is uploaded + * (`npm run store:check`, and the metadata job in .github/workflows/native.yml): + * + * - every text both stores require exists and fits its limit (App Store: name and + * subtitle 30, keywords 100, promotional text 170, description 4000; Google + * Play: title 30, short description 80, full description 4000, changelog 500); + * - the URL files hold one https URL each; + * - every screenshot and listing graphic that is present has the exact size its + * slot takes and no alpha channel, which both stores refuse. + * + * Plain Node, no dependencies: a PNG's size and colour type are in its header. + */ +import { existsSync, readdirSync, readFileSync } from 'fs'; +import { dirname, join } from 'path'; +import { fileURLToPath } from 'url'; + +const fastlane = join(dirname(fileURLToPath(import.meta.url)), '..', 'fastlane'); +const meta = join(fastlane, 'metadata'); +const problems = []; + +/** [file, max length] the listing needs. */ +const TEXTS = [ + ['en-US/name.txt', 30], + ['en-US/subtitle.txt', 30], + ['en-US/keywords.txt', 100], + ['en-US/promotional_text.txt', 170], + ['en-US/description.txt', 4000], + ['en-US/release_notes.txt', 4000], + ['android/en-US/title.txt', 30], + ['android/en-US/short_description.txt', 80], + ['android/en-US/full_description.txt', 4000], + ['android/en-US/changelogs/default.txt', 500], + ['review_information/notes.txt', 4000], +]; +const URLS = ['en-US/support_url.txt', 'en-US/marketing_url.txt', 'en-US/privacy_url.txt']; + +function read(rel) { + const path = join(meta, rel); + if (!existsSync(path)) { + problems.push(`${rel}: missing`); + return null; + } + return readFileSync(path, 'utf8').trim(); +} + +for (const [rel, max] of TEXTS) { + const text = read(rel); + if (text === null) continue; + if (!text) problems.push(`${rel}: empty`); + // Code points, as the stores count them, not UTF-16 units. + const length = [...text].length; + if (length > max) problems.push(`${rel}: ${length} characters, the limit is ${max}`); +} +for (const rel of URLS) { + const url = read(rel); + if (url !== null && !/^https:\/\/\S+$/.test(url)) problems.push(`${rel}: not a single https URL`); +} + +/** Width, height and whether the PNG carries alpha (colour types 4 and 6), from its header. */ +function pngInfo(path) { + const head = readFileSync(path).subarray(0, 26); + if (head.toString('latin1', 1, 4) !== 'PNG') return null; + return { width: head.readUInt32BE(16), height: head.readUInt32BE(20), alpha: head[25] === 4 || head[25] === 6 }; +} + +/** [folder or file, accepted sizes] for every image slot. */ +const IMAGES = [ + [join(fastlane, 'screenshots', 'en-US'), ['1320x2868', '2064x2752']], + [join(meta, 'android', 'en-US', 'images', 'phoneScreenshots'), ['1080x1920']], + [join(meta, 'android', 'en-US', 'images', 'sevenInchScreenshots'), ['1620x2880']], + [join(meta, 'android', 'en-US', 'images', 'tenInchScreenshots'), ['1920x1080']], + [join(meta, 'android', 'en-US', 'images', 'featureGraphic.png'), ['1024x500']], + [join(meta, 'android', 'en-US', 'images', 'icon.png'), ['512x512']], +]; + +for (const [target, sizes] of IMAGES) { + if (!existsSync(target)) continue; + const files = target.endsWith('.png') + ? [target] + : readdirSync(target) + .filter((f) => f.endsWith('.png')) + .map((f) => join(target, f)); + for (const file of files) { + const info = pngInfo(file); + const rel = file.slice(fastlane.length + 1); + if (!info) { + problems.push(`${rel}: not a PNG`); + continue; + } + if (!sizes.includes(`${info.width}x${info.height}`)) { + problems.push(`${rel}: ${info.width}x${info.height}, expected ${sizes.join(' or ')}`); + } + if (info.alpha) problems.push(`${rel}: has an alpha channel`); + } +} + +if (problems.length) { + for (const problem of problems) console.error(`FAIL ${problem}`); + process.exit(1); +} +console.log('store metadata: every text fits, every image has its size and no alpha'); diff --git a/client/scripts/eslint-baseline.json b/client/scripts/eslint-baseline.json index b572afd98..74be1f03f 100644 --- a/client/scripts/eslint-baseline.json +++ b/client/scripts/eslint-baseline.json @@ -1,27 +1,27 @@ { "src": { - "@typescript-eslint/no-non-null-assertion": 377, - "@typescript-eslint/no-misused-promises": 847, + "@typescript-eslint/no-non-null-assertion": 367, + "@typescript-eslint/no-misused-promises": 820, "no-console": 88, - "complexity": 218, - "@typescript-eslint/no-explicit-any": 144, - "trek/no-swallowed-catch": 128, - "max-params": 32, - "trek/store-without-selector": 67, - "react-hooks/refs": 554, - "react-hooks/set-state-in-effect": 193, - "@typescript-eslint/no-floating-promises": 164, - "react-hooks/exhaustive-deps": 116, - "@typescript-eslint/no-unused-vars": 124, + "complexity": 217, + "@typescript-eslint/no-explicit-any": 143, + "trek/no-swallowed-catch": 127, + "max-params": 31, + "trek/store-without-selector": 66, + "react-hooks/refs": 534, + "react-hooks/set-state-in-effect": 189, + "@typescript-eslint/no-floating-promises": 162, + "react-hooks/exhaustive-deps": 113, + "@typescript-eslint/no-unused-vars": 121, "react-hooks/immutability": 28, - "max-lines-per-function": 130, + "max-lines-per-function": 127, "react-hooks/static-components": 50, "react-hooks/preserve-manual-memoization": 12, "no-useless-assignment": 7, "no-empty": 19, "trek/no-window-globals": 41, "react-refresh/only-export-components": 44, - "unused-disable-directive": 6, + "unused-disable-directive": 5, "max-depth": 21, "react-hooks/void-use-memo": 1, "@typescript-eslint/no-unused-expressions": 2, @@ -31,11 +31,11 @@ }, "suppressed": { "@typescript-eslint/no-explicit-any": 38, - "react-hooks/exhaustive-deps": 46 + "react-hooks/exhaustive-deps": 44 }, "tests": { "@typescript-eslint/no-explicit-any": 489, - "@typescript-eslint/no-non-null-assertion": 1914, + "@typescript-eslint/no-non-null-assertion": 1875, "@typescript-eslint/no-misused-promises": 22, "@typescript-eslint/no-unused-vars": 51, "@typescript-eslint/no-floating-promises": 33, diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json index b7ddd0447..58f062177 100644 --- a/client/scripts/feature-pairs.json +++ b/client/scripts/feature-pairs.json @@ -57,6 +57,51 @@ "desktop": ["src/pages/admin/AdminSettingsTab.tsx"], "mobile": ["src/mobile/screens/admin/MAdminSettingsSection.tsx"] }, + { + "feature": "API keys", + "hooks": ["src/components/Settings/useApiKeys.ts"], + "desktop": ["src/components/Settings/ApiKeysSection.tsx"], + "mobile": ["src/mobile/screens/settings/MApiKeysSection.tsx"] + }, + { + "feature": "Wanderer connection", + "hooks": ["src/components/Settings/useWandererConnection.ts"], + "desktop": ["src/components/Settings/WandererConnectionSection.tsx"], + "mobile": ["src/mobile/screens/settings/MWandererConnectionSection.tsx"] + }, + { + "feature": "Admin notification defaults", + "hooks": [ + "src/pages/admin/useNotificationDefaults.ts", + "src/pages/admin/notificationDefaultsModel.ts" + ], + "desktop": ["src/pages/admin/AdminNotificationDefaultsPanel.tsx"], + "mobile": ["src/mobile/screens/admin/MAdminNotificationDefaults.tsx"] + }, + { + "feature": "Admin Google daily limit", + "hooks": ["src/components/Admin/useGoogleQuota.ts"], + "desktop": ["src/components/Admin/GoogleDailyLimitRow.tsx"], + "mobile": ["src/mobile/screens/admin/MAdminGoogleDailyLimit.tsx"] + }, + { + "feature": "Admin share place details", + "hooks": [ + "src/components/Admin/usePlaceContribPanel.ts", + "src/components/Admin/placeContribModel.ts" + ], + "desktop": ["src/components/Admin/PlaceContribPanel.tsx"], + "mobile": ["src/mobile/screens/admin/MAdminPlaceContrib.tsx"] + }, + { + "feature": "Admin TREK services allowance", + "hooks": [ + "src/components/Admin/useServiceIdentity.ts", + "src/components/Admin/serviceIdentityModel.ts" + ], + "desktop": ["src/components/Admin/ServiceIdentityPanel.tsx"], + "mobile": ["src/mobile/screens/admin/MAdminServiceQuota.tsx"] + }, { "feature": "Admin users invite status", "hooks": ["src/pages/admin/adminModel.ts"], @@ -130,6 +175,24 @@ "src/mobile/screens/trip/sheets/MTransportFormSheet.tsx" ] }, + { + "feature": "Booking mail import: pending bookings", + "hooks": ["src/components/MailIngest/useMailInbox.ts", "src/components/MailIngest/mailInboxModel.ts"], + "desktop": ["src/components/MailIngest/MailInboxDialog.tsx"], + "mobile": ["src/mobile/screens/mail/MMailInboxSheet.tsx"] + }, + { + "feature": "Booking mail import: settings card", + "hooks": ["src/components/MailIngest/useMailImportSettings.ts"], + "desktop": ["src/components/Settings/MailImportSection.tsx"], + "mobile": ["src/mobile/screens/settings/MMailImportSection.tsx"] + }, + { + "feature": "Booking mail import: admin card", + "hooks": ["src/components/Admin/mailIngest/useMailIngestAdmin.ts", "src/components/Admin/mailIngest/mailIngestAdminModel.ts"], + "desktop": ["src/components/Admin/mailIngest/MailIngestAdminCard.tsx"], + "mobile": ["src/mobile/screens/admin/MMailIngestAdminCard.tsx"] + }, { "feature": "Booking save follow-up: travellers and files before the editor closes", "hooks": ["src/components/Planner/useBookingFollowUp.ts"], @@ -279,14 +342,26 @@ "feature": "Costs/budget ledger: costsModel", "hooks": ["src/components/Budget/costsModel.ts"], "desktop": ["src/components/Budget/CostsPanel.tsx"], - "mobile": ["src/mobile/screens/trip/sheets/MCostSheet.tsx", "src/mobile/screens/trip/tabs/MCostsTab.tsx"] + "mobile": ["src/mobile/screens/trip/tabs/MCostsTab.tsx"] }, { - "feature": "Costs/budget ledger: useCostsLedger, useSettlementForm, useExpenseLinks", - "hooks": ["src/components/Budget/useCostsLedger.ts", "src/components/Budget/useSettlementForm.ts", "src/components/Budget/useExpenseLinks.ts"], + "feature": "Costs/budget ledger: useCostsLedger, useExpenseLinks", + "hooks": ["src/components/Budget/useCostsLedger.ts", "src/components/Budget/useExpenseLinks.ts"], "desktop": ["src/components/Budget/CostsPanel.tsx"], "mobile": ["src/mobile/screens/trip/tabs/MCostsTab.tsx"] }, + { + "feature": "Costs/budget splitting or totals only: useCostsMode", + "hooks": ["src/components/Budget/useCostsMode.ts"], + "desktop": ["src/components/Budget/CostsModeCard.tsx"], + "mobile": ["src/mobile/screens/trip/tabs/MCostsTab.tsx"] + }, + { + "feature": "Costs/budget settle-up payment: useSettlementForm", + "hooks": ["src/components/Budget/useSettlementForm.ts"], + "desktop": ["src/components/Budget/SettlementModal.tsx"], + "mobile": ["src/mobile/screens/trip/tabs/MCostsPayment.tsx"] + }, { "feature": "Create/edit trip form", "hooks": ["src/components/Trips/tripFormModel.ts", "src/components/Trips/useTripCoverPicker.ts"], @@ -404,6 +479,12 @@ "desktop": ["src/components/Planner/usePlacesSidebar.ts"], "mobile": ["src/mobile/screens/trip/sheets/ImpListStep.tsx"] }, + { + "feature": "Live flight status", + "hooks": ["src/components/Planner/flightLive/useFlightLiveCard.ts"], + "desktop": ["src/components/Planner/flightLive/FlightLiveCard.tsx", "src/components/Planner/flightLive/FlightLiveStrip.tsx"], + "mobile": ["src/mobile/screens/trip/sheets/MFlightLiveCard.tsx", "src/mobile/screens/trip/MFlightLiveStrip.tsx"] + }, { "feature": "Places column file routing between the Tours and places imports", "hooks": ["src/components/Planner/usePlacesColumnFileImport.ts"], @@ -566,6 +647,18 @@ "desktop": ["src/components/Packing/usePackingListPanel.ts"], "mobile": ["src/mobile/screens/trip/tabs/MPackingListTab.tsx"] }, + { + "feature": "Packing list: who brings and who sees an item", + "hooks": ["src/components/Packing/packingItemAccess.ts"], + "desktop": ["src/components/Packing/PackingItemDetail.tsx"], + "mobile": ["src/mobile/screens/trip/tabs/MPackItemSheet.tsx"] + }, + { + "feature": "Packing list: sharing of a whole list", + "hooks": ["src/components/Packing/usePackingCategorySharing.ts"], + "desktop": ["src/components/Packing/usePackingListPanel.ts"], + "mobile": ["src/mobile/screens/trip/tabs/MPackingListTab.tsx"] + }, { "feature": "Packing list: usePackingImport", "hooks": ["src/components/Packing/usePackingImport.ts"], @@ -605,6 +698,24 @@ "desktop": ["src/components/Planner/PlaceFormModal.tsx"], "mobile": ["src/mobile/screens/trip/sheets/PlPlaceSearch.tsx"] }, + { + "feature": "Place add/edit form: tags", + "hooks": ["src/components/Planner/usePlaceTags.ts"], + "desktop": ["src/components/Planner/PlaceFormModal.tsx"], + "mobile": ["src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx"] + }, + { + "feature": "Place add/edit form: description, notes and the day note as tabs", + "hooks": ["src/components/Planner/usePlaceTextTabs.ts"], + "desktop": ["src/components/Planner/PlaceFormTexts.tsx"], + "mobile": ["src/mobile/screens/trip/sheets/PlPlaceTexts.tsx"] + }, + { + "feature": "Place add/edit form: phone, e-mail and opening hours", + "hooks": ["src/components/Planner/usePlaceHours.ts"], + "desktop": ["src/components/Planner/PlaceContactFields.tsx"], + "mobile": ["src/mobile/screens/trip/sheets/PlContactFields.tsx"] + }, { "feature": "Place detail actions", "hooks": ["src/components/Planner/usePlaceActions.ts"], @@ -620,8 +731,7 @@ "desktop": ["src/components/Planner/PlacesSidebarHeader.tsx", "src/components/Planner/usePlacesSidebar.ts"], "mobile": [ "src/mobile/screens/trip/places/MPlacesBrowser.tsx", - "src/mobile/screens/trip/places/MPlacesFilterControls.tsx", - "src/mobile/screens/trip/places/MPlacesFilterSheet.tsx" + "src/mobile/screens/trip/places/MPlacesFilterControls.tsx" ] }, { @@ -664,12 +774,24 @@ "desktop": ["src/components/Roadtrip/RoadtripStopPopup.tsx"], "mobile": ["src/mobile/screens/trip/roadtrip/MRtDraftSheet.tsx"] }, + { + "feature": "Road-trip Google Maps route import", + "hooks": ["src/components/Roadtrip/useGoogleRouteImport.ts"], + "desktop": ["src/components/Roadtrip/GoogleRouteImport.tsx"], + "mobile": ["src/mobile/screens/trip/roadtrip/MRtRouteImportSheet.tsx"] + }, { "feature": "Road-trip stay length draft", "hooks": ["src/components/Roadtrip/useStayDraft.ts"], "desktop": ["src/components/Roadtrip/RoadtripStayModal.tsx"], "mobile": ["src/mobile/screens/trip/roadtrip/MRtStaySheet.tsx"] }, + { + "feature": "Demo welcome", + "hooks": ["src/components/Demo/useDemoWelcome.ts"], + "desktop": ["src/components/Demo/DemoWelcome.tsx"], + "mobile": ["src/mobile/screens/dashboard/MDemoWelcome.tsx"] + }, { "feature": "Settings / Demo account locks", "hooks": ["src/components/Demo/useDemoLock.ts"], @@ -691,6 +813,12 @@ "desktop": ["src/components/Settings/AccountTab.tsx"], "mobile": ["src/mobile/screens/settings/MSettingsAccount.tsx"] }, + { + "feature": "Settings / Account / Native app server", + "hooks": ["src/components/Settings/useNativeServer.ts"], + "desktop": ["src/components/Settings/NativeServerSection.tsx"], + "mobile": ["src/mobile/screens/settings/MSettingsServer.tsx"] + }, { "feature": "Settings / Account / Passkeys", "hooks": ["src/components/Settings/usePasskeys.ts"], @@ -811,6 +939,12 @@ "desktop": ["src/components/shared/Toast.tsx"], "mobile": ["src/mobile/components/MToastHost.tsx"] }, + { + "feature": "Tour editor workspace", + "hooks": ["src/pages/tripPlanner/useTripPlannerPage.ts"], + "desktop": ["src/pages/TripPlannerPage.tsx"], + "mobile": ["src/mobile/screens/trip/tours/MTourWorkspace.tsx"] + }, { "feature": "Tours list filter", "hooks": ["src/components/Tours/tourPresentation.ts"], @@ -847,6 +981,12 @@ "desktop": ["src/components/Planner/DayPlanSidebarTransportDetailModal.tsx"], "mobile": ["src/mobile/screens/trip/sheets/MTransportSheet.tsx"] }, + { + "feature": "Live flight cards in the booking detail: useFlightLiveCard", + "hooks": ["src/components/Planner/flightLive/useFlightLiveCard.ts"], + "desktop": ["src/components/Planner/bookings/BookingDetailDialog.tsx"], + "mobile": ["src/mobile/screens/trip/sheets/MTransportSheet.tsx"] + }, { "feature": "Transport booking form: bookingFormModel", "hooks": ["src/components/Planner/bookingFormModel.ts"], @@ -980,6 +1120,8 @@ } ], "mobileOnly": { + "src/mobile/screens/trip/sheets/MReviewNotice.tsx": "The transport sheet's row asking for a look at an imported booking; the desktop dialog folds the same \"looks right\" action into its review pill (ReviewPill in bookingParts.tsx), so there is no separate twin.", + "src/mobile/screens/mail/MMailInboxHost.tsx": "Mounts the phone shell's one inbox sheet and reads the person's import settings; the desktop mounts its dialog from the Navbar, so there is no twin.", "src/mobile/screens/admin/MAdminOidcCard.tsx": "Markup only; the OIDC card of MAdminSettingsSection, with the form state from useAdmin and the save from its useAdminSettingsActions handed in through props.", "src/mobile/screens/admin/MAdminResetMfaSheet.tsx": "Markup only; the 2FA reset confirm that MAdminSheets opens, with the reset handed in through props from its useAdminUserActions.", "src/mobile/screens/admin/MAdminUi.tsx": "Phone only admin UI primitives (button, card, field, input, secret input, sheet frame).", @@ -991,11 +1133,15 @@ "src/mobile/screens/collections/MCollInvites.tsx": "Markup only; the invites and accept and decline come through props from useCollections via MCollections.", "src/mobile/screens/collections/MCollLabelsSheet.tsx": "Phone label sheet; create, update, delete and assign come through props from useCollections.", "src/mobile/screens/collections/MCollLinksEditor.tsx": "Markup only; link rows and the change handler come through props from the collection sheets.", + "src/mobile/screens/collections/MCollListNav.tsx": "Markup only; the collections' lists as the header dropdown or as the column beside the places on a wide window, with the lists and the selection handed in through props from useCollections.", "src/mobile/screens/collections/MCollListPickerSheet.tsx": "Phone list picker sheet; the move or copy action comes through onPick from useCollections.", "src/mobile/screens/collections/MCollSheetKit.tsx": "Phone only sheet UI primitives for the collections screens (header, footer, pill, eyebrow).", "src/mobile/screens/collections/collectionsMobileModel.ts": "Visual constants only the phone collections screens use (category and status specs, swatches, cover gradient).", "src/mobile/screens/dashboard/MUserMenu.tsx": "Phone avatar menu with a three state theme cycle the desktop navbar does not have.", "src/mobile/screens/journey/MDawarichDaySheet.tsx": "Markup only; the phone frame the Dawarich day sheets (route and stays) render their shared review in.", + "src/mobile/screens/journey/MJourneyFeed.tsx": "Markup only; the journey's entries as a feed beside the map on a wide window, with the entries, the active one and the tap handed in through props from useJourneyDetail and useJourneyCarouselSync.", + "src/mobile/screens/settings/MAppLockCard.tsx": "Phone only: the app lock exists only in the native app, so there is no desktop setting to share with.", + "src/mobile/screens/settings/MClientCertCard.tsx": "Phone only: the client certificate is kept by the native app, so there is no desktop setting to share with.", "src/mobile/screens/settings/MConfirmSheet.tsx": "Phone only bottom sheet confirm dialog used across the mobile screens.", "src/mobile/screens/settings/MDawarichConnectionSection.tsx": "Already shares hooks/useDawarichConnection with components/Settings/DawarichConnectionSection.tsx.", "src/mobile/screens/settings/MMobileDashOrder.tsx": "Phone only setting that orders the mobile dashboard blocks; the desktop has no such setting.", @@ -1004,17 +1150,22 @@ "src/mobile/screens/settings/MSettingsAbout.tsx": "Markup only about card with static links and no state.", "src/mobile/screens/settings/MSettingsOffline.tsx": "Already shares components/Settings/useOfflineSettings with components/Settings/OfflineTab.tsx.", "src/mobile/screens/settings/MSettingsUi.tsx": "Phone only settings UI primitives (card, row, input, button, segments, hint).", + "src/mobile/screens/settings/MTileCacheUsage.tsx": "Phone only: the native tile cache size and clear action, which the browser build has no counterpart for.", "src/mobile/screens/settings/MWebPushCard.tsx": "Already shares hooks/useWebPush with components/Settings/WebPushCard.tsx.", + "src/mobile/screens/trip/tabHeadSlot.ts": "Phone shell only; the place in the shell's top row the tours tab and the journal fill with their own switches. The desktop heads its panels itself.", + "src/mobile/screens/trip/MTripRail.tsx": "Phone shell only; the trip's sections on the leading edge of a wide window in place of the dock, with the tabs and handlers MTripShell hands in.", + "src/mobile/screens/trip/MTripShellParts.tsx": "Markup only; small pieces of MTripShell's top controls (segment pill, compact toggle, document sync button), with the state and handlers MTripShell hands in.", "src/mobile/screens/trip/dockTabs.ts": "Phone only helper that picks which trip tabs get a seat in the mobile dock.", + "src/mobile/screens/trip/useTripTabSwitch.ts": "Phone shell only; switches the section the dock and a notification link open, and the collab part a message link means. The desktop switches through useTripPlanner alone.", "src/mobile/screens/trip/lib/dayNotes.ts": "Phone only helper that splits a leading time off a day note for the plan timeline.", "src/mobile/screens/trip/map/MMapArea.tsx": "Phone map stage framing; already shares usePoiExplore and useMergedMapPois with the desktop trip planner.", - "src/mobile/screens/trip/map/MPlacesFilterPill.tsx": "Phone only map control for the active places filter count, built on the shared MapTogglePill.", "src/mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": "Markup only; categories and the pick handler come through props from MPlacesBrowser.", "src/mobile/screens/trip/places/MPlacesToursModeSwitch.tsx": "Markup only places or tours toggle; value and onChange come through props from MPlacesBrowser.", "src/mobile/screens/trip/places/placesBrowserModel.ts": "Phone pool helpers over the shared utils/placesFilter, placeSearch and plannedPlaces.", "src/mobile/screens/trip/plan/MPlanTimelineRows.tsx": "Markup only timeline rows; row data comes from MPlanTimeline and planTimelineModel.", + "src/mobile/screens/trip/plan/MRouteAppsSheet.tsx": "Markup only; the route apps come from the shared components/Planner/dayRouteApps the desktop menu uses too.", + "src/mobile/screens/trip/plan/openRouteTarget.ts": "Phone only helper that opens a route target: a web link in a new tab, geo: in place.", "src/mobile/screens/trip/plan/planTimelineModel.ts": "Phone plan timeline row builder over the shared utils/dayMerge, dayOrder and dayTourProjection.", - "src/mobile/screens/trip/plan/useMPlanDaySwipe.ts": "Phone only touch swipe gesture for switching days.", "src/mobile/screens/trip/plan/useMPlanDragReorder.ts": "Phone only long press drag gesture; the reorder itself runs through the handler it is given.", "src/mobile/screens/trip/roadtrip/MRoadtripRows.tsx": "Markup only road trip rows over the shared Roadtrip models the desktop sidebar rows also use.", "src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx": "Phone road trip tab over the shared roadtripRowModel, stopBookings and nightBookend RoadtripSidebar uses.", @@ -1022,8 +1173,10 @@ "src/mobile/screens/trip/roadtrip/MRtCorridorBar.tsx": "Markup only; its corridor state comes through props from useMRtCorridor.", "src/mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx": "Phone corridor search sheet over useMRtCorridor and the planner's shared corridor state.", "src/mobile/screens/trip/roadtrip/MRtInfoSheet.tsx": "Read only figures sheet that already shares useHotelBookends, dayWindow and parseAvoid with RoadtripLimitsCard.", + "src/mobile/screens/trip/roadtrip/MRtLimitsEditor.tsx": "Large screen form inside MRtInfoSheet over the planner's saveRoadtripLimit, the desktop dialog's own save, and the shared dayWindow, parseAvoid and rangeFromSpec.", "src/mobile/screens/trip/roadtrip/MRtKindSheet.tsx": "Thin sheet over planner.setRoadtripStopKind that already shares STOP_KINDS with StopKindPicker.", "src/mobile/screens/trip/roadtrip/MRtStopSheet.tsx": "Phone only stop detail sheet over the shared roadtripRowModel, stayReading and planner writers.", + "src/mobile/screens/trip/roadtrip/MRtTrackSheet.tsx": "Large screen sheet over the planner's followTrack, the same hook RoadtripTrackModal runs on; the phone has no entry to it.", "src/mobile/screens/trip/roadtrip/stageBadges.ts": "Badge helpers for the phone stage header and alternatives bar, which have no desktop counterpart.", "src/mobile/screens/trip/roadtrip/useMRoadtrip.ts": "Phone stage screen adapter over the shared roadtripRowModel plus a live clock tick.", "src/mobile/screens/trip/roadtrip/useMRtAlternatives.ts": "Tap to preview, confirm to write layer over the planner's shared route alternatives.", @@ -1033,15 +1186,22 @@ "src/mobile/screens/trip/sheets/MBrowseActionsSheet.tsx": "Phone action sheet for a pool place that calls planner handlers and the shared placeToSaveTarget.", "src/mobile/screens/trip/sheets/MDaysSheet.tsx": "Button based day reorder sheet over planner.handleReorderDays; the desktop reorders by drag.", "src/mobile/screens/trip/sheets/MLinkedCosts.tsx": "Already shares useExpenseLinks with the desktop BookingCostsSection; only markup and a search filter are local.", + "src/mobile/screens/trip/sheets/MTourDetailShell.tsx": "Markup only phone frame for the shared TourDetailDialog, which renders its own content into it.", "src/mobile/screens/trip/sheets/MTripSheetUi.tsx": "Phone sheet UI primitives (eyebrow, headers, stat boxes, action circles) and a time display helper.", "src/mobile/screens/trip/sheets/PlFileAttach.tsx": "Markup only; pending files and link actions come through props from the phone form sheets.", "src/mobile/screens/trip/sheets/PlSheetChrome.tsx": "Phone form sheet chrome primitives (header, footer, field classes).", + "src/mobile/screens/trip/sheets/PlTags.tsx": "Markup only; the tag picker's state comes through props from MPlaceEditSheet, which runs usePlaceTags, and the chips of the place sheet draw the tags the place carries.", "src/mobile/screens/trip/sheets/PlTimeFields.tsx": "Phone time fields that already share timeCollisions with the desktop PlaceFormModal.", + "src/mobile/screens/trip/sheets/tourSheetOpen.ts": "Phone only context for MTourDetailShell: whether the tour sheet is open and the name it carries.", "src/mobile/screens/trip/tabs/MCollabTab.tsx": "Phone collab sub tab router that reuses the desktop CollabLinks component.", + "src/mobile/screens/trip/tabs/MFilesBoard.tsx": "Markup only; the trip's files as tiles and the picked file's preview on a wide window, with the files and their actions handed in through props from MFilesTab.", "src/mobile/screens/trip/tabs/MListsTab.tsx": "Phone router between the packing and to-do bodies, with no logic of its own.", + "src/mobile/screens/trip/tabs/MPackingCategorySharingSheet.tsx": "Markup only; the sheet that shares a whole list, with its state from usePackingCategorySharing handed in through props by MPackingListTab.", "src/mobile/screens/trip/tabs/MReceiptScanButton.tsx": "Already shares useReceiptScan and ReceiptScanModal with the desktop CostsPanel.", "src/mobile/screens/trip/tabs/MReservationCardParts.tsx": "Markup only: the title, actions, date, files and delete sheet parts both phone booking tabs draw.", + "src/mobile/screens/trip/tabs/MTodoSidebar.tsx": "Markup only; the to-do filters as a pane beside the tasks on a wide window, with the filter state and the counts handed in through props from useTodoView.", "src/mobile/screens/trip/tabs/MTripTabPanel.tsx": "Phone tab router that mounts the per tab screens and plugin frames, with no logic of its own.", + "src/mobile/screens/trip/tabs/collabPanes.ts": "Phone only; decides whether the collab tab shows the chat beside a board on a wide window, a layout question of the touch shell that the desktop planner does not have.", "src/mobile/screens/trip/tabs/listsModel.ts": "Priority colour and label constants only the phone to-do list and task sheet use.", "src/mobile/screens/trip/tabs/tabChrome.tsx": "Phone tab chrome primitives (scroller, section headers, fields, traveler chips, plugin slots).", "src/mobile/screens/trip/tabs/tabModel.ts": "Phone tab prop type and status colour tokens only the phone tabs use.", diff --git a/client/scripts/format-baseline.json b/client/scripts/format-baseline.json index 501a55b93..e16931db4 100644 --- a/client/scripts/format-baseline.json +++ b/client/scripts/format-baseline.json @@ -519,8 +519,6 @@ "src/components/Map/reservationsMapbox.ts", "src/components/Map/routeUsageCounter.test.ts", "src/components/Map/routeUsageCounter.ts", - "src/components/Map/rtlText.test.ts", - "src/components/Map/rtlText.ts", "src/components/Map/selectedPlaceTarget.test.ts", "src/components/Map/selectedPlaceTarget.ts", "src/components/Map/trackColors.ts", @@ -577,16 +575,12 @@ "src/components/Packing/PackingListPanelItemRow.test.tsx", "src/components/Packing/PackingListPanelItemRow.tsx", "src/components/Packing/PackingListPanelList.tsx", - "src/components/Packing/PackingListPanelQuantityInput.test.tsx", - "src/components/Packing/PackingListPanelQuantityInput.tsx", "src/components/Packing/PackingListPanelViewTabs.tsx", "src/components/Packing/PackingPackedCounter.test.tsx", "src/components/Packing/PackingPackedCounter.tsx", "src/components/Packing/PackingPopover.test.tsx", "src/components/Packing/PackingPopover.tsx", "src/components/Packing/PackingPrintPreview.tsx", - "src/components/Packing/PackingShareControl.test.tsx", - "src/components/Packing/PackingShareControl.tsx", "src/components/Packing/PackingWeightSummary.tsx", "src/components/Packing/packingExport.test.ts", "src/components/Packing/packingExport.ts", @@ -1025,7 +1019,6 @@ "src/components/Tours/useTourPermissions.ts", "src/components/Trips/TripDateReview.tsx", "src/components/Trips/TripFormModal.test.tsx", - "src/components/Trips/TripFormModal.tsx", "src/components/Trips/TripMemberAvatar.tsx", "src/components/Trips/TripMembersModal.test.tsx", "src/components/Trips/TripMembersModal.tsx", @@ -1351,11 +1344,9 @@ "src/mobile/screens/trip/dockTabs.ts", "src/mobile/screens/trip/lib/dayNotes.ts", "src/mobile/screens/trip/map/MMapArea.tsx", - "src/mobile/screens/trip/map/MPlacesFilterPill.tsx", "src/mobile/screens/trip/places/MPlacesBrowser.tsx", "src/mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx", "src/mobile/screens/trip/places/MPlacesFilterControls.tsx", - "src/mobile/screens/trip/places/MPlacesFilterSheet.tsx", "src/mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx", "src/mobile/screens/trip/places/MPlacesToursModeSwitch.tsx", "src/mobile/screens/trip/places/MToursSelectionList.test.tsx", @@ -1366,8 +1357,6 @@ "src/mobile/screens/trip/plan/MPlanTimelineRows.tsx", "src/mobile/screens/trip/plan/planTimelineModel.test.ts", "src/mobile/screens/trip/plan/planTimelineModel.ts", - "src/mobile/screens/trip/plan/useMPlanDaySwipe.test.tsx", - "src/mobile/screens/trip/plan/useMPlanDaySwipe.ts", "src/mobile/screens/trip/plan/useMPlanDragReorder.test.ts", "src/mobile/screens/trip/plan/useMPlanDragReorder.ts", "src/mobile/screens/trip/plan/useMPlanTimeline.ts", @@ -1982,7 +1971,6 @@ "tests/unit/mobile/trip/MPlaceSheet.test.tsx", "tests/unit/mobile/trip/MPlacesBrowser.test.tsx", "tests/unit/mobile/trip/MPlacesBulkCategorySheet.test.tsx", - "tests/unit/mobile/trip/MPlacesFilterSheet.test.tsx", "tests/unit/mobile/trip/MPlacesSaveToCollectionSheet.test.tsx", "tests/unit/mobile/trip/MPlanTimeline.test.tsx", "tests/unit/mobile/trip/MPlanTimelineRows.test.tsx", diff --git a/client/scripts/generate-adaptive-icons.mjs b/client/scripts/generate-adaptive-icons.mjs new file mode 100644 index 000000000..c48a2f8c6 --- /dev/null +++ b/client/scripts/generate-adaptive-icons.mjs @@ -0,0 +1,33 @@ +/** + * Writes the Android adaptive icon layers at their full size, after + * `npx @capacitor/assets generate` (see the icons:app script). + * + * The assets tool renders the foreground and background layers at the legacy + * launcher size (192 px at xxxhdpi), while an adaptive icon layer is 108 dp + * (432 px at xxxhdpi), so launchers that draw the icon large showed it soft. + * The layers come from the same sources in assets/, and + * mipmap-anydpi-v26/ic_launcher*.xml keeps placing them as before; it also uses + * the foreground as the monochrome layer for themed icons, since the mark is + * white on transparent. + */ +import { dirname, join } from 'path'; +import sharp from 'sharp'; +import { fileURLToPath } from 'url'; + +const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const resDir = join(clientDir, 'android', 'app', 'src', 'main', 'res'); + +/** 108 dp in pixels for each density bucket. */ +const DENSITIES = { ldpi: 81, mdpi: 108, hdpi: 162, xhdpi: 216, xxhdpi: 324, xxxhdpi: 432 }; +const LAYERS = { ic_launcher_foreground: 'icon-foreground.png', ic_launcher_background: 'icon-background.png' }; + +for (const [density, size] of Object.entries(DENSITIES)) { + for (const [name, source] of Object.entries(LAYERS)) { + const out = join(resDir, `mipmap-${density}`, `${name}.png`); + await sharp(join(clientDir, 'assets', source)) + .resize(size, size) + .png({ compressionLevel: 9 }) + .toFile(out); + console.log(`wrote ${out}`); + } +} diff --git a/client/scripts/generate-android-strings.mjs b/client/scripts/generate-android-strings.mjs new file mode 100644 index 000000000..33a16dfb0 --- /dev/null +++ b/client/scripts/generate-android-strings.mjs @@ -0,0 +1,76 @@ +/** + * Writes the Android app's native strings in every language the iOS app has + * (android/app/src/main/res/values-*\/strings_native.xml). + * + * The widget gallery and the share sheet say the same on both platforms, so + * their texts come from the iOS strings files (ios/App/TREKWidgets and + * ShareExtension, .lproj/Localizable.strings); what only Android has (the + * notification channels) lives in android-strings.json next to this script. + * Run `node scripts/generate-android-strings.mjs` from client/ after changing either. + */ +import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'fs'; +import { dirname, join } from 'path'; +import { fileURLToPath } from 'url'; + +const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const ios = join(clientDir, 'ios', 'App'); +const res = join(clientDir, 'android', 'app', 'src', 'main', 'res'); +const androidOnly = JSON.parse(readFileSync(join(clientDir, 'scripts', 'android-strings.json'), 'utf8')); + +/** Android's resource folder for an iOS language, where the two differ. */ +const FOLDER = { + en: 'values', + he: 'values-iw', + id: 'values-in', + 'pt-BR': 'values-pt-rBR', + 'zh-Hans': 'values-b+zh+Hans', + 'zh-Hant': 'values-b+zh+Hant', +}; + +/** iOS keys are dotted camelCase, Android names snake_case. */ +const androidName = (key) => + key + .replace(/([a-z])([A-Z])/g, '$1_$2') + .toLowerCase() + .replace(/\./g, '_'); + +function parseStrings(file) { + const out = []; + const text = readFileSync(file, 'utf8'); + for (const m of text.matchAll(/^"([^"]+)"\s*=\s*"((?:[^"\\]|\\.)*)";/gm)) out.push([m[1], m[2].replace(/\\"/g, '"')]); + return out; +} + +function escape(value) { + let v = value.replace(/&/g, '&').replace(//g, '>'); + v = v.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/"/g, '\\"'); + v = v.replace(/%@/g, '%1$s').replace(/%d/g, '%1$d'); + return /^[@?]/.test(v) ? `\\${v}` : v; +} + +const languages = readdirSync(join(ios, 'TREKWidgets')) + .filter((d) => d.endsWith('.lproj')) + .map((d) => d.slice(0, -'.lproj'.length)) + .sort(); + +for (const lang of languages) { + const widgets = parseStrings(join(ios, 'TREKWidgets', `${lang}.lproj`, 'Localizable.strings')); + const share = parseStrings(join(ios, 'ShareExtension', `${lang}.lproj`, 'Localizable.strings')); + const extra = androidOnly[lang]; + if (!extra) throw new Error(`android-strings.json has no ${lang}`); + const rows = [...widgets, ...share].map(([key, value]) => [androidName(key), value]); + // A widget with nothing to show yet says what the share sheet says without trips. + rows.push(['widget_empty', Object.fromEntries(share)['share.noTrips']]); + rows.push(...Object.entries(extra)); + const folder = join(res, FOLDER[lang] ?? `values-${lang}`); + mkdirSync(folder, { recursive: true }); + const body = rows.map(([name, value]) => ` ${escape(value)}`).join('\n'); + writeFileSync( + join(folder, 'strings_native.xml'), + '\n' + + '\n' + + `\n${body}\n\n` + ); +} +console.log(`wrote ${languages.length} languages`); diff --git a/client/scripts/generate-app-icons.mjs b/client/scripts/generate-app-icons.mjs new file mode 100644 index 000000000..dda9bddd3 --- /dev/null +++ b/client/scripts/generate-app-icons.mjs @@ -0,0 +1,108 @@ +/** + * Renders the native apps' icon and splash sources into assets/, from the + * white TREK mark in public/icons/icon-white.svg. `npx @capacitor/assets + * generate --android --ios` then turns them into every size both platforms + * ask for (see the icons:app script). + * + * The look: a dark, slightly glassy tile (a soft light from the top left and a + * sheen over the upper half) under the white mark. Dark because that is the + * app's launch background (#09090b) and its default scheme. + * + * Android's adaptive icon masks the foreground to a circle inside the + * canvas, so the mark there sits smaller than on the iOS tile. + */ +import { mkdirSync, readFileSync } from 'fs'; +import { dirname, join } from 'path'; +import sharp from 'sharp'; +import { fileURLToPath } from 'url'; + +const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const outDir = join(clientDir, 'assets'); +mkdirSync(outDir, { recursive: true }); + +const source = readFileSync(join(clientDir, 'public', 'icons', 'icon-white.svg'), 'utf8'); +const markPath = [...source.matchAll(/ m[1]).find((d) => d.length > 500); +if (!markPath) throw new Error('No mark path found in icon-white.svg'); +// The mark's extent inside its 1500 x 1500 viewBox. +const MARK = { x: 40, y: 5, w: 1420, h: 1490 }; + +const LAUNCH_BG = '#09090b'; + +function tile(size) { + return ` + + + + + + + + + + + + + + + + + + + + + + + + + +`; +} + +/** The white mark, `share` of the canvas tall, centred, with a soft shadow for depth. */ +function mark(size, share, shadow = true) { + const scale = (1024 * share) / MARK.h; + const w = MARK.w * scale; + const h = MARK.h * scale; + const tx = (1024 - w) / 2 - MARK.x * scale; + const ty = (1024 - h) / 2 - MARK.y * scale; + return ` + + + + + + + + + + + + +`; +} + +async function render(svg, file) { + await sharp(Buffer.from(svg)).png().toFile(join(outDir, file)); +} + +async function composite(background, overlay, file, size) { + const base = await sharp(Buffer.from(background)).resize(size, size).png().toBuffer(); + const top = await sharp(Buffer.from(overlay)).resize(size, size).png().toBuffer(); + await sharp(base) + .composite([{ input: top }]) + .flatten({ background: LAUNCH_BG }) + .png() + .toFile(join(outDir, file)); +} + +// iOS and store listings: one opaque tile, the mark at about half its height. +await composite(tile(1024), mark(1024, 0.5), 'icon-only.png', 1024); +// Android adaptive icon: the two layers apart, the mark inside the safe circle. +await render(tile(1024), 'icon-background.png'); +await render(mark(1024, 0.58), 'icon-foreground.png'); +// Splash: the launch background with the mark, light and dark alike. +const splashBg = ``; +await composite(splashBg, mark(2732, 0.2, false), 'splash.png', 2732); +await composite(splashBg, mark(2732, 0.2, false), 'splash-dark.png', 2732); + +console.log(`[app-icons] wrote icon and splash sources to ${outDir}`); diff --git a/client/scripts/generate-feature-graphic.mjs b/client/scripts/generate-feature-graphic.mjs new file mode 100644 index 000000000..802bf0886 --- /dev/null +++ b/client/scripts/generate-feature-graphic.mjs @@ -0,0 +1,75 @@ +/** + * The Google Play listing graphics (`npm run store:graphic`): + * + * featureGraphic.png 1024 x 500, the dark app background, the white TREK mark, + * the name and the subtitle, and on the right a crop of the + * first phone screenshot when one has been promoted + * (`npm run store:promote`); without it, mark and text only. + * icon.png 512 x 512, from the same 1024 px tile as the app icon. + * + * Both are flattened: Play refuses an alpha channel in either. + */ +import { existsSync, mkdirSync, readFileSync } from 'fs'; +import { dirname, join } from 'path'; +import sharp from 'sharp'; +import { fileURLToPath } from 'url'; + +const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const imagesDir = join(clientDir, 'fastlane', 'metadata', 'android', 'en-US', 'images'); +mkdirSync(imagesDir, { recursive: true }); + +const WIDTH = 1024; +const HEIGHT = 500; +const BACKGROUND = '#09090b'; +const TITLE = 'TREK Travel Planner'; +const SUBTITLE = readFileSync(join(clientDir, 'fastlane', 'metadata', 'en-US', 'subtitle.txt'), 'utf8').trim(); + +const escapeXml = (text) => text.replace(/&/g, '&').replace(//g, '>'); + +const mark = await sharp(join(clientDir, 'public', 'icons', 'icon-white.svg')) + .resize(120, 120) + .png() + .toBuffer(); + +const text = Buffer.from(` + ${escapeXml(TITLE)} + ${escapeXml(SUBTITLE)} +`); + +const layers = [ + { input: mark, left: 72, top: 110 }, + { input: text, left: 0, top: 0 }, +]; + +// The first phone screenshot, cut to the top of the screen and set at the right edge. +const phone = join(imagesDir, 'phoneScreenshots', '1_dashboard.png'); +if (existsSync(phone)) { + const crop = await sharp(phone) + .resize({ width: 300 }) + .extract({ left: 0, top: 0, width: 300, height: 440 }) + .png() + .toBuffer(); + const frame = Buffer.from(` + `); + const rounded = await sharp(crop) + .composite([{ input: frame, blend: 'dest-in' }]) + .png() + .toBuffer(); + layers.push({ input: rounded, left: WIDTH - 300 - 64, top: 30 }); +} + +await sharp({ create: { width: WIDTH, height: HEIGHT, channels: 3, background: BACKGROUND } }) + .composite(layers) + .flatten({ background: BACKGROUND }) + .removeAlpha() + .png() + .toFile(join(imagesDir, 'featureGraphic.png')); + +await sharp(join(clientDir, 'assets', 'icon-only.png')) + .resize(512, 512) + .flatten({ background: BACKGROUND }) + .removeAlpha() + .png() + .toFile(join(imagesDir, 'icon.png')); + +console.log(`wrote ${join(imagesDir, 'featureGraphic.png')} and icon.png`); diff --git a/client/scripts/generate-native-icons.mjs b/client/scripts/generate-native-icons.mjs new file mode 100644 index 000000000..0e00dffb1 --- /dev/null +++ b/client/scripts/generate-native-icons.mjs @@ -0,0 +1,67 @@ +/** + * Generates the Android status-bar notification icon from the master + * white-silhouette SVG. + * + * Android renders the small notification icon as a mask: every non-transparent + * pixel becomes the tint colour and everything else is dropped. Feeding it the + * launcher icon (a full-bleed coloured square) therefore produces a solid white + * blob, which is the single most common Capacitor push-notification complaint. + * public/icons/icon-white.svg is already white-on-transparent, so we only have + * to rasterise it at the five densities and flatten the colour to pure white so + * any future edit to that SVG's fill cannot silently change the mask. + * + * Referenced from AndroidManifest.xml as @drawable/notification_icon. + * Run: node scripts/generate-native-icons.mjs + */ +import { mkdirSync } from 'fs'; +import { dirname, join } from 'path'; +import sharp from 'sharp'; +import { fileURLToPath } from 'url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const clientDir = join(__dirname, '..'); +const source = join(clientDir, 'public', 'icons', 'icon-white.svg'); +const resDir = join(clientDir, 'android', 'app', 'src', 'main', 'res'); + +// Android notification icon sizes, in px, per density bucket (24dp baseline). +const densities = [ + { dir: 'drawable-mdpi', size: 24 }, + { dir: 'drawable-hdpi', size: 36 }, + { dir: 'drawable-xhdpi', size: 48 }, + { dir: 'drawable-xxhdpi', size: 72 }, + { dir: 'drawable-xxxhdpi', size: 96 }, +]; + +for (const { dir, size } of densities) { + const outDir = join(resDir, dir); + mkdirSync(outDir, { recursive: true }); + + // Inset the glyph slightly: Android's status bar clips tight to the 24dp box + // and a mark that touches the edge reads as cropped. + const glyph = Math.round(size * 0.86); + + const mask = await sharp(source, { density: 512 }) + .resize(glyph, glyph, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } }) + .extend({ + top: Math.floor((size - glyph) / 2), + bottom: Math.ceil((size - glyph) / 2), + left: Math.floor((size - glyph) / 2), + right: Math.ceil((size - glyph) / 2), + background: { r: 0, g: 0, b: 0, alpha: 0 }, + }) + .ensureAlpha() + .toBuffer(); + + // Keep the alpha, force every visible pixel to pure white. `dest-in` composites + // the white plate through the glyph's alpha channel. + await sharp({ + create: { width: size, height: size, channels: 4, background: { r: 255, g: 255, b: 255, alpha: 1 } }, + }) + .composite([{ input: mask, blend: 'dest-in' }]) + .png({ compressionLevel: 9 }) + .toFile(join(outDir, 'notification_icon.png')); + + console.log(` ✓ ${dir}/notification_icon.png (${size}x${size})`); +} + +console.log('Android notification icons generated.'); diff --git a/client/scripts/i18n-keys.mjs b/client/scripts/i18n-keys.mjs index 0f85ddd0f..0e23662c9 100644 --- a/client/scripts/i18n-keys.mjs +++ b/client/scripts/i18n-keys.mjs @@ -44,8 +44,9 @@ * * The en keys nothing reaches are a ratchet. Besides src/, the search for * references reads server/src (system notice and notification channel keys - * the server sends, *Key properties in its registries), plugin-sdk/src and - * shared/src/book (the Studio's layout template names), so + * the server sends, *Key properties in its registries), plugin-sdk/src, + * shared/src/book (the Studio's layout template names) and the native apps' + * address screen in native-shell/, so * a key the server uses does not read as dead; those references only count as * reached, they are not held to the rules above. The unused keys per en * domain file may not rise above scripts/i18n-unused-baseline.json, and an @@ -75,6 +76,9 @@ const UNUSED_BASELINE = join(HERE, 'i18n-unused-baseline.json'); * its layout templates. Read only to find which en keys are reached. */ export const REFERENCE_ROOTS = [ + // The address screen the native apps ship (vite.native.config.js): its own + // small build outside src/, reading only the native.* strings. + join(HERE, '..', 'native-shell'), join(HERE, '..', '..', 'server', 'src'), join(HERE, '..', '..', 'plugin-sdk', 'src'), join(HERE, '..', '..', 'shared', 'src', 'book'), diff --git a/client/scripts/i18n-unused-baseline.json b/client/scripts/i18n-unused-baseline.json index 7c9e4560a..9dd1bdcc0 100644 --- a/client/scripts/i18n-unused-baseline.json +++ b/client/scripts/i18n-unused-baseline.json @@ -2,12 +2,12 @@ "admin.ts": 112, "atlas.ts": 9, "backup.ts": 10, - "budget.ts": 36, + "budget.ts": 35, "categories.ts": 1, "collab.ts": 9, "collection.ts": 35, "common.ts": 7, - "dashboard.ts": 65, + "dashboard.ts": 64, "dawarich.ts": 15, "dayplan.ts": 17, "docsync.ts": 25, @@ -35,7 +35,7 @@ "shared.ts": 2, "storage.ts": 16, "system_notice.ts": 32, - "todo.ts": 3, + "todo.ts": 2, "tours.ts": 12, "trip.ts": 10, "undo.ts": 1, diff --git a/client/scripts/lib/precompress.mjs b/client/scripts/lib/precompress.mjs new file mode 100644 index 000000000..10725daa0 --- /dev/null +++ b/client/scripts/lib/precompress.mjs @@ -0,0 +1,60 @@ +/* + * The work behind scripts/precompress.mjs: a Brotli copy (.br) beside every + * compressible build file under dist/assets. + * + * The server compresses a build file on every download otherwise, at the low level + * a request path can afford. A file under assets/ carries its content hash in its + * name and never changes, so it is compressed once here, at the level a build can + * afford, and the server hands that copy out as it is + * (server/src/nest/platform/precompressed-static.ts). + */ +import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { brotliCompressSync, constants } from 'node:zlib'; + +/** What the server's own compression would take; fonts, images and video are compressed formats already. */ +const COMPRESSIBLE = /\.(?:m?js|css|svg|json|wasm|html|webmanifest)$/i; +/** The server leaves anything below 1 kB uncompressed too: the headers cost more than the saving. */ +export const MIN_BYTES = 1024; +/** Quality 11 takes about ten times as long per byte as 9, so the largest chunks get 9. */ +const BIG_BYTES = 1024 * 1024; + +function* walk(dir) { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = join(dir, entry.name); + if (entry.isDirectory()) yield* walk(full); + else yield full; + } +} + +/** + * Writes the .br copies under `dir` and returns what it did. A copy that would not be + * smaller than its file is not written, and a directory that does not exist is no work. + */ +export function precompress(dir) { + const result = { files: 0, before: 0, after: 0 }; + let files; + try { + files = [...walk(dir)]; + } catch (err) { + if (err.code === 'ENOENT') return result; + throw err; + } + for (const file of files) { + if (!COMPRESSIBLE.test(file)) continue; + const input = readFileSync(file); + if (input.length < MIN_BYTES) continue; + const output = brotliCompressSync(input, { + params: { + [constants.BROTLI_PARAM_QUALITY]: input.length > BIG_BYTES ? 9 : 11, + [constants.BROTLI_PARAM_SIZE_HINT]: input.length, + }, + }); + if (output.length >= input.length) continue; + writeFileSync(`${file}.br`, output); + result.files += 1; + result.before += input.length; + result.after += output.length; + } + return result; +} diff --git a/client/scripts/offline-baseline.json b/client/scripts/offline-baseline.json index 87a35b30d..ad9ce83dc 100644 --- a/client/scripts/offline-baseline.json +++ b/client/scripts/offline-baseline.json @@ -97,7 +97,6 @@ "src/components/Roadtrip/useDayBoundaries.ts", "src/components/Roadtrip/useRefuelSearch.ts", "src/components/Roadtrip/useRoadtripVias.ts", - "src/components/Settings/ApiKeysSection.tsx", "src/components/Settings/useAccountSettings.ts", "src/components/Settings/useAirTrailSettings.ts", "src/components/Settings/useMcpIntegration.ts", @@ -129,7 +128,6 @@ "src/mobile/screens/trip/tabs/MCollabNotes.tsx", "src/pages/JourneyDetailPage.tsx", "src/pages/OAuthAuthorizePage.tsx", - "src/pages/admin/AdminSettingsTab.tsx", "src/pages/admin/useAdmin.ts", "src/pages/admin/useNotificationDefaults.ts", "src/pages/atlas/useAtlas.ts", diff --git a/client/scripts/precompress.mjs b/client/scripts/precompress.mjs new file mode 100644 index 000000000..9ffe084de --- /dev/null +++ b/client/scripts/precompress.mjs @@ -0,0 +1,12 @@ +#!/usr/bin/env node +/* + * postbuild: writes a Brotli copy beside every compressible file under dist/assets, + * which the server hands to a browser that accepts Brotli instead of compressing + * the file again on each download. scripts/lib/precompress.mjs holds the work. + */ +import { fileURLToPath } from 'node:url'; +import { precompress } from './lib/precompress.mjs'; + +const { files, before, after } = precompress(fileURLToPath(new URL('../dist/assets', import.meta.url))); +const mb = (bytes) => (bytes / 1048576).toFixed(1); +console.log(`precompress: ${files} files, ${mb(before)} MB -> ${mb(after)} MB (brotli)`); diff --git a/client/scripts/rtl-baseline.json b/client/scripts/rtl-baseline.json index 699f4c2c8..3cf884e2f 100644 --- a/client/scripts/rtl-baseline.json +++ b/client/scripts/rtl-baseline.json @@ -24,8 +24,8 @@ "components/Map/DawarichTrailPill.tsx": 1, "components/Map/LocationButton.tsx": 1, "components/Map/MapTogglePill.tsx": 1, - "components/Map/MapView.tsx": 6, - "components/Map/MapViewGL.tsx": 8, + "components/Map/MapView.tsx": 5, + "components/Map/MapViewGL.tsx": 7, "components/Map/NightPauseTooltip.tsx": 1, "components/Map/PlaceHoverCard.tsx": 1, "components/Map/PoiCategoryPill.tsx": 1, @@ -34,12 +34,11 @@ "components/Map/locationMarkerMapbox.ts": 2, "components/Map/nightPauseMarker.ts": 4, "components/Map/ratingBadge.ts": 1, + "components/Map/switcherRow.ts": 1, "components/PDF/TripPDF.tsx": 7, "components/PDF/tripMapImage.ts": 1, "components/Packing/PackingListPanelBagCard.tsx": 1, "components/Packing/PackingListPanelCategoryGroup.tsx": 3, - "components/Packing/PackingListPanelItemRow.tsx": 2, - "components/Packing/PackingShareControl.tsx": 3, "components/Planner/DayDetailPanel.tsx": 1, "components/Planner/PlaceInspector.tsx": 1, "components/Planner/TransitSearchPanel.tsx": 3, @@ -62,7 +61,7 @@ "components/Vacay/VacayCalendar.tsx": 3, "components/Vacay/VacayMonthCard.tsx": 7, "components/Vacay/VacaySettings.tsx": 1, - "components/shared/ContextMenu.tsx": 3, + "components/shared/ContextMenu.tsx": 1, "components/shared/CustomDateTimePicker.tsx": 2, "components/shared/CustomSelect.tsx": 4, "components/shared/CustomTimePicker.tsx": 3, @@ -78,16 +77,11 @@ "help/contexts/tripMap.ts": 1, "hooks/useAnchoredPosition.ts": 3, "hooks/useElementRect.ts": 3, - "mobile/components/MSegmented.tsx": 3, - "mobile/components/MSheet.tsx": 1, - "mobile/screens/dashboard/MDashboard.tsx": 1, + "mobile/components/MSegmented.tsx": 1, "mobile/screens/journey/MJourneyDetail.tsx": 3, "mobile/screens/journey/MJourneyEntrySheet.tsx": 1, - "mobile/screens/trip/MTripShell.tsx": 3, "mobile/screens/trip/map/MMapArea.tsx": 3, - "mobile/screens/trip/tabs/MCollabPolls.tsx": 1, "mobile/screens/trip/tabs/MFileLightbox.tsx": 2, - "mobile/screens/vacay/MVacay.tsx": 1, "mobile/screens/vacay/MVacayMonth.tsx": 1, "pages/AtlasPage.tsx": 2, "pages/JourneyDetailPage.tsx": 1, diff --git a/client/scripts/rtl-disable-baseline.json b/client/scripts/rtl-disable-baseline.json index 253de175d..e8f5d8afe 100644 --- a/client/scripts/rtl-disable-baseline.json +++ b/client/scripts/rtl-disable-baseline.json @@ -1,8 +1,12 @@ { "components/Collections/CollectionMap.tsx": 1, + "components/Packing/PackingItemDetail.tsx": 1, "components/Studio/LineHandles.tsx": 1, "components/Studio/StudioSelectionChrome.tsx": 2, "components/Studio/inspector/FocalPad.tsx": 1, "mobile/components/trek3d/MascotClip.tsx": 1, + "mobile/screens/trip/MTripShell.tsx": 1, + "mobile/screens/vacay/MVacay.tsx": 1, + "pages/CollectionsPage.tsx": 1, "pages/tripPlanner/PlanMapStage.tsx": 4 } diff --git a/client/scripts/size-baseline.json b/client/scripts/size-baseline.json index f6c481626..9ba37f583 100644 --- a/client/scripts/size-baseline.json +++ b/client/scripts/size-baseline.json @@ -2,26 +2,26 @@ "e2e/help/fixtures.ts": 2291, "src/api/client.ts": 1873, "src/components/Admin/AdminPluginsPanel.test.tsx": 2704, - "src/components/Admin/AdminPluginsPanel.tsx": 1266, - "src/components/Budget/CostsPanel.test.tsx": 2730, - "src/components/Budget/CostsPanel.tsx": 1798, - "src/components/Map/MapView.tsx": 1337, + "src/components/Admin/AdminPluginsPanel.tsx": 1265, + "src/components/Budget/CostsPanel.test.tsx": 2725, + "src/components/Budget/CostsPanel.tsx": 1607, + "src/components/Map/MapView.tsx": 1200, "src/components/Map/MapViewGL.test.tsx": 2919, - "src/components/Map/MapViewGL.tsx": 2198, + "src/components/Map/MapViewGL.tsx": 2116, "src/components/Planner/DayDetailPanel.test.tsx": 2333, "src/components/Planner/DayPlanSidebar.test.tsx": 5349, - "src/components/Planner/DayPlanSidebar.tsx": 2929, + "src/components/Planner/DayPlanSidebar.tsx": 2910, "src/components/Planner/PlaceFormModal.test.tsx": 2836, - "src/components/Planner/PlaceInspector.tsx": 1290, + "src/components/Planner/PlaceInspector.tsx": 1128, "src/components/Studio/TravelElements.tsx": 1559, "src/components/Studio/countryShapes.ts": 2595, "src/index.css": 1636, - "src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1507, + "src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503, "src/pages/JourneyDetailPage.test.tsx": 4028, - "src/pages/LoginPage.tsx": 1348, + "src/pages/LoginPage.tsx": 1294, "src/pages/TripPlannerPage.tsx": 1128, - "src/pages/atlas/useAtlas.ts": 1210, + "src/pages/atlas/useAtlas.ts": 1207, "src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518, - "src/pages/tripPlanner/useTripPlanner.test.tsx": 3270, + "src/pages/tripPlanner/useTripPlanner.test.tsx": 3269, "src/styles/studio.css": 1918 } diff --git a/client/scripts/store-screenshots.mjs b/client/scripts/store-screenshots.mjs new file mode 100644 index 000000000..d5f6d62e7 --- /dev/null +++ b/client/scripts/store-screenshots.mjs @@ -0,0 +1,64 @@ +/** + * Moves the store screenshots from e2e/.tmp/store/ (written by the Playwright + * `store` project, `npm run store:shots`) into the folders fastlane uploads + * from, flattened onto the app background: both stores refuse an image with an + * alpha channel. + * + * iphone69, ipad13 fastlane/screenshots/en-US/ (deliver, App Store) + * play-phone fastlane/metadata/android/en-US/images/phoneScreenshots/ + * play-7in .../sevenInchScreenshots/ + * play-10in .../tenInchScreenshots/ (supply, Google Play) + * + * Every image is checked against the size its device must have, so a capture at + * the wrong viewport never reaches a listing. `npm run store:check` checks the + * committed files the same way. + */ +import { existsSync, mkdirSync, readdirSync } from 'fs'; +import { dirname, join } from 'path'; +import sharp from 'sharp'; +import { fileURLToPath } from 'url'; + +const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..'); +const rawDir = join(clientDir, 'e2e', '.tmp', 'store'); +const fastlane = join(clientDir, 'fastlane'); +const playImages = join(fastlane, 'metadata', 'android', 'en-US', 'images'); + +const TARGETS = { + iphone69: { dir: join(fastlane, 'screenshots', 'en-US'), size: [1320, 2868] }, + ipad13: { dir: join(fastlane, 'screenshots', 'en-US'), size: [2064, 2752] }, + 'play-phone': { dir: join(playImages, 'phoneScreenshots'), size: [1080, 1920] }, + 'play-7in': { dir: join(playImages, 'sevenInchScreenshots'), size: [1620, 2880] }, + 'play-10in': { dir: join(playImages, 'tenInchScreenshots'), size: [1920, 1080] }, +}; + +const BACKGROUND = '#09090b'; + +if (!existsSync(rawDir)) { + console.error(`No captures in ${rawDir}. Run npm run store:shots first.`); + process.exit(1); +} + +let failed = false; +for (const [device, { dir, size }] of Object.entries(TARGETS)) { + const from = join(rawDir, device); + if (!existsSync(from)) { + console.error(`missing captures for ${device}`); + failed = true; + continue; + } + mkdirSync(dir, { recursive: true }); + for (const file of readdirSync(from).filter((f) => f.endsWith('.png'))) { + const image = sharp(join(from, file)); + const { width, height } = await image.metadata(); + if (width !== size[0] || height !== size[1]) { + console.error(`${device}/${file}: ${width}x${height}, expected ${size[0]}x${size[1]}`); + failed = true; + continue; + } + // The App Store folder holds both devices; the prefix keeps them apart. + const name = dir.endsWith(join('screenshots', 'en-US')) ? `${device}_${file}` : file; + await image.flatten({ background: BACKGROUND }).removeAlpha().png().toFile(join(dir, name)); + console.log(`wrote ${join(dir, name)}`); + } +} +process.exit(failed ? 1 : 0); diff --git a/client/scripts/strict-baseline.json b/client/scripts/strict-baseline.json index d6b35e74f..5e95cff2c 100644 --- a/client/scripts/strict-baseline.json +++ b/client/scripts/strict-baseline.json @@ -38,16 +38,14 @@ "src/components/Journey/journeyGeo.ts": 4, "src/components/Layout/Navbar.test.tsx": 1, "src/components/Map/MapView.test.tsx": 2, - "src/components/Map/MapView.tsx": 8, + "src/components/Map/MapView.tsx": 7, "src/components/Map/MapViewGL.tsx": 1, "src/components/Map/ReservationOverlay.test.tsx": 1, "src/components/Map/transitGeometry.ts": 1, - "src/components/Map/useDawarichTrailGL.test.ts": 4, "src/components/Map/useMarkerThumbs.ts": 1, - "src/components/PDF/TripPDF.tsx": 40, - "src/components/Packing/PackingListPanelItemRow.test.tsx": 2, + "src/components/PDF/TripPDF.tsx": 38, "src/components/Planner/DayPlanSidebar.constants.ts": 1, - "src/components/Planner/DayPlanSidebar.tsx": 61, + "src/components/Planner/DayPlanSidebar.tsx": 52, "src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1, "src/components/Planner/PlaceFormModal.test.tsx": 3, "src/components/Planner/PlaceFormModal.tsx": 1, @@ -105,7 +103,7 @@ "src/mobile/screens/trip/map/MMapArea.tsx": 1, "src/mobile/screens/trip/places/MPlacesBrowser.tsx": 2, "src/mobile/screens/trip/plan/planTimelineModel.ts": 1, - "src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx": 2, + "src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx": 1, "src/mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx": 1, "src/mobile/screens/trip/roadtrip/MRtCorridorBar.tsx": 1, "src/mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx": 2, diff --git a/client/scripts/theme-baseline.json b/client/scripts/theme-baseline.json index e9a007d72..10da2cade 100644 --- a/client/scripts/theme-baseline.json +++ b/client/scripts/theme-baseline.json @@ -40,7 +40,7 @@ "components/Journey/JourneyDetailPageProviderPicker.tsx": 163, "components/Journey/JourneyDetailPageScrollTrigger.tsx": 4, "components/Journey/JourneyDetailPageVerdictSection.tsx": 51, - "components/Journey/JourneyEntryCover.tsx": 15, + "components/Journey/JourneyEntryCover.tsx": 13, "components/Journey/JourneyMap.tsx": 3, "components/Journey/JourneyMapGL.tsx": 5, "components/Journey/MobileEntryView.tsx": 94, @@ -60,8 +60,8 @@ "components/Map/LocationButton.tsx": 1, "components/Map/MapPluginMarkers.tsx": 2, "components/Map/MapTogglePill.tsx": 1, - "components/Map/MapView.tsx": 8, - "components/Map/MapViewGL.tsx": 11, + "components/Map/MapView.tsx": 7, + "components/Map/MapViewGL.tsx": 10, "components/Map/NightPauseTooltip.tsx": 1, "components/Map/PlaceHoverCard.tsx": 1, "components/Map/ReservationOverlay.tsx": 5, @@ -71,12 +71,11 @@ "components/Map/poiCategories.ts": 7, "components/Map/ratingBadge.ts": 2, "components/Map/reservationsMapbox.ts": 1, - "components/PDF/TripPDF.tsx": 51, + "components/Map/switcherRow.ts": 1, + "components/PDF/TripPDF.tsx": 44, "components/Packing/PackingListPanelBagModal.tsx": 2, "components/Packing/PackingListPanelCategoryGroup.tsx": 5, - "components/Packing/PackingListPanelHeader.tsx": 5, - "components/Packing/PackingListPanelItemRow.tsx": 2, - "components/Packing/PackingShareControl.tsx": 3, + "components/Packing/PackingListPanelHeader.tsx": 3, "components/Packing/packingPrintDocument.ts": 24, "components/Planner/AirTrailImportModal.tsx": 4, "components/Planner/BookingCostsSection.tsx": 1, @@ -109,7 +108,7 @@ "components/SystemNotices/SystemNoticeModal.tsx": 107, "components/Todo/TodoListPanel.tsx": 6, "components/Todo/todoListModel.ts": 3, - "components/Trips/TripFormModal.tsx": 9, + "components/Trips/TripFormModal.tsx": 6, "components/Vacay/VacayBadge.tsx": 3, "components/Vacay/VacayCalendar.tsx": 20, "components/Vacay/VacayMonthCard.tsx": 5, @@ -125,7 +124,6 @@ "components/shared/CustomSelect.tsx": 1, "components/shared/CustomTimePicker.tsx": 1, "components/shared/EmptyState.tsx": 1, - "components/shared/ErrorBoundary.tsx": 2, "components/shared/Modal.tsx": 3, "components/shared/NavigationMenu.tsx": 1, "components/shared/NoteColorPicker.tsx": 2, @@ -147,10 +145,10 @@ "mobile/components/MStorageTestResult.tsx": 3, "mobile/components/MToastHost.tsx": 2, "mobile/components/MUserPickerList.tsx": 1, - "mobile/screens/admin/MAdmin.tsx": 9, - "mobile/screens/admin/MAdminAddonManager.tsx": 9, + "mobile/screens/admin/MAdmin.tsx": 8, + "mobile/screens/admin/MAdminAddonManager.tsx": 4, "mobile/screens/admin/MAdminAuditLogPanel.tsx": 15, - "mobile/screens/admin/MAdminBackupPanel.tsx": 8, + "mobile/screens/admin/MAdminBackupPanel.tsx": 7, "mobile/screens/admin/MAdminCategoryManager.tsx": 8, "mobile/screens/admin/MAdminDefaultUserSettings.tsx": 5, "mobile/screens/admin/MAdminDevNotificationsPanel.tsx": 6, @@ -158,40 +156,40 @@ "mobile/screens/admin/MAdminMcpTokensPanel.tsx": 14, "mobile/screens/admin/MAdminNotifyMatrix.tsx": 5, "mobile/screens/admin/MAdminPackingTemplateManager.tsx": 8, - "mobile/screens/admin/MAdminPermissionsPanel.tsx": 5, - "mobile/screens/admin/MAdminPluginsPanel.tsx": 129, - "mobile/screens/admin/MAdminSettingsSection.tsx": 10, + "mobile/screens/admin/MAdminPermissionsPanel.tsx": 1, + "mobile/screens/admin/MAdminPluginsPanel.tsx": 128, + "mobile/screens/admin/MAdminSettingsSection.tsx": 2, "mobile/screens/admin/MAdminSheets.tsx": 11, "mobile/screens/admin/MAdminStoragePanel.tsx": 42, - "mobile/screens/admin/MAdminUi.tsx": 10, - "mobile/screens/admin/MAdminUsersSection.tsx": 14, + "mobile/screens/admin/MAdminUi.tsx": 7, + "mobile/screens/admin/MAdminUsersSection.tsx": 13, "mobile/screens/admin/MApiProviderBlocks.tsx": 10, - "mobile/screens/atlas/MAtlas.tsx": 7, - "mobile/screens/atlas/MAtlasBucketSheet.tsx": 16, + "mobile/screens/atlas/MAtlas.tsx": 5, + "mobile/screens/atlas/MAtlasBucketSheet.tsx": 14, "mobile/screens/atlas/MAtlasCountryPopup.tsx": 11, "mobile/screens/atlas/MAtlasSearch.tsx": 5, "mobile/screens/atlas/MAtlasStatsCard.tsx": 3, - "mobile/screens/collections/MCollAddSheet.tsx": 7, + "mobile/screens/collections/MCollAddSheet.tsx": 6, "mobile/screens/collections/MCollCategoryPicker.tsx": 2, - "mobile/screens/collections/MCollEditSheet.tsx": 5, + "mobile/screens/collections/MCollEditSheet.tsx": 2, "mobile/screens/collections/MCollLabelsSheet.tsx": 6, "mobile/screens/collections/MCollLinksEditor.tsx": 2, "mobile/screens/collections/MCollListPickerSheet.tsx": 3, "mobile/screens/collections/MCollPlaceRow.tsx": 3, "mobile/screens/collections/MCollPlaceSheet.tsx": 11, "mobile/screens/collections/MCollShareSheet.tsx": 14, - "mobile/screens/collections/MCollSheetKit.tsx": 6, + "mobile/screens/collections/MCollSheetKit.tsx": 5, "mobile/screens/collections/MCollTripPickerSheet.tsx": 4, - "mobile/screens/collections/MCollections.tsx": 21, + "mobile/screens/collections/MCollections.tsx": 13, "mobile/screens/dashboard/MDashWidgets.tsx": 22, - "mobile/screens/dashboard/MDashboard.tsx": 36, - "mobile/screens/dashboard/MNewTripSheet.tsx": 20, + "mobile/screens/dashboard/MDashboard.tsx": 30, + "mobile/screens/dashboard/MNewTripSheet.tsx": 12, "mobile/screens/dashboard/MUserMenu.tsx": 7, "mobile/screens/journey/MJourney.tsx": 10, - "mobile/screens/journey/MJourneyCreateSheet.tsx": 10, + "mobile/screens/journey/MJourneyCreateSheet.tsx": 7, "mobile/screens/journey/MJourneyDetail.tsx": 6, - "mobile/screens/journey/MJourneyEntrySheet.tsx": 52, - "mobile/screens/journey/MJourneySettingsSheet.tsx": 32, + "mobile/screens/journey/MJourneyEntrySheet.tsx": 48, + "mobile/screens/journey/MJourneySettingsSheet.tsx": 2, "mobile/screens/journey/mobileJourneyMeta.ts": 4, "mobile/screens/notifications/MNotificationRow.tsx": 4, "mobile/screens/notifications/MNotifications.tsx": 3, @@ -202,28 +200,27 @@ "mobile/screens/settings/MMobileNavCustomizer.tsx": 8, "mobile/screens/settings/MPhotoProvidersSection.tsx": 2, "mobile/screens/settings/MScopeGroupPicker.tsx": 5, - "mobile/screens/settings/MSetPickerSheet.tsx": 2, - "mobile/screens/settings/MSettings.tsx": 2, + "mobile/screens/settings/MSetPickerSheet.tsx": 1, + "mobile/screens/settings/MSettings.tsx": 1, "mobile/screens/settings/MSettingsAbout.tsx": 5, "mobile/screens/settings/MSettingsAccount.tsx": 20, "mobile/screens/settings/MSettingsAppearance.tsx": 12, "mobile/screens/settings/MSettingsMap.tsx": 5, - "mobile/screens/settings/MSettingsMcp.tsx": 30, + "mobile/screens/settings/MSettingsMcp.tsx": 26, "mobile/screens/settings/MSettingsNotifications.tsx": 5, "mobile/screens/settings/MSettingsOffline.tsx": 18, "mobile/screens/settings/MSettingsPlugins.tsx": 14, - "mobile/screens/settings/MSettingsUi.tsx": 11, + "mobile/screens/settings/MSettingsUi.tsx": 10, "mobile/screens/settings/MWebPushCard.tsx": 1, "mobile/screens/trip/MTripLoadingSplash.tsx": 2, - "mobile/screens/trip/MTripShell.tsx": 9, + "mobile/screens/trip/MTripShell.tsx": 7, "mobile/screens/trip/places/MPlacesBrowser.tsx": 10, - "mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": 4, + "mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": 2, "mobile/screens/trip/places/MPlacesFilterControls.tsx": 1, - "mobile/screens/trip/places/MPlacesFilterSheet.tsx": 3, - "mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx": 7, + "mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx": 6, "mobile/screens/trip/places/MPlacesToursModeSwitch.tsx": 1, - "mobile/screens/trip/plan/MPlanTimeline.tsx": 14, - "mobile/screens/trip/plan/MPlanTimelineRows.tsx": 26, + "mobile/screens/trip/plan/MPlanTimeline.tsx": 12, + "mobile/screens/trip/plan/MPlanTimelineRows.tsx": 24, "mobile/screens/trip/roadtrip/MRoadtripRows.tsx": 31, "mobile/screens/trip/roadtrip/MRoadtripTab.tsx": 16, "mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx": 8, @@ -237,27 +234,26 @@ "mobile/screens/trip/sheets/ImpFileStep.tsx": 12, "mobile/screens/trip/sheets/ImpListStep.tsx": 3, "mobile/screens/trip/sheets/MAccommodationSheet.tsx": 10, - "mobile/screens/trip/sheets/MBookingFields.tsx": 6, - "mobile/screens/trip/sheets/MBrowseActionsSheet.tsx": 5, + "mobile/screens/trip/sheets/MBookingFields.tsx": 5, + "mobile/screens/trip/sheets/MBrowseActionsSheet.tsx": 3, "mobile/screens/trip/sheets/MCostSheet.tsx": 33, "mobile/screens/trip/sheets/MDaySheet.tsx": 22, "mobile/screens/trip/sheets/MDaysSheet.tsx": 4, "mobile/screens/trip/sheets/MExportSheet.tsx": 2, "mobile/screens/trip/sheets/MImportSheet.tsx": 2, - "mobile/screens/trip/sheets/MLinkedCosts.tsx": 9, + "mobile/screens/trip/sheets/MLinkedCosts.tsx": 8, "mobile/screens/trip/sheets/MMehrSheet.tsx": 3, "mobile/screens/trip/sheets/MNoteSheet.tsx": 1, "mobile/screens/trip/sheets/MPlaceEditSheet.tsx": 2, "mobile/screens/trip/sheets/MPlaceSheet.tsx": 23, "mobile/screens/trip/sheets/MReservationSheet.tsx": 2, "mobile/screens/trip/sheets/MTransportFormSheet.tsx": 9, - "mobile/screens/trip/sheets/MTransportSheet.tsx": 12, + "mobile/screens/trip/sheets/MTransportSheet.tsx": 9, "mobile/screens/trip/sheets/MTripSheetUi.tsx": 5, - "mobile/screens/trip/sheets/MTripSheets.tsx": 2, - "mobile/screens/trip/sheets/PlCategoryPicker.tsx": 2, - "mobile/screens/trip/sheets/PlFileAttach.tsx": 7, + "mobile/screens/trip/sheets/PlCategoryPicker.tsx": 1, + "mobile/screens/trip/sheets/PlFileAttach.tsx": 3, "mobile/screens/trip/sheets/PlPlaceSearch.tsx": 6, - "mobile/screens/trip/sheets/PlSheetChrome.tsx": 7, + "mobile/screens/trip/sheets/PlSheetChrome.tsx": 5, "mobile/screens/trip/sheets/PlTimeFields.tsx": 3, "mobile/screens/trip/tabs/MBagsSheet.tsx": 13, "mobile/screens/trip/tabs/MBookingsTab.tsx": 2, @@ -265,27 +261,27 @@ "mobile/screens/trip/tabs/MCollabNotes.tsx": 19, "mobile/screens/trip/tabs/MCollabPolls.tsx": 18, "mobile/screens/trip/tabs/MCollabTab.tsx": 1, - "mobile/screens/trip/tabs/MCostsTab.tsx": 71, + "mobile/screens/trip/tabs/MCostsTab.tsx": 70, "mobile/screens/trip/tabs/MDocSyncSheet.tsx": 43, "mobile/screens/trip/tabs/MFileLightbox.tsx": 12, "mobile/screens/trip/tabs/MFileLinkSheet.tsx": 2, "mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1, "mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4, "mobile/screens/trip/tabs/MFilesTab.tsx": 12, - "mobile/screens/trip/tabs/MPackItemSheet.tsx": 7, + "mobile/screens/trip/tabs/MPackItemSheet.tsx": 1, "mobile/screens/trip/tabs/MPackingImportSheet.tsx": 3, - "mobile/screens/trip/tabs/MPackingListTab.tsx": 32, + "mobile/screens/trip/tabs/MPackingListTab.tsx": 2, "mobile/screens/trip/tabs/MReservationCardParts.tsx": 6, "mobile/screens/trip/tabs/MTaskSheet.tsx": 6, - "mobile/screens/trip/tabs/MTodoListTab.tsx": 15, + "mobile/screens/trip/tabs/MTodoListTab.tsx": 3, "mobile/screens/trip/tabs/MTransportsTab.tsx": 2, "mobile/screens/trip/tabs/filesModel.ts": 5, "mobile/screens/trip/tabs/tabChrome.tsx": 12, - "mobile/screens/vacay/MVacay.tsx": 23, - "mobile/screens/vacay/MVacayInviteSheet.tsx": 9, + "mobile/screens/vacay/MVacay.tsx": 17, + "mobile/screens/vacay/MVacayInviteSheet.tsx": 8, "mobile/screens/vacay/MVacayMonth.tsx": 3, - "mobile/screens/vacay/MVacaySettingsSheet.tsx": 35, - "mobile/screens/vacay/MVacayShareSheet.tsx": 11, + "mobile/screens/vacay/MVacaySettingsSheet.tsx": 34, + "mobile/screens/vacay/MVacayShareSheet.tsx": 10, "mobile/screens/vacay/vacayDayModel.ts": 1, "pages/AtlasPage.tsx": 32, "pages/DashboardPage.tsx": 1, @@ -296,7 +292,7 @@ "pages/JourneyDetailPage.tsx": 53, "pages/JourneyPage.tsx": 64, "pages/JourneyPublicPage.tsx": 113, - "pages/LoginPage.tsx": 58, + "pages/LoginPage.tsx": 54, "pages/OAuthAuthorizePage.tsx": 33, "pages/PluginPage.tsx": 1, "pages/ResetPasswordPage.tsx": 23, @@ -304,6 +300,7 @@ "pages/VacayPage.tsx": 13, "pages/atlas/useAtlas.ts": 2, "pages/collections/useCollections.ts": 1, + "pages/login/MfaCodeStep.tsx": 4, "pages/sharedTrip/SharedChrome.tsx": 2, "pages/sharedTrip/SharedMap.tsx": 1, "pages/tripPlanner/ListsContainer.tsx": 1, diff --git a/client/scripts/theme-disable-baseline.json b/client/scripts/theme-disable-baseline.json index 2a56b0a8b..b9692c6be 100644 --- a/client/scripts/theme-disable-baseline.json +++ b/client/scripts/theme-disable-baseline.json @@ -19,8 +19,10 @@ "components/Journey/journeyPhotoLayer.ts": 2, "components/Map/DawarichTrailLayer.tsx": 1, "components/Map/dawarichTrail.ts": 10, + "components/Map/markerLook.ts": 1, + "components/Map/poiCategories.ts": 2, "components/Map/useDawarichTrailGL.ts": 1, - "components/Packing/PackingListPanelItemRow.tsx": 1, + "components/Packing/PackingBringersCard.tsx": 1, "components/Planner/DayReorderPopup.tsx": 1, "components/Planner/bookings/bookingsModel.ts": 1, "components/Planner/bookings/transitParts.tsx": 1, @@ -53,6 +55,7 @@ "components/shared/DialogShell.tsx": 2, "components/shared/PasswordChecklist.tsx": 2, "mobile/components/MSheet.tsx": 1, + "mobile/components/MWalletButton.tsx": 1, "mobile/screens/atlas/MAtlas.tsx": 1, "mobile/screens/atlas/MAtlasCountryPopup.tsx": 2, "mobile/screens/atlas/MAtlasSearch.tsx": 1, diff --git a/client/src/App.tsx b/client/src/App.tsx index 6419e2018..59baf4af5 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useState, useRef, ReactNode, Suspense } from 'react' -import { Routes, Route, Navigate, useLocation } from 'react-router' +import { Routes, Route, Navigate, useLocation, useNavigationType } from 'react-router' import { useAuthStore } from './store/authStore' import { useSettingsStore } from './store/settingsStore' import { applyAppearance } from './theme/applyAppearance' @@ -21,6 +21,7 @@ import { lazyWithRetry } from './utils/lazyWithRetry' import { reconcileAppVersion } from './utils/versionHandover' import { useServerVersionStore } from './store/serverVersionStore' import { useIsPhone } from './mobile/useIsPhone' +import { useRouteTransition } from './mobile/routeTransition' import { TranslationProvider, useTranslation } from './i18n' import { authApi, isAuthPublicPath } from './api/client' import { tripRepo } from './repo/tripRepo' @@ -32,6 +33,12 @@ import { useRoadtripPreferencesSync } from './hooks/useRoadtripPreferencesSync' import { registerSyncTriggers, unregisterSyncTriggers } from './sync/syncTriggers' import OfflineBanner from './components/Layout/OfflineBanner' import NewVersionNotice from './components/Layout/NewVersionNotice' +import NativeUpdateNotice from './components/Layout/NativeUpdateNotice' +import AppLockGate from './components/Layout/AppLockGate' +import NativeImportSheet from './mobile/components/NativeImportSheet' +import MPushPrompt from './mobile/components/MPushPrompt' +import NativeWidgetsSync from './components/Layout/NativeWidgetsSync' +import NativeQuickActionsSync from './components/Layout/NativeQuickActionsSync' import { SystemNoticeHost } from './components/SystemNotices/SystemNoticeHost.js' import HelpPanel from './components/Help/HelpPanel' // Notice action registrations (side-effect imports): @@ -45,6 +52,7 @@ import { managedRoutes } from './managed' // for a reload. const PluginPage = lazyWithRetry(() => import('./pages/PluginPage')) const ForgotPasswordPage = lazyWithRetry(() => import('./pages/ForgotPasswordPage')) +const NativeHandoffPage = lazyWithRetry(() => import('./pages/NativeHandoffPage')) const ResetPasswordPage = lazyWithRetry(() => import('./pages/ResetPasswordPage')) const DashboardPage = lazyWithRetry(() => import('./pages/DashboardPage')) const TripPlannerPage = lazyWithRetry(() => import('./pages/TripPlannerPage')) @@ -406,6 +414,9 @@ export default function App() { }, [settings.dark_mode, settings.appearance, isSharedPage]) const isPhone = useIsPhone() + // On the phone, pages slide like a native navigation stack (mobile/routeTransition.ts). + const navigationType = useNavigationType() + const routedLocation = useRouteTransition(location, navigationType, isPhone) const keepingTour = useSaveToCollectionStore(s => s.tour !== null) const isAuthPage = location.pathname.startsWith('/login') || location.pathname.startsWith('/register') @@ -441,18 +452,25 @@ export default function App() { )} + + + + {!hideAuthedWidgets && isPhone && } + + {/* One boundary for all route chunks, above so it stays mounted across navigations. react-router runs location updates inside a transition, so a mounted boundary keeps the current page on screen instead of flashing a spinner on every jump — the spinner is for the first paint of a deep link. */} }> - + } /> } /> } /> } /> } /> } /> + } /> } /> {/* OAuth 2.1 consent page — intentionally outside ProtectedRoute */} } /> diff --git a/client/src/api/assignmentStay.ts b/client/src/api/assignmentStay.ts new file mode 100644 index 000000000..6c773bb86 --- /dev/null +++ b/client/src/api/assignmentStay.ts @@ -0,0 +1,8 @@ +import { assignmentSchema, type AssignmentStayRequest } from '@trek/shared'; +import { apiClient } from './client'; + +/** How long the drive stands at one visit (#3092); null hands it back to the place's stay. */ +export async function saveAssignmentStay(tripId: number | string, id: number, body: AssignmentStayRequest) { + const saved = await apiClient.put(`/trips/${tripId}/assignments/${id}/stay`, body); + return assignmentSchema.parse(saved.data.assignment); +} diff --git a/client/src/api/client.behavior.test.ts b/client/src/api/client.behavior.test.ts index 087965f83..cc49538fe 100644 --- a/client/src/api/client.behavior.test.ts +++ b/client/src/api/client.behavior.test.ts @@ -12,6 +12,8 @@ const { probeNow } = vi.hoisted(() => ({ probeNow: vi.fn(async (): Promise<'online' | 'offline' | 'proxy-wall'> => 'offline'), })) vi.mock('../sync/connectivity', () => ({ probeNow })) +const isNativeApp = vi.hoisted(() => vi.fn(() => false)) +vi.mock('../native/platform', () => ({ isNativeApp })) const { apiClient, adminApi, mapsApi, pluginsApi, parseInDev } = await import('./client') @@ -357,6 +359,24 @@ describe('client > redirect handling', () => { expect(loc.href).toBe('/login?redirect=' + encodeURIComponent('/trips/7?tab=map#day-2')) }) + it('FE-APIWIRE-019b: in the app it waits for the first page to finish loading before it leaves', async () => { + isNativeApp.mockReturnValue(true) + const ready = Object.getOwnPropertyDescriptor(Document.prototype, 'readyState') + Object.defineProperty(document, 'readyState', { value: 'loading', configurable: true }) + const loc = setLocation('/dashboard') + server.use(http.get('/api/auth/me', () => HttpResponse.json({ code: 'AUTH_REQUIRED' }, { status: 401 }))) + + await captureError(() => apiClient.get('/auth/me')) + expect(loc.href).not.toContain('/login') + + window.dispatchEvent(new Event('load')) + expect(loc.href).toBe('/login?redirect=' + encodeURIComponent('/dashboard')) + + delete (document as { readyState?: unknown }).readyState + if (ready) Object.defineProperty(Document.prototype, 'readyState', ready) + isNativeApp.mockReturnValue(false) + }) + it('FE-APIWIRE-020: an MFA_REQUIRED 403 sends the user to the settings page', async () => { const loc = setLocation('/dashboard') server.use(http.get('/api/auth/me', () => HttpResponse.json({ code: 'MFA_REQUIRED' }, { status: 403 }))) diff --git a/client/src/api/client.ts b/client/src/api/client.ts index fa7dc7b24..056b13662 100644 --- a/client/src/api/client.ts +++ b/client/src/api/client.ts @@ -70,13 +70,13 @@ import { RoadtripVia, RoadtripViaBatchRequest, RoadtripViaCreateRequest, - RoadtripViaReanchorRequest, - RoadtripViaUpdateRequest, + RoadtripViaReanchorRequest, RoadtripViaUpdateRequest, } from '@trek/shared' import { getSocketId } from './websocket' import { probeNow } from '../sync/connectivity' import { downloadBlob } from '../utils/fileDownload' import { translateRateLimit } from './rateLimitMessage' +import { hardNavigate } from './hardNavigate' /** * Validate a response payload against its @trek/shared Zod schema — but only in @@ -145,7 +145,7 @@ apiClient.interceptors.request.use( ) export function isAuthPublicPath(pathname: string): boolean { - const publicPaths = ['/login', '/register', '/forgot-password', '/reset-password'] + const publicPaths = ['/login', '/register', '/forgot-password', '/reset-password', '/native-handoff'] const publicPrefixes = ['/shared/', '/public/'] return publicPaths.includes(pathname) || publicPrefixes.some((p) => pathname.startsWith(p)) } @@ -218,7 +218,7 @@ apiClient.interceptors.response.use( const { pathname } = window.location if (!isAuthPublicPath(pathname)) { const currentPath = pathname + window.location.search + window.location.hash - window.location.href = '/login?redirect=' + encodeURIComponent(currentPath) + hardNavigate('/login?redirect=' + encodeURIComponent(currentPath)) } } if ( @@ -226,7 +226,7 @@ apiClient.interceptors.response.use( (error.response?.data as { code?: string } | undefined)?.code === 'MFA_REQUIRED' && !window.location.pathname.startsWith('/settings') ) { - window.location.href = '/settings?mfa=required' + hardNavigate('/settings?mfa=required') } if (error.response?.status === 429) { const translated = translateRateLimit() @@ -520,7 +520,7 @@ export const packingApi = { reorder: (tripId: number | string, orderedIds: number[]) => apiClient.put(`/trips/${tripId}/packing/reorder`, { orderedIds } satisfies PackingReorderRequest).then(r => r.data), setSharing: (tripId: number | string, id: number, data: PackingSetSharingRequest) => apiClient.put(`/trips/${tripId}/packing/${id}/sharing`, data).then(r => r.data), clone: (tripId: number | string, id: number) => apiClient.post(`/trips/${tripId}/packing/${id}/clone`).then(r => r.data), - addContributor: (tripId: number | string, id: number) => apiClient.post(`/trips/${tripId}/packing/${id}/contributors`).then(r => r.data), + addContributor: (tripId: number | string, id: number, userId?: number) => apiClient.post(`/trips/${tripId}/packing/${id}/contributors`, userId == null ? undefined : { user_id: userId }).then(r => r.data), removeContributor: (tripId: number | string, id: number, userId: number) => apiClient.delete(`/trips/${tripId}/packing/${id}/contributors/${userId}`).then(r => r.data), getCategoryAssignees: (tripId: number | string) => apiClient.get(`/trips/${tripId}/packing/category-assignees`).then(r => r.data), setCategoryAssignees: (tripId: number | string, categoryName: string, userIds: number[]) => apiClient.put(`/trips/${tripId}/packing/category-assignees/${encodeURIComponent(categoryName)}`, { user_ids: userIds } satisfies PackingCategoryAssigneesRequest).then(r => r.data), diff --git a/client/src/api/collections.test.ts b/client/src/api/collections.test.ts index 65ca3e974..c0796d3e0 100644 --- a/client/src/api/collections.test.ts +++ b/client/src/api/collections.test.ts @@ -1,4 +1,4 @@ -// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-034 +// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-035 // // 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 @@ -352,6 +352,15 @@ describe('collectionsApi', () => { expect(res).toEqual({ name: 'Tokyo', gpx: '', waypoints: 0, omitted: 2 }) }) + it('FE-API-COLLECTIONS-035: exportKml() reads the KML of a list by id (#1866)', async () => { + server.use(http.get(`${BASE}/:id/export/kml`, record({ name: 'Tokyo', kml: '', pins: 1, omitted: 0 }))) + + const res = await collectionsApi.exportKml(1) + + expect(requestUrl).toContain(`${BASE}/1/export/kml`) + expect(res).toEqual({ name: 'Tokyo', kml: '', pins: 1, omitted: 0 }) + }) + 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 }))) diff --git a/client/src/api/collections.ts b/client/src/api/collections.ts index 71f1ed8dd..bce9d0a5e 100644 --- a/client/src/api/collections.ts +++ b/client/src/api/collections.ts @@ -17,6 +17,7 @@ import type { CollectionGpxExport, CollectionGpxReadRequest, CollectionGpxReadResult, + CollectionKmlExport, CollectionPlaceUpdateRequest, CollectionCopyToTripRequest, CollectionInviteRequest, @@ -75,6 +76,9 @@ export const collectionsApi = { ax.get(`${base}/${id}/export/gpx`).then((r: AxiosResponse) => r.data), readGpx: (body: CollectionGpxReadRequest): Promise => ax.post(`${base}/gpx/read`, body satisfies CollectionGpxReadRequest).then((r: AxiosResponse) => r.data), + /** The same list as pins for Google My Maps (#1866). */ + exportKml: (id: number): Promise => + ax.get(`${base}/${id}/export/kml`).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 diff --git a/client/src/api/flightLive.ts b/client/src/api/flightLive.ts new file mode 100644 index 000000000..b53db44e9 --- /dev/null +++ b/client/src/api/flightLive.ts @@ -0,0 +1,11 @@ +import apiClient from './client'; + +/** + * GET /api/trips/:tripId/flights/live: the live state of every flight leg of a + * trip TREK can follow. The answer comes back unparsed; store/flightLiveStore.ts + * checks it against the shared contract before anything draws it. + */ +export const flightLiveApi = { + trip: (tripId: number, signal?: AbortSignal): Promise => + apiClient.get(`/trips/${tripId}/flights/live`, { signal }).then((response) => response.data as unknown), +}; diff --git a/client/src/api/hardNavigate.ts b/client/src/api/hardNavigate.ts new file mode 100644 index 000000000..c8a843ade --- /dev/null +++ b/client/src/api/hardNavigate.ts @@ -0,0 +1,15 @@ +import { isNativeApp } from '../native/platform'; + +/** + * A full page load to `url`. In the apps it waits for the first page to finish + * loading: started earlier, it cancels that load, and the shell answers a + * cancelled load with its "Server not reachable" page, which is where a + * signed-out user opening the app for the first time ended up. + */ +export function hardNavigate(url: string): void { + const go = () => { + window.location.href = url; + }; + if (isNativeApp() && document.readyState !== 'complete') window.addEventListener('load', go, { once: true }); + else go(); +} diff --git a/client/src/api/mailIngest.test.ts b/client/src/api/mailIngest.test.ts new file mode 100644 index 000000000..425b3997e --- /dev/null +++ b/client/src/api/mailIngest.test.ts @@ -0,0 +1,21 @@ +// FE-MAILINGEST-API-001 +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('./client', () => ({ + default: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() }, + postMultipart: vi.fn(async () => ({ duplicate: false })), +})); + +import apiClient, { postMultipart } from './client'; +import { mailIngestApi } from './mailIngest'; + +describe('mailIngestApi.upload', () => { + it('FE-MAILINGEST-API-001: sends the .eml as a multipart form, never through the JSON post', async () => { + const file = new File(['From: a@b.c\r\n\r\nhi'], 'booking.eml', { type: 'message/rfc822' }); + expect(await mailIngestApi.upload(file)).toEqual({ duplicate: false }); + const [url, form] = vi.mocked(postMultipart).mock.calls[0]; + expect(url).toBe('/mail-ingest/upload'); + expect((form as FormData).get('file')).toBe(file); + expect(apiClient.post).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/api/mailIngest.ts b/client/src/api/mailIngest.ts new file mode 100644 index 000000000..92787e3ac --- /dev/null +++ b/client/src/api/mailIngest.ts @@ -0,0 +1,49 @@ +import apiClient, { postMultipart } from './client'; + +/** + * The booking mail import (server nest/mail-ingest): the person's settings and + * forwarding address, the inbox of bookings read from forwarded mails, and the + * actions on them. Answers come back unparsed; store/mailIngestStore.ts checks + * them against the shared contracts. apiClient puts an idempotency key on every + * write, so a request sent again on a flaky connection acts once. + */ +const data = (response: { data: unknown }) => response.data; + +export type MailIngestAction = 'apply' | 'move' | 'file' | 'undo' | 'discard'; + +export const mailIngestApi = { + // The admin's view: how the import runs, in counts only, and whether the transport reaches its mail now. + adminStatus: (): Promise => apiClient.get('/admin/mail-ingest/status').then(data), + adminTest: (): Promise => apiClient.post('/admin/mail-ingest/test', {}).then(data), + /** The stored transport fields, passwords masked, from the admin's app settings. */ + adminSettings: (): Promise => apiClient.get('/auth/app-settings').then(data), + saveAdminSettings: (patch: Record): Promise => + apiClient.put('/auth/app-settings', patch).then(data), + + settings: (): Promise => apiClient.get('/mail-ingest/settings').then(data), + updateSettings: (body: { enabled?: boolean; ai_enabled?: boolean; auto_add?: boolean }): Promise => + apiClient.patch('/mail-ingest/settings', body).then(data), + renewAddress: (): Promise => apiClient.post('/mail-ingest/address/renew', {}).then(data), + + tripAddress: (tripId: number): Promise => apiClient.get(`/trips/${tripId}/mail-ingest/address`).then(data), + createTripAddress: (tripId: number): Promise => + apiClient.post(`/trips/${tripId}/mail-ingest/address`, {}).then(data), + + inbox: (params: { status?: 'open' | 'resolved'; before?: number; limit?: number }): Promise => + apiClient.get('/mail-ingest/inbox', { params }).then(data), + inboxCount: (): Promise => apiClient.get('/mail-ingest/inbox/count').then(data), + preview: (messageId: number): Promise => + apiClient.get(`/mail-ingest/messages/${messageId}/preview`).then(data), + prefill: (candidateId: number): Promise => + apiClient.get(`/mail-ingest/candidates/${candidateId}/prefill`).then(data), + + act: (candidateId: number, action: MailIngestAction, body: Record = {}): Promise => + apiClient.post(`/mail-ingest/candidates/${candidateId}/${action}`, body).then(data), + + upload: (file: File): Promise => { + const form = new FormData(); + form.append('file', file); + // As multipart: under the client's default JSON content type the form went as JSON, without the file. + return postMultipart('/mail-ingest/upload', form); + }, +}; diff --git a/client/src/api/nativeAuth.test.ts b/client/src/api/nativeAuth.test.ts new file mode 100644 index 000000000..56c1adff5 --- /dev/null +++ b/client/src/api/nativeAuth.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it, vi } from 'vitest'; +import { apiClient } from './client'; +import { nativeAuthApi } from './nativeAuth'; + +vi.mock('./client', () => ({ apiClient: { post: vi.fn() } })); + +describe('nativeAuthApi', () => { + it('mints a hand-off code for a challenge', async () => { + vi.mocked(apiClient.post).mockResolvedValue({ data: { code: 'c1' } }); + await expect(nativeAuthApi.handoff('ab'.repeat(32))).resolves.toEqual({ code: 'c1' }); + expect(apiClient.post).toHaveBeenCalledWith('/auth/native/handoff', { challenge: 'ab'.repeat(32) }); + }); + + it('redeems the code with its verifier', async () => { + vi.mocked(apiClient.post).mockResolvedValue({ data: { ok: true } }); + await expect(nativeAuthApi.exchange({ code: 'c1', verifier: 'v'.repeat(64) })).resolves.toBeUndefined(); + expect(apiClient.post).toHaveBeenCalledWith('/auth/native/exchange', { code: 'c1', verifier: 'v'.repeat(64) }); + }); +}); diff --git a/client/src/api/nativeAuth.ts b/client/src/api/nativeAuth.ts new file mode 100644 index 000000000..db02fbc8e --- /dev/null +++ b/client/src/api/nativeAuth.ts @@ -0,0 +1,12 @@ +import type { NativeExchangeRequest, NativeHandoffResponse } from '@trek/shared'; +import { apiClient } from './client'; + +/** The two halves of the sign-in hand-off between system browser and app. */ +export const nativeAuthApi = { + /** Browser side: trade a signed-in session for a one-time code bound to `challenge`. */ + handoff: (challenge: string): Promise => + apiClient.post('/auth/native/handoff', { challenge }).then((r) => r.data), + /** App side: redeem the code with the verifier; the response sets the session cookie. */ + exchange: (body: NativeExchangeRequest): Promise => + apiClient.post('/auth/native/exchange', body).then(() => undefined), +}; diff --git a/client/src/api/tripTags.ts b/client/src/api/tripTags.ts new file mode 100644 index 000000000..faa01d698 --- /dev/null +++ b/client/src/api/tripTags.ts @@ -0,0 +1,14 @@ +import type { TripTagCreateRequest, TripTagListResponse, TripTagResponse, TripTagUpdateRequest } from '@trek/shared'; +import apiClient from './client'; + +/** The tags a trip owns: every member reads them, and whoever may edit its places adds one. */ +export const tripTagsApi = { + list: (tripId: number | string): Promise => + apiClient.get(`/trips/${tripId}/tags`).then((r) => r.data), + /** Answers the trip's existing tag when it already has one of that name. */ + create: (tripId: number | string, body: TripTagCreateRequest): Promise => + apiClient.post(`/trips/${tripId}/tags`, body).then((r) => r.data), + /** A new name or colour for one of the trip's tags; every place carrying it shows the change. */ + update: (tripId: number | string, tagId: number, body: TripTagUpdateRequest): Promise => + apiClient.put(`/trips/${tripId}/tags/${tagId}`, body).then((r) => r.data), +}; diff --git a/client/src/api/wsEventPolicy.ts b/client/src/api/wsEventPolicy.ts index 3aa08c4b8..2095dd56c 100644 --- a/client/src/api/wsEventPolicy.ts +++ b/client/src/api/wsEventPolicy.ts @@ -21,6 +21,11 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [ 'tours:changed', // CW-03: store/tourVisitStore (watchTourVisits) keeps the visits store current. 'tours:visits', + // store/flightLiveStore (watchFlightLive, mounted by useFlightLiveSync) merges live flight states. + 'flight:live', + // store/mailIngestStore (watchMailInbox, mounted by Navbar and MMailInboxHost): the open count and the settings card. + 'mailInbox:changed', + 'mailInbox:settings', // Collab — Collab/MCollab components + useTripWebSocket's collabFileSync 'collab:note:created', 'collab:note:updated', diff --git a/client/src/components/Admin/AddonManager.test.tsx b/client/src/components/Admin/AddonManager.test.tsx index 8338b5a63..66e3470e4 100644 --- a/client/src/components/Admin/AddonManager.test.tsx +++ b/client/src/components/Admin/AddonManager.test.tsx @@ -53,12 +53,6 @@ function isOn(toggle: HTMLElement): boolean { return toggle.getAttribute('aria-pressed') === 'true'; } -/** A shelf of more than one row starts folded; open every one so its rows can be read. */ -async function unfoldShelves(): Promise { - const bars = await screen.findAllByRole('button', { name: /\d+ options?/, expanded: false }); - for (const bar of bars) await userEvent.click(bar); -} - beforeAll(() => { Object.defineProperty(window, 'matchMedia', { writable: true, @@ -236,7 +230,6 @@ describe('AddonManager', () => { ) ); render(); - await unfoldShelves(); // Provider sub-rows are visible under Journey addon await screen.findByText('Unsplash'); @@ -272,15 +265,6 @@ describe('AddonManager', () => { expect(screen.getByText('No addons available')).toBeInTheDocument(); }); - it('FE-ADMIN-ADDON-013: dark mode swaps the wordmark in the header', async () => { - // The wordmark reads the .dark class, the same source applyAppearance() writes. - document.documentElement.classList.add('dark'); - render(); - - await screen.findByText('No addons available'); - expect(screen.getByAltText('TREK')).toHaveAttribute('src', '/text-light.svg'); - }); - it('FE-ADMIN-ADDON-014: photo-flavoured trip addons are hidden from the trip section', async () => { server.use(addonsRoute([ buildAddon({ id: 'photos', name: 'Memories', icon: 'Image' }), @@ -302,7 +286,6 @@ describe('AddonManager', () => { buildAddon({ id: 'unsplash', name: 'Unsplash', description: 'Stock photos', type: 'photo_provider', enabled: false }), ])); render(); - await unfoldShelves(); await screen.findByText('Immich'); // immich and synologyphotos ship a vendor glyph, unsplash does not @@ -437,16 +420,16 @@ describe('AddonManager', () => { ])); render(); - await unfoldShelves(); 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(); + // Documents and Journey are the addons, one per type card; an enabled + // provider is a shelf row and must not turn the trip card's 1/1 into 2/2. + expect(screen.getByText('1/1')).toBeInTheDocument(); + expect(screen.getByText('0/1')).toBeInTheDocument(); }); it('FE-ADMIN-ADDON-034: document providers stay hidden while Documents itself is off', async () => { @@ -536,7 +519,6 @@ describe('AddonManager', () => { />, ); - await unfoldShelves(); await screen.findByText('Chat'); expect(screen.getByText('Notes')).toBeInTheDocument(); @@ -567,7 +549,6 @@ describe('AddonManager', () => { onToggleCollabFeature={vi.fn()} /> ); - await unfoldShelves(); const links = await screen.findByText('Links'); expect(links).toHaveAttribute('title'); @@ -623,7 +604,7 @@ describe('AddonManager', () => { await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); }); - it('FE-ADMIN-ADDON-040: a shelf of several options starts folded and says how many there are and how many are on', async () => { + it('FE-ADMIN-ADDON-040: the options of an addon are listed under it at once, nothing to unfold', async () => { server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })])); render( { /> ); - const bar = await screen.findByRole('button', { name: /5 options/, expanded: false }); - expect(bar).toHaveTextContent('2 on'); - expect(screen.queryByText('Chat')).not.toBeInTheDocument(); - - await userEvent.click(bar); - expect(bar).toHaveAttribute('aria-expanded', 'true'); - expect(screen.getByText('Chat')).toBeInTheDocument(); - - await userEvent.click(bar); - expect(screen.queryByText('Chat')).not.toBeInTheDocument(); + expect(await screen.findByRole('button', { name: 'Chat' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Polls' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /\d+ options?/ })).not.toBeInTheDocument(); }); it('FE-ADMIN-ADDON-041: a shelf of one option shows it at once, without a fold', async () => { @@ -668,10 +642,6 @@ describe('AddonManager', () => { ); - // Folded like Collab's and Documents' options until the bar is opened. - await screen.findByRole('button', { name: /\d+ options?/, expanded: false }); - expect(screen.queryByRole('button', { name: 'wanderer' })).not.toBeInTheDocument(); - await unfoldShelves(); const toggle = await screen.findByRole('button', { name: 'wanderer' }); expect(isOn(toggle)).toBe(false); await userEvent.click(toggle); @@ -685,8 +655,7 @@ describe('AddonManager', () => { server.use(addonsRoute([buildAddon({ id: 'tours', name: 'Tours', icon: 'Mountain', enabled: true })])); render(); - await screen.findByRole('button', { name: /\d+ options?/, expanded: false }); - await unfoldShelves(); + await screen.findByText('Tours'); expect(screen.queryByRole('button', { name: 'wanderer' })).not.toBeInTheDocument(); }); @@ -702,7 +671,6 @@ describe('AddonManager', () => { ); - await unfoldShelves(); await userEvent.click(await screen.findByRole('button', { name: 'wanderer' })); await waitFor(() => expect(isOn(screen.getByRole('button', { name: 'wanderer' }))).toBe(false)); @@ -723,33 +691,4 @@ describe('AddonManager', () => { expect(roadtrip.querySelector('svg.lucide-car-front')).toBeInTheDocument(); expect(tours.querySelector('svg.lucide-puzzle')).not.toBeInTheDocument(); }); - - it('FE-ADMIN-ADDON-045: finds an addon by name or description and shows the ones on or off', async () => { - const user = userEvent.setup(); - server.use( - addonsRoute([ - buildAddon({ id: 'x-lists', name: 'Todo List', description: 'Track tasks', type: 'trip', enabled: true }), - buildAddon({ id: 'x-costs', name: 'Budget', description: 'Split costs', type: 'trip', enabled: false }), - buildAddon({ id: 'x-holiday', name: 'Vacay', description: 'Holiday planner', type: 'global', enabled: true }), - ]) - ); - render(); - await screen.findByText('Todo List'); - - await user.type(screen.getByRole('searchbox', { name: 'Search addons' }), 'costs'); - expect(screen.getByText('Budget')).toBeInTheDocument(); - expect(screen.queryByText('Todo List')).toBeNull(); - expect(screen.queryByText('Vacay')).toBeNull(); - - await user.clear(screen.getByRole('searchbox', { name: 'Search addons' })); - await user.click(screen.getByRole('button', { name: 'On' })); - expect(screen.getByText('Todo List')).toBeInTheDocument(); - expect(screen.getByText('Vacay')).toBeInTheDocument(); - expect(screen.queryByText('Budget')).toBeNull(); - - await user.click(screen.getByRole('button', { name: 'Off' })); - await user.type(screen.getByRole('searchbox', { name: 'Search addons' }), 'nothing like this'); - expect(screen.getByText('No addon matches the search or the filter.')).toBeInTheDocument(); - }); }); - diff --git a/client/src/components/Admin/AddonManager.tsx b/client/src/components/Admin/AddonManager.tsx index a5939fb5b..591b78e5b 100644 --- a/client/src/components/Admin/AddonManager.tsx +++ b/client/src/components/Admin/AddonManager.tsx @@ -1,7 +1,6 @@ -import { useState, type ComponentType } from 'react' +import type { ComponentType, ReactNode } from 'react' import { useTranslation } from '../../i18n' -import { useIsDark } from '../../hooks/useIsDark' -import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Search } from 'lucide-react' +import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront } from 'lucide-react' import EmptyState from '../shared/EmptyState' import DawarichIcon from '../shared/DawarichIcon' import AirTrailIcon from '../shared/AirTrailIcon' @@ -9,8 +8,7 @@ import { DOCUMENT_PROVIDER_ICONS } from '../shared/documentProviderIconMap' import AddonTile from './AddonTile' import AddonSubRow from './AddonSubRow' import { Tooltip } from '../shared/Tooltip' -import { fs } from '../shared/DialogShell' -import { SettingsCard, StatusPill } from '../Settings/settingsKit' +import { SettingsCard, SettingsColumns, StatusPill } from '../Settings/settingsKit' import { type Addon, type CollabFeatures, COLLAB_SUB_FEATURES, getAddonLabel } from './addons/addonModel' import { useAddonManager } from './addons/useAddonManager' import AiAddonTile from './addons/AiAddonTile' @@ -67,9 +65,15 @@ const TYPE_META: Record; labelK integration: { icon: Link2, labelKey: 'admin.addons.type.integration', hintKey: 'admin.addons.integrationHint' }, } -export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature }: { bagTrackingEnabled?: boolean; onToggleBagTracking?: () => void; collabFeatures?: CollabFeatures; onToggleCollabFeature?: (key: string) => void }) { +export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, aside }: { + bagTrackingEnabled?: boolean + onToggleBagTracking?: () => void + collabFeatures?: CollabFeatures + onToggleCollabFeature?: (key: string) => void + /** Cards that set up what the integrations reach (flight status, booking mails), under them in the right column. */ + aside?: ReactNode +}) { const { t } = useTranslation() - const dark = useIsDark() const { addons, loading, handleToggle, tripAddons, globalAddons, integrationAddons, aiAddons, providerOptions, documentProviderOptions, toursWanderer, @@ -77,9 +81,6 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, toggleToursWanderer, mapSwitches, } = useAddonManager() - const [query, setQuery] = useState('') - const [view, setView] = useState('all') - if (loading) { return ( @@ -203,39 +204,18 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, /* A card per type, the way every other admin tab sets its cards: Trip in the left column, Global and Integration in the right one, each card with the - dialogs' head band carrying the type, its count and what it means. Above - them one card says how many are on and finds an addon by name. */ + dialogs' head band carrying the type, its count and what it means. */ const groups = [ { key: 'trip', addons: tripAddons }, { key: 'global', addons: globalAddons }, { key: 'integration', addons: integrationAddons }, ].filter(g => g.addons.length > 0 || (g.key === 'integration' && aiAddons.length > 0)) - const enabledCount = addons.filter(a => a.type !== 'photo_provider' && a.type !== 'document_provider' && a.enabled).length - const totalCount = tripAddons.length + globalAddons.length + integrationAddons.length + aiAddons.length - - const subtitle = ( - - {t('admin.addons.subtitleBefore')} - TREK - {t('admin.addons.subtitleAfter')} - - ) - - /** Whether an addon is shown under the search and the filter. */ - const shown = (addon: Addon) => { - if (view === 'on' && !addon.enabled) return false - if (view === 'off' && addon.enabled) return false - const q = query.trim().toLocaleLowerCase() - if (!q) return true - const label = getAddonLabel(t, addon) - return `${label.name} ${label.description ?? ''}`.toLocaleLowerCase().includes(q) - } const card = (g: (typeof groups)[number]) => { const meta = TYPE_META[g.key] const all = g.key === 'integration' ? [...aiAddons, ...g.addons] : g.addons - const visible = g.addons.filter(shown) - const ai = g.key === 'integration' && aiAddons.some(shown) + const visible = g.addons + const ai = g.key === 'integration' && aiAddons.length > 0 if (!visible.length && !ai) return null const on = all.filter(a => a.enabled).length return ( @@ -249,8 +229,8 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, 0 ? 'success' : 'neutral'}>{on}/{all.length} )} - bodyClassName="p-3" > + {/* The addons in one rounded block of rows, as every settings card holds its rows. */}
{/* The AI addons share a connection and a settings dialog, so they head the card as one tile. */} {ai && } @@ -263,103 +243,13 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, const [first, ...rest] = groups const cards = { start: first ? card(first) : null, end: rest.map(card).filter(Boolean) } - return ( - <> - 0 ? ( - - - 0 ? 'success' : 'neutral'}>{enabledCount}/{totalCount} - - - ) : undefined} - > - {addons.length === 0 - ? - : ({ key: g.key, addons: g.key === 'integration' ? [...aiAddons, ...g.addons] : g.addons }))} query={query} onQuery={setQuery} view={view} onView={setView} t={t} />} + if (addons.length === 0) { + return ( + + + ) + } - {addons.length > 0 && (cards.start || cards.end.length > 0 ? ( -
-
{cards.start}
-
{cards.end}
-
- ) : ( -

- {t('admin.addons.noMatch')} -

- ))} - - ) -} - -type AddonView = 'all' | 'on' | 'off' - -/** - * The head card's body: a tile per type with how many of it are on, then a - * search over the addons' names and descriptions and a switch between all, - * the ones on and the ones off. - */ -function AddonToolbar({ groups, query, onQuery, view, onView, t }: { - groups: { key: string; addons: Addon[] }[] - query: string - onQuery: (q: string) => void - view: AddonView - onView: (v: AddonView) => void - t: (key: string, params?: Record) => string -}) { - return ( - <> -
- {groups.map(g => { - const meta = TYPE_META[g.key] - const Icon = meta.icon - const on = g.addons.filter(a => a.enabled).length - return ( -
- - - - - {t(meta.labelKey)} - {t('admin.addons.group.count', { enabled: on, total: g.addons.length })} - - 0 ? 'text-content' : 'text-content-faint'}`} style={fs(18, 'body')} aria-hidden>{on} -
- ) - })} -
-
- -
- {(['all', 'on', 'off'] as const).map(v => ( - - ))} -
-
- - ) + return {cards.end}{aside}} /> } diff --git a/client/src/components/Admin/AddonSubRow.tsx b/client/src/components/Admin/AddonSubRow.tsx index 4586fad1f..d8a9ba472 100644 --- a/client/src/components/Admin/AddonSubRow.tsx +++ b/client/src/components/Admin/AddonSubRow.tsx @@ -33,7 +33,8 @@ export default function AddonSubRow({ onToggle: () => void }) { return ( -
  • + // Indented under the addon's name (16 + 32 + 12 px), one step quieter than it. +
  • {icon ? {icon} : } diff --git a/client/src/components/Admin/AddonTile.tsx b/client/src/components/Admin/AddonTile.tsx index dff37d989..953fc3047 100644 --- a/client/src/components/Admin/AddonTile.tsx +++ b/client/src/components/Admin/AddonTile.tsx @@ -1,30 +1,18 @@ -import { Children, type ReactNode, isValidElement, useId, useState } from 'react' +import { Children, type ReactNode } from 'react' import ToggleSwitch from '../Settings/ToggleSwitch' +import { HintMark } from '../Settings/settingsKit' import { fs } from '../shared/DialogShell' -import { ChevronDown } from 'lucide-react' -import { useTranslation } from '../../i18n' - -/** How many of the shelf's rows are switched on, read from the rows' own `enabled`. */ -function enabledRows(rows: ReactNode[]): number { - return rows.filter((row) => isValidElement<{ enabled?: boolean }>(row) && row.props.enabled === true).length -} /** - * One addon in its type's card: a row like the bag sidebar's (#2541), with the - * icon tile on the left, name and description beside it and the switch on the - * right. Its sub-features sit under it in a grey inset box of hairline rows. + * One addon in its type's card, as a settings row: the icon tile, the name with + * its description behind an info mark, and the switch on the right. Its + * sub-features follow as indented rows while it is on, in the same list and with + * the same hairlines: no box of their own, nothing folded away. * * The on/off state rides on the icon tile and the switch: a switched-off addon - * greys its tile and its description, but keeps its name at full strength. The - * name is the tile's identity, not its state; greying it out reads as "broken" - * rather than "not enabled". - * - * The row is not a click target, only the switches are. No lift, no pointer - * cursor, no `role="button"`. - * - * A shelf of more than one row starts folded behind a bar that says how many - * options there are and how many are on, so a page of addons stays short and - * the options are still plain to see. + * greys its tile but keeps its name at full strength. The name is the row's + * identity, not its state; greying it out reads as "broken" rather than "not + * enabled". The row is not a click target, only the switches are. */ export default function AddonTile({ icon, @@ -32,90 +20,42 @@ export default function AddonTile({ description, enabled, onToggle, + trailing, children, }: { icon: ReactNode name: string description?: string enabled: boolean - onToggle: () => void - /** The sub-shelf: `` children. */ + /** The addon's switch; leave it out for a row that shows a state instead (`trailing`). */ + onToggle?: () => void + /** Shown in place of the switch. */ + trailing?: ReactNode + /** The sub-features: `` children. */ children?: ReactNode }) { - const { t } = useTranslation() - const shelfId = useId() - const [open, setOpen] = useState(false) - const rows = Children.toArray(children) - const foldable = rows.length > 1 - const active = enabledRows(rows) - return ( -
    -
    +
    +
    {icon}
    - -
    -

    - {name} -

    -

    - {description} -

    +
    +

    {name}

    + {description && }
    - -
    - +
    + {trailing ?? (onToggle && )}
    - - {rows.length > 0 && ( -
    - {foldable && ( - - )} - {/* Sitting inside the parent on its own fill is enough to say these belong - to it: no rail, no indent guides. */} - {(!foldable || open) && ( -
      {children}
    - )} -
    - )} + {/* An empty shelf (a tours addon without its options here) draws no line. */} + {Children.count(children) > 0 &&
      {children}
    }
    ) } diff --git a/client/src/components/Admin/AdminMcpTokensPanel.tsx b/client/src/components/Admin/AdminMcpTokensPanel.tsx index 6f9e3a9bd..5e0aa41b5 100644 --- a/client/src/components/Admin/AdminMcpTokensPanel.tsx +++ b/client/src/components/Admin/AdminMcpTokensPanel.tsx @@ -5,7 +5,7 @@ import { useFormatDate } from '../../hooks/useDateFormat' import ConfirmDialog from '../shared/ConfirmDialog' import { Tooltip } from '../shared/Tooltip' import { fs } from '../shared/DialogShell' -import { SETTINGS_ICON_BUTTON, SettingRows, SettingsCard, SettingsHint, StatusPill } from '../Settings/settingsKit' +import { SETTINGS_ICON_BUTTON, SettingRows, SettingsCard, SettingsHint, StatusPill, SettingsColumns } from '../Settings/settingsKit' import { SCOPES_PREVIEW, useMcpTokensAdmin } from './useMcpTokensAdmin' const ROW = 'flex flex-wrap items-center gap-x-4 gap-y-2 px-3.5 py-3' @@ -72,6 +72,9 @@ export default function AdminMcpTokensPanel() { return (
    + {/* The sessions and the tokens side by side: two lists of the same kind. */} + {/* OAuth Sessions. The tab's own subtitle sits in its band: the sidebar already names the tab, so a bare heading over the cards only repeated it. */} )} - + } + end={<> {/* MCP Tokens */} )} + } + /> {/* Revoke OAuth session */} setLinkPath(e.target.value)} spellCheck={false} placeholder={t('admin.plugins.devLinkPathPlaceholder')} className={`${INPUT} font-mono`} /> -
    @@ -223,7 +223,7 @@ export default function AdminPluginsPanel() { surface="var(--bg-secondary)" size={88} action={( - )} @@ -627,7 +627,7 @@ function EgressDialog({ data, draft, setDraft, saving, error, onSave, onClose, t className={`${INPUT} flex-1 font-mono`} />
    diff --git a/client/src/components/Admin/AuditLogPanel.tsx b/client/src/components/Admin/AuditLogPanel.tsx index fde48298c..f852f51dd 100644 --- a/client/src/components/Admin/AuditLogPanel.tsx +++ b/client/src/components/Admin/AuditLogPanel.tsx @@ -68,14 +68,14 @@ export default function AuditLogPanel({ serverTimezone }: AuditLogPanelProps): R icon={ClipboardList} title={t('admin.tabs.audit')} hint={t('admin.audit.subtitle')} - badge={{t('admin.audit.showing', { count: entries.length, total })}} + // The count only once there is one: never "0 of 0" while the first page loads. + badge={total > 0 ? {t('admin.audit.showing', { count: entries.length, total })} : undefined} action={ diff --git a/client/src/components/Admin/BackupPanel.tsx b/client/src/components/Admin/BackupPanel.tsx index 57a8533fc..fce3cf10e 100644 --- a/client/src/components/Admin/BackupPanel.tsx +++ b/client/src/components/Admin/BackupPanel.tsx @@ -56,7 +56,6 @@ export default function BackupPanel() { onClick={() => fileInputRef.current?.click()} disabled={isUploading} className={SETTINGS_BUTTON} - style={fs(12.5, 'body')} title={isUploading ? t('backup.uploading') : t('backup.upload')} > {isUploading @@ -69,7 +68,6 @@ export default function BackupPanel() { onClick={handleCreate} disabled={isCreating} className={SETTINGS_BUTTON_PRIMARY} - style={fs(12.5, 'body')} title={isCreating ? t('backup.creating') : t('backup.create')} > {isCreating @@ -97,7 +95,7 @@ export default function BackupPanel() { surface="var(--bg-secondary)" className="!py-6" action={ - @@ -295,7 +293,6 @@ export default function BackupPanel() { onClick={handleSaveAutoSettings} disabled={autoSettingsSaving || !autoSettingsDirty} className={SETTINGS_BUTTON_PRIMARY} - style={fs(13, 'body')} > {autoSettingsSaving ? diff --git a/client/src/components/Admin/CategoryManager.tsx b/client/src/components/Admin/CategoryManager.tsx index a4edae032..2913785f3 100644 --- a/client/src/components/Admin/CategoryManager.tsx +++ b/client/src/components/Admin/CategoryManager.tsx @@ -135,7 +135,7 @@ export default function CategoryManager() { hint={t('categories.subtitle')} badge={!isLoading && categories.length > 0 ? {categories.length} : undefined} action={ - diff --git a/client/src/components/Admin/DefaultUserSettingsTab.test.tsx b/client/src/components/Admin/DefaultUserSettingsTab.test.tsx index c8eb1ea0e..d2698cfad 100644 --- a/client/src/components/Admin/DefaultUserSettingsTab.test.tsx +++ b/client/src/components/Admin/DefaultUserSettingsTab.test.tsx @@ -395,10 +395,11 @@ describe('DefaultUserSettingsTab', () => { render(); await screen.findByText('3D buildings & terrain'); - // 3D defaults to on, quality mode to off when neither is stored - const threeD = within(screen.getByText('3D buildings & terrain').closest('div') as HTMLElement); + // 3D defaults to on, quality mode to off when neither is stored. The row + // (label left, control right) holds the On/Off pair. + const threeD = within(screen.getByText('3D buildings & terrain').closest('.flex-wrap') as HTMLElement); expect(isActive(threeD.getByRole('button', { name: 'On' }))).toBe(true); - const quality = within(screen.getByText('High-quality mode').closest('div') as HTMLElement); + const quality = within(screen.getByText('High-quality mode').closest('.flex-wrap') as HTMLElement); expect(isActive(quality.getByRole('button', { name: 'Off' }))).toBe(true); await user.click(threeD.getByRole('button', { name: 'Off' })); diff --git a/client/src/components/Admin/DefaultUserSettingsTab.tsx b/client/src/components/Admin/DefaultUserSettingsTab.tsx index abc4f6c76..a1bbcb060 100644 --- a/client/src/components/Admin/DefaultUserSettingsTab.tsx +++ b/client/src/components/Admin/DefaultUserSettingsTab.tsx @@ -1,8 +1,8 @@ import React from 'react' -import { Loader2, Map as MapIcon, Settings2 } from 'lucide-react' +import { Loader2, Map as MapIcon, Settings2, Route } from 'lucide-react' import { useTranslation } from '../../i18n' import Section from '../Settings/Section' -import { SettingRows, SettingsHint } from '../Settings/settingsKit' +import { SettingRow, SettingRows, SettingsColumns } from '../Settings/settingsKit' import { fs } from '../shared/DialogShell' import { EditorField, INPUT, Segmented } from '../shared/dialogParts' import CustomSelect from '../shared/CustomSelect' @@ -34,15 +34,8 @@ function ChoiceRow({ stacked?: boolean children: React.ReactNode }) { - return ( -
    - - {hint &&

    {hint}

    } -
    {children}
    -
    - ) + // The settings row every page uses, so a default reads like the setting it presets. + return } /** A wide field box inside the white rows, for the map card's token and style. */ @@ -114,23 +107,11 @@ export default function DefaultUserSettingsTab(): React.ReactElement { const darkMode = defaults.dark_mode return ( -
    - - {t('admin.defaultSettings.description')} - + - {/* Two columns from xl up, the same idea as the Settings tab: as one flat list - the map fields sat a screen below the units while the right half of the page - stayed empty. Grouped by subject rather than by height — what a user ends up - seeing on the left, everything that configures the map on the right. - The columns are deliberately uneven: the left one never needs more than the - widest option row, while the right one holds four text fields whose values - are 60-character tile URLs. Only the column gap is set, because Section - carries its own bottom margin and a row gap would double it once the grid - collapses. Two cards can sit straight in the grid; a third would need the - explicit per-column stacks the Settings tab uses, or it leaves a hole. */} -
    -
    +
    {/* Color Mode */} {t('settings.colorMode')} }> @@ -207,7 +188,7 @@ export default function DefaultUserSettingsTab(): React.ReactElement { {/* Default Currency */} - {t('settings.currency')} }> + {t('settings.currency')} } hint={t('settings.currencyHint')}>
    - {t('settings.currencyHint')}
    - + {/* Which engines answer routes, under the defaults: on its own card it keeps + the two columns about as long as each other. */} + {!managed && ( +
    + +
    + )} + + } + end={
    {/* Map Tile URL */} {t('settings.mapTemplate')}} hint={t('settings.mapDefaultHint')}> @@ -270,7 +259,6 @@ export default function DefaultUserSettingsTab(): React.ReactElement { /> )} - {!managed && }
    {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */} {React.createElement(MapView as any, { @@ -386,7 +374,7 @@ export default function DefaultUserSettingsTab(): React.ReactElement { )}
    -
    -
    + } + /> ) } diff --git a/client/src/components/Admin/GitHubPanel.tsx b/client/src/components/Admin/GitHubPanel.tsx index dda191525..6bd222ced 100644 --- a/client/src/components/Admin/GitHubPanel.tsx +++ b/client/src/components/Admin/GitHubPanel.tsx @@ -15,6 +15,7 @@ import { } from 'lucide-react'; import { type ComponentType, type CSSProperties, type ReactNode } from 'react'; import { useTranslation } from '../../i18n'; +import { withoutDonationsInApp } from '../../utils/donations'; import { escapeReleaseHtml as escapeHtml, parseReleaseNotes } from '../../utils/releaseNotes'; import { fs } from '../shared/DialogShell'; import { SETTINGS_BUTTON, SettingsCard, StatusPill } from '../Settings/settingsKit'; @@ -134,7 +135,7 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b }); }; - const supportLinks: SupportLink[] = [ + const supportLinks: SupportLink[] = withoutDonationsInApp([ { href: 'https://ko-fi.com/mauriceboe', brand: '#ff5e5b', // theme-lint-disable: Ko-fi brand colour @@ -177,7 +178,7 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b title: 'Wiki', hint: t('settings.about.wikiHint'), }, - ]; + ]); const subtitle = t('admin.github.subtitle').replace('{repo}', REPO); @@ -204,7 +205,6 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b target="_blank" rel="noopener noreferrer" className={`${SETTINGS_BUTTON} no-underline`} - style={fs(12.5, 'body')} > GitHub @@ -297,7 +297,6 @@ export default function GitHubPanel({ isPrerelease = false }: { isPrerelease?: b onClick={handleLoadMore} disabled={loadingMore} className={SETTINGS_BUTTON} - style={fs(12.5, 'body')} > {loadingMore ? : } {loadingMore ? t('admin.github.loading') : t('admin.github.loadMore')} diff --git a/client/src/components/Admin/GoogleDailyLimitRow.tsx b/client/src/components/Admin/GoogleDailyLimitRow.tsx index f398d291a..6ccb14611 100644 --- a/client/src/components/Admin/GoogleDailyLimitRow.tsx +++ b/client/src/components/Admin/GoogleDailyLimitRow.tsx @@ -1,44 +1,40 @@ -import { AlertTriangle, Check } from 'lucide-react' +import { Check } from 'lucide-react' import { useTranslation } from '../../i18n' import { NumericInput } from '../shared/NumericInput' import { fs } from '../shared/DialogShell' import { INPUT } from '../shared/dialogParts' -import { SETTINGS_BUTTON_PRIMARY, StatusPill } from '../Settings/settingsKit' +import { HintMark, SETTINGS_BUTTON_PRIMARY } from '../Settings/settingsKit' import { useGoogleQuota } from './useGoogleQuota' /** * The daily ceiling on Google calls (#1582), as one row of the Google options: - * today's count as a pill beside the name, the number on the right, a save + * today's count as a quiet line under the name, the number on the right, a save * button only while there is something to save. Laid out like settingsKit's - * SettingRow, but with the pill outside the
  • )} @@ -456,7 +472,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
    {fmt(f.amount)} - {canEdit && } + {canSettle && }
    ))} @@ -480,10 +496,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
    {t('costs.totalSpend')}
    {bigMoney(totals.totalSpend, 24, 'rgba(255,255,255,0.6)')}
    -
    + {splitting &&
    {t('costs.yourShare')} {fmt0(totals.myShare)} {t('costs.youPaid')} {fmt0(totals.myPaid)} -
    +
    } {canEdit && (
    - {/* Owe / Owed */} + {/* Owe / Owed, outstanding and settling up: only with something to split (#2689) */} + {splitting && <>
    @@ -536,11 +553,13 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
    {SettleFlows()}
    + } {/* Expenses */}
    -
    {t('costs.expenses')}
    +
    {t('costs.expenses')}
    +
    -
    + {splitting &&
    {(['all', 'mine', 'owed'] as const).map(f => ( ))} -
    +
    }
    setCatFilter(String(v))} options={categoryOptions} size="sm" style={{ flex: 1, minWidth: 0 }} /> setDayFilter(String(v))} options={dayOptions} size="sm" searchable style={{ flex: 1, minWidth: 0 }} /> @@ -578,23 +597,25 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps })}
    - {/* Balances */} + {/* Balances and the final budget */} + {splitting && <>
    {t('costs.balances')}
    {BalancesList({ balances: settlement?.balances || [] })}
    - {/* Final budget */}
    {t('costs.finalBudget')}
    {FinalBudgetList()}
    + } {/* By category */}
    {t('costs.byCategory')}
    - {CategoryBreakdown()} + {categoryBars}
    +
    ) } @@ -632,9 +653,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps const c = catMeta(e.category) const Icon = c.Icon 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) + // Payers, the split and what is still open say nothing with nothing to split (#2689). + const payers = splitting ? (e.payers || []).filter(p => p.amount !== 0) : [] + const net = splitting ? round2(myPaidOf(e) - myShareOf(e)) : 0 + const unfinished = splitting && isUnfinished(e) const note = readUserNote(e) // Fixed columns, identical on every row, so the eye can run down the list @@ -724,7 +746,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps ))} )} - {SplitChips({ e })} + {splitting && } + personName={personName} shareOf={shareOf} fmt={v => fmt(v)} />} {/* The note, marked by a rule in the category colour instead of a box, so @@ -748,39 +771,6 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps ) } - // Who an expense is split between and each one's part (#1763), so checking that - // the right people are in no longer means opening every expense. Quieter than - // the payer chips above, and capped so a large group cannot crowd the row. - function SplitChips({ e }: { e: BudgetItem }) { - const members = e.members || [] - if (members.length === 0) return null - const shown = members.length > SPLIT_CHIP_MAX ? members.slice(0, SPLIT_CHIP_MAX - 1) : members - const rest = members.slice(shown.length) - const chip = 'inline-flex items-center gap-[5px] rounded-full bg-surface-tertiary text-content-secondary' - return ( -
    - {t('costs.split')} - {shown.map(m => { - const share = fmt(shareOf(e, m.user_id)) - return ( - - - - {share} - {m.paid ? : null} - - - ) - })} - {rest.length > 0 && ( - t('costs.splitChipLabel', { name: personName(m.user_id), amount: fmt(shareOf(e, m.user_id)) })).join(', ')}> - +{rest.length} - - )} -
    - ) - } - // A row's note as a pill that opens in place; an empty one keeps the column. function NoteCell({ note, noteKey, color }: { note: string; noteKey: string; color: string }) { if (!note) return @@ -995,114 +985,6 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps ) } - - function CategoryBreakdown() { - // Categories net refunds against spend (#2176): a negative entry lowers its - // category's sum, and a category that nets negative keeps its own row, - // just without a bar, since the bars rank positive spend. Bars are scaled - // relative to the most expensive category (the top row fills the bar), not - // to the trip grand total, which makes the relative ranking readable. - if (catBreakdown.length === 0) return
    {t('costs.noCategories')}
    - return ( -
    - {catBreakdown.map(row => { - const c = COST_CAT_META[row.key] - const v = row.amount; const pct = row.widthPct - return ( -
    - - {t(c.labelKey)} - {fmt0(v)} -
    - -
    -
    - ) - })} -
    - ) - } -} - -// ── pure subcomponents ───────────────────────────────────────────────────── -// Add or edit a settle-up payment (from / to / amount / currency). Reachable inline -// from the ledger row and from a manual "Add payment" button, so recording "I sent -// money to X" works the same whether or not there's an outstanding expense behind it. -// 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, 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() - const { fromId, setFromId, toId, setToId, amount, setAmount, currency: cur, setCurrency: setCur, day, setDay, note, setNote, saving, valid, save } = - useSettlementForm({ tripId, tripCurrency, base: currency, people, me, editing, t, toast, onSaved }) - const opts = people.map(p => ({ value: String(p.id), label: p.id === me ? t('costs.you') : p.username })) - - const labelId = useId() - const nameOf = (id: number) => { - const p = people.find(x => x.id === id) - if (!p) return '' - return p.id === me ? t('costs.you') : p.username - } - - return ( - } - tint={NEUTRAL_TINT} - labelId={labelId} - onClose={onClose} - title={editing ? t('costs.editPayment') : t('costs.addPayment')} - sub={fromId !== toId ? `${nameOf(fromId)} → ${nameOf(toId)}` : undefined} - /> - )} - footer={( - - - {t('common.cancel')} - {editing ? t('common.save') : t('costs.addPayment')} - - )} - > -
    - - setFromId(Number(v))} options={opts} style={{ width: '100%' }} /> - - - setToId(Number(v))} options={opts} style={{ width: '100%' }} /> - -
    -
    - -
    - {SYMBOLS[cur] || (cur + ' ')} - {/* Typed and shown the way the expense total is, in the reader's own decimal mark. */} - setAmount(v.replace(',', '.'))} - className="w-full flex-1 border-0 bg-transparent ps-1.5 font-semibold text-content outline-none dark:bg-transparent" style={fs(14, 'body')} /> -
    -
    - - setCur(String(v))} searchable - options={currencyOptions(cur)} - style={{ width: '100%' }} /> - -
    - - - - - '; + for (const el of Array.from(document.body.children)) { + prepareField(el); + expect(el.hasAttribute('enterkeyhint')).toBe(false); + } + }); +}); + +describe('prepareKeyboardFields', () => { + it('prepares a field as it is focused, and stops when told to', () => { + const stop = prepareKeyboardFields(); + const a = field(''); + a.focus(); + expect(a.getAttribute('enterkeyhint')).toBe('done'); + stop(); + const b = field(''); + b.focus(); + expect(b.hasAttribute('enterkeyhint')).toBe(false); + }); +}); + +describe('closeOnDone', () => { + // Wired the way the app wires it: on the document, in the capture phase, + // ahead of every handler the field has of its own. + const enter = (el: HTMLElement) => + el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })); + let stop: () => void = () => {}; + afterEach(() => { + stop(); + vi.useRealTimers(); + }); + + it('closes the keyboard when nothing took the Enter of a "done" field', () => { + vi.useFakeTimers(); + stop = prepareKeyboardFields(document); + const el = field(''); + el.focus(); + enter(el); + vi.runAllTimers(); + expect(document.activeElement).not.toBe(el); + }); + + it('keeps the keyboard for a field that acted on the Enter and cleared itself', () => { + vi.useFakeTimers(); + stop = prepareKeyboardFields(document); + const el = field(''); + el.value = 'Socks'; + el.focus(); + el.addEventListener('keydown', () => { + el.value = ''; + }); + enter(el); + vi.runAllTimers(); + expect(document.activeElement).toBe(el); + }); + + it('leaves "go" and "search" fields and handled Enters alone', () => { + vi.useFakeTimers(); + stop = prepareKeyboardFields(document); + for (const hint of ['go', 'search']) { + const el = field(``); + el.focus(); + enter(el); + vi.runAllTimers(); + expect(document.activeElement).toBe(el); + } + const handled = field(''); + handled.focus(); + handled.addEventListener('keydown', (e) => e.preventDefault()); + enter(handled); + vi.runAllTimers(); + expect(document.activeElement).toBe(handled); + }); +}); diff --git a/client/src/native/keyboardFields.ts b/client/src/native/keyboardFields.ts new file mode 100644 index 000000000..c0d256d18 --- /dev/null +++ b/client/src/native/keyboardFields.ts @@ -0,0 +1,143 @@ +/** + * The keyboard a field gets in the app: what its return key says, and whether + * it capitalises and corrects what is typed. + * + * Left alone, every field in a web view gets the return key of a text editor + * and the autocorrect of a letter, so an email address starts with a capital, + * a booking code is "corrected" into a word, and Enter on a search field reads + * "return". Before a field is focused (on the touch that focuses it, or on the + * focus itself when code moves it there) this fills in what the field does not + * say for itself: + * + * - enterkeyhint: "go" in a form, which Enter submits, "done" anywhere else. + * Search fields say "search" in their own markup. + * - autocapitalize, autocorrect and spellcheck off for addresses, codes, + * numbers and names a machine reads (email, URL, password, tel, number; + * autocomplete such as username or one-time-code; a name or id such as + * "code", "token" or "host"). + * + * An attribute the field sets itself always wins, and textareas, which take + * Enter as a new line, keep the return key. Only the app calls this. + * + * The "done" key also has to close the keyboard: a web view only sends Enter, + * and a field outside a form has nothing listening for it, so the key did + * nothing. When no handler took the Enter (the field still has focus and the + * same text a moment later) the field lets go of the focus. A field that acts + * on Enter and clears itself, such as a list that adds the next item, keeps it. + */ + +const SKIP_TYPES = new Set([ + 'button', + 'checkbox', + 'color', + 'date', + 'datetime-local', + 'file', + 'hidden', + 'image', + 'month', + 'radio', + 'range', + 'reset', + 'submit', + 'time', + 'week', +]); +const MACHINE_TYPES = new Set(['email', 'url', 'password', 'tel', 'number']); +const MACHINE_MODES = new Set(['email', 'url', 'numeric', 'decimal', 'tel']); +const MACHINE_AUTOCOMPLETE = + /\b(username|email|url|one-time-code|current-password|new-password|tel|postal-code|cc-[a-z-]+)\b/; +const MACHINE_WORDS = new Set([ + 'code', + 'token', + 'key', + 'apikey', + 'secret', + 'host', + 'hostname', + 'url', + 'uri', + 'domain', + 'slug', + 'username', + 'email', + 'mail', + 'iban', + 'bic', + 'pin', + 'otp', + 'totp', + 'ref', + 'reference', + 'server', + 'port', + 'ip', +]); + +/** The words of an id or name: "bookingCode", "booking_code" and "booking-code" all give booking, code. */ +function words(...values: (string | null)[]): string[] { + return values + .filter((v): v is string => !!v) + .flatMap((v) => + v + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .toLowerCase() + .split(/[^a-z0-9]+/) + ) + .filter(Boolean); +} + +function readByMachine(el: HTMLInputElement): boolean { + if (MACHINE_TYPES.has(el.type)) return true; + if (MACHINE_MODES.has((el.getAttribute('inputmode') ?? '').toLowerCase())) return true; + if (MACHINE_AUTOCOMPLETE.test((el.getAttribute('autocomplete') ?? '').toLowerCase())) return true; + return words(el.name, el.id).some((w) => MACHINE_WORDS.has(w)); +} + +function setIfAbsent(el: Element, name: string, value: string) { + if (!el.hasAttribute(name)) el.setAttribute(name, value); +} + +export function prepareField(target: EventTarget | null): void { + if (!(target instanceof HTMLInputElement) || SKIP_TYPES.has(target.type) || target.readOnly) return; + const el = target; + const search = el.type === 'search' || el.getAttribute('role') === 'searchbox'; + setIfAbsent(el, 'enterkeyhint', search ? 'search' : el.form ? 'go' : 'done'); + if (search || readByMachine(el)) { + setIfAbsent(el, 'autocapitalize', 'none'); + setIfAbsent(el, 'autocorrect', 'off'); + setIfAbsent(el, 'spellcheck', 'false'); + } +} + +/** + * Enter on a "done" field that nothing acted on closes the keyboard. Listens in + * the capture phase, so the field's text is read before any handler of the field + * runs; whether one took the Enter is read off the event once it has gone round. + */ +function closeOnDone(e: KeyboardEvent): void { + const el = e.target; + if (e.key !== 'Enter' || e.isComposing) return; + if (!(el instanceof HTMLInputElement) || el.getAttribute('enterkeyhint') !== 'done') return; + const before = el.value; + // After every handler of this Enter, including ones React schedules. + setTimeout(() => { + if (e.defaultPrevented) return; + if (el.ownerDocument.activeElement === el && el.value === before) el.blur(); + }, 0); +} + +export function prepareKeyboardFields(doc: Document = document): () => void { + // On the touch, before the focus: the keyboard is set up as the field takes it. + const onTouch = (e: Event) => prepareField(e.target instanceof Element ? e.target.closest('input') : null); + const onFocus = (e: FocusEvent) => prepareField(e.target); + doc.addEventListener('touchstart', onTouch, { capture: true, passive: true }); + doc.addEventListener('focusin', onFocus, true); + // Capturing, so the text is read before the field's own handler can change it. + doc.addEventListener('keydown', closeOnDone, true); + return () => { + doc.removeEventListener('touchstart', onTouch, { capture: true }); + doc.removeEventListener('focusin', onFocus, true); + doc.removeEventListener('keydown', closeOnDone, true); + }; +} diff --git a/client/src/native/links.ts b/client/src/native/links.ts new file mode 100644 index 000000000..8838351e5 --- /dev/null +++ b/client/src/native/links.ts @@ -0,0 +1,31 @@ +/** + * Pages the apps link to outside the user's server. They open in the system + * browser: the WebView hands every navigation off the server's own origin to it. + */ + +/** The privacy policy the store listings name too. */ +export const PRIVACY_URL = 'https://liketrek.com/privacy?app=1'; + +/** Running the app with a sign-in proxy (Cloudflare Access, Pangolin and the like) in front of TREK. */ +export const AUTH_PROXY_DOCS_URL = 'https://github.com/liketrek/TREK/wiki/Native-Apps#behind-a-sign-in-proxy'; + +/** Adding a client certificate for a server behind mutual TLS (Cloudflare, nginx, Caddy, Traefik). */ +export const CLIENT_CERT_DOCS_URL = 'https://github.com/liketrek/TREK/wiki/Native-Apps#client-certificates-mtls'; + +/** The public demo the address screen offers to someone without a server. */ +export const DEMO_SERVER_URL = 'https://demo.liketrek.com'; + +/** TREK Cloud, for someone who wants a hosted TREK rather than running their own. */ +export const CLOUD_URL = 'https://liketrek.com'; + +/** + * The terms an in-app subscription is sold under: Apple's standard licence + * agreement, which the App Store applies when an app names no own EULA. The + * store rules ask for it next to the purchase, together with the privacy policy. + */ +export const STORE_TERMS_URL = 'https://www.apple.com/legal/internet-services/itunes/dev/stdeula/'; +/** Where the App Store and Google Play let someone manage or end a subscription. */ +export const APP_STORE_SUBSCRIPTIONS_URL = 'https://apps.apple.com/account/subscriptions'; +export const PLAY_SUBSCRIPTIONS_URL = 'https://play.google.com/store/account/subscriptions?package=com.liketrek.trek'; +/** Our terms for TREK Cloud (§ 5a covers a purchase in the app), as the app opens them: without the site's sales header. */ +export const CLOUD_TERMS_URL = 'https://liketrek.com/terms?app=1'; diff --git a/client/src/native/nativeApp.css b/client/src/native/nativeApp.css new file mode 100644 index 000000000..750655104 --- /dev/null +++ b/client/src/native/nativeApp.css @@ -0,0 +1,83 @@ +/* + * What the UI does differently inside the iOS and Android app, keyed on the + * attributes native/nativeApp.ts puts on there (data-native-app, and + * data-touch-input while a finger drives it). A browser never has them, so + * none of this reaches it. Loaded after index.css (main.tsx). + */ + +/* Inside the iOS and Android app (native/nativeApp.ts sets the attribute): a long + press on a label, card or image does nothing, as in a native app, instead of + starting a text selection, a magnifier or a "save image" callout. What the user + types into stays selectable, or editing, pasting and moving the caret would break; + text worth copying opts in with .trek-selectable. A browser keeps its default. */ +html[data-native-app] body { + -webkit-user-select: none; + user-select: none; + -webkit-touch-callout: none; +} +html[data-native-app] :is(input, textarea, select, [contenteditable]:not([contenteditable='false']), .trek-selectable), +html[data-native-app] :is([contenteditable]:not([contenteditable='false']), .trek-selectable) * { + -webkit-user-select: text; + user-select: text; + -webkit-touch-callout: default; +} +html[data-native-app] img { + -webkit-user-drag: none; +} + +/* A picture still loading waits unseen and fades in once it is there + (native/imageFade.ts). An animation rather than a transition, so an image's + own transitions (a hover zoom, a crossfade) stay as they are. */ +html[data-native-app] img[data-fading] { + opacity: 0; +} +@keyframes trek-image-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} +@media (prefers-reduced-motion: no-preference) { + html[data-native-app]:not([data-reduce-motion]) img[data-faded] { + animation: trek-image-in 0.24s ease-out; + } +} + +/* The press a native button shows the moment a finger lands on it. Most of the + UI says nothing until the finger lifts, which reads as lag. Only what has no + press of its own (no active: class), only the innermost pressed control, not + the card around a pressed button, and after a 60 ms wait, so a finger that + lands on a row to scroll the list does not flash it. Draggable rows show + their own pick-up; data-no-press opts a control out. */ +html[data-native-app] + :is(button, a[href], [role='button'], [role='tab'], [role='menuitem'], [role='option'], summary):not(:disabled):not( + [aria-disabled='true'] + ):not([class*='active:']):not([draggable='true']):not([data-no-press]):not([data-pressing]):not( + :has(:is(button, a[href], [role='button']):active) + ):active { + opacity: 0.55; + transition: opacity 0s linear 60ms; +} + +/* A card held for its menu lifts a little under the finger + (mobile/components/useLongPress.ts), as a native context menu does. */ +html[data-native-app] [data-long-press] { + transition: transform 0.3s cubic-bezier(0.32, 0.72, 0, 1); +} +html[data-native-app] [data-long-press][data-pressing] { + transform: scale(0.97); +} + +/* A tap focuses a button on Android, and a focus: ring (rather than + focus-visible:) then stays round it, which no native control shows. Focus + from a hardware keyboard is focus-visible and keeps its ring. */ +html[data-touch-input] + :is(button, a, [role='button'], [role='tab'], [role='menuitem'], [role='option'], [tabindex]):focus:not( + :focus-visible + ) { + outline: none; + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; +} diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts new file mode 100644 index 000000000..870c5fc0b --- /dev/null +++ b/client/src/native/nativeApp.test.ts @@ -0,0 +1,237 @@ +import { App } from '@capacitor/app'; +import { Keyboard } from '@capacitor/keyboard'; +import { SplashScreen } from '@capacitor/splash-screen'; +import { StatusBar, Style } from '@capacitor/status-bar'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { closeTopOverlay } from '../mobile/overlayStack'; +import { isEffectivelyOffline } from '../sync/networkMode'; +import { checkAppUpdate, hasNativeFeature } from './capabilities'; +import { installNativeGeolocation } from './geolocation'; +import { prepareKeyboardFields } from './keyboardFields'; +import { scrollToTop, startNativeApp } from './nativeApp'; +import { keepOfflineShellFresh } from './offlineShell'; +import { isNativeAndroid, isNativeApp, isNativeIos } from './platform'; +import { openPushTarget } from './push'; +import { trackTouchInput } from './touchInput'; + +vi.mock('@capacitor/app', () => ({ + App: { addListener: vi.fn(), minimizeApp: vi.fn(), getLaunchUrl: vi.fn(async () => undefined) }, +})); +vi.mock('@capacitor/keyboard', () => ({ + Keyboard: { setAccessoryBarVisible: vi.fn(), addListener: vi.fn(async () => ({ remove: vi.fn() })) }, +})); +vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn() } })); +vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Style: { Dark: 'DARK', Light: 'LIGHT' } })); +vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn(), isNativeAndroid: vi.fn() })); +vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() })); +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() })); +vi.mock('./capabilities', () => ({ + checkAppUpdate: vi.fn(async () => false), + loadNativeCapabilities: vi.fn(async () => ({})), + hasNativeFeature: vi.fn(() => false), +})); +vi.mock('./geolocation', () => ({ installNativeGeolocation: vi.fn() })); +vi.mock('./sharedFiles', () => ({ startSharedFiles: vi.fn(async () => {}) })); +vi.mock('./push', () => ({ startNativePush: vi.fn(async () => {}), openPushTarget: vi.fn() })); +vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) })); +vi.mock('./touchInput', () => ({ trackTouchInput: vi.fn() })); +vi.mock('./quickActions', () => ({ startQuickActions: vi.fn() })); +vi.mock('./imageFade', () => ({ fadeInImages: vi.fn() })); +vi.mock('./keyboardFields', () => ({ prepareKeyboardFields: vi.fn() })); + +function backButtonHandler(): (event: { canGoBack: boolean }) => void { + const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton'); + if (!call) throw new Error('no backButton listener'); + return call[1] as unknown as (event: { canGoBack: boolean }) => void; +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.clearAllMocks(); + vi.mocked(isNativeApp).mockReturnValue(true); + vi.mocked(isNativeIos).mockReturnValue(false); + vi.mocked(isNativeAndroid).mockReturnValue(false); + vi.mocked(isEffectivelyOffline).mockReturnValue(false); + vi.mocked(keepOfflineShellFresh).mockResolvedValue(); + vi.mocked(hasNativeFeature).mockReturnValue(false); + document.documentElement.classList.remove('dark'); + document.documentElement.removeAttribute('data-native-app'); + document.documentElement.removeAttribute('data-native-ios'); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('startNativeApp', () => { + it('does nothing in a browser', () => { + vi.mocked(isNativeApp).mockReturnValue(false); + startNativeApp(); + expect(App.addListener).not.toHaveBeenCalled(); + expect(StatusBar.setStyle).not.toHaveBeenCalled(); + expect(document.documentElement.hasAttribute('data-native-app')).toBe(false); + expect(trackTouchInput).not.toHaveBeenCalled(); + expect(prepareKeyboardFields).not.toHaveBeenCalled(); + }); + + it('marks so a long press selects no text in the app', () => { + startNativeApp(); + expect(document.documentElement.hasAttribute('data-native-app')).toBe(true); + }); + + it('follows finger or pointer for hover, press and focus, and fits the keyboard to each field', () => { + startNativeApp(); + expect(trackTouchInput).toHaveBeenCalledTimes(1); + expect(prepareKeyboardFields).toHaveBeenCalledTimes(1); + }); + + it("Android's back gesture closes an open sheet before it leaves the page", () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + vi.mocked(closeTopOverlay).mockReturnValueOnce(true); + startNativeApp(); + backButtonHandler()({ canGoBack: true }); + expect(back).not.toHaveBeenCalled(); + backButtonHandler()({ canGoBack: true }); + expect(back).toHaveBeenCalledTimes(1); + back.mockRestore(); + }); + + it('puts the app location under navigator.geolocation once the binary has answered', async () => { + vi.useRealTimers(); + startNativeApp(); + await vi.waitFor(() => expect(installNativeGeolocation).toHaveBeenCalled()); + }); + + it('a status bar tap scrolls the list in the middle of the screen back to the top', () => { + const list = document.createElement('div'); + list.style.overflowY = 'auto'; + Object.defineProperty(list, 'scrollTop', { configurable: true, value: 300 }); + list.scrollTo = vi.fn(); + document.body.appendChild(list); + document.elementFromPoint = vi.fn(() => list); + scrollToTop(); + expect(list.scrollTo).toHaveBeenCalledWith({ top: 0, behavior: 'smooth' }); + list.remove(); + }); + + it('asks the binary what it can do and the server which binary it needs', () => { + startNativeApp(); + expect(checkAppUpdate).toHaveBeenCalledWith(expect.any(Function)); + }); + + it('hides the splash after the first frame', () => { + startNativeApp(); + vi.runOnlyPendingTimers(); + expect(SplashScreen.hide).toHaveBeenCalled(); + }); + + it('walks back through history before it leaves the app', () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + startNativeApp(); + backButtonHandler()({ canGoBack: true }); + expect(back).toHaveBeenCalled(); + backButtonHandler()({ canGoBack: false }); + expect(App.minimizeApp).toHaveBeenCalled(); + }); + + it('keeps the status bar icons readable when the scheme changes', async () => { + startNativeApp(); + expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Light }); + document.documentElement.classList.add('dark'); + await vi.waitFor(() => expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Dark })); + }); + + it('hides the keyboard accessory bar on iOS only', () => { + startNativeApp(); + expect(Keyboard.setAccessoryBarVisible).not.toHaveBeenCalled(); + vi.mocked(isNativeIos).mockReturnValue(true); + startNativeApp(); + expect(Keyboard.setAccessoryBarVisible).toHaveBeenCalledWith({ isVisible: false }); + }); + + it('refreshes the offline start on iOS once the first screen has settled', () => { + vi.mocked(isNativeIos).mockReturnValue(true); + startNativeApp(); + expect(keepOfflineShellFresh).not.toHaveBeenCalled(); + vi.advanceTimersByTime(15_000); + expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toBe(false); + }); + + it('refreshes it on Android too, into the store of the app', () => { + vi.mocked(isNativeAndroid).mockReturnValue(true); + startNativeApp(); + vi.advanceTimersByTime(15_000); + expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toBe(true); + }); + + it('skips the refresh while offline', () => { + vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(isEffectivelyOffline).mockReturnValue(true); + startNativeApp(); + vi.advanceTimersByTime(15_000); + expect(keepOfflineShellFresh).not.toHaveBeenCalled(); + }); + + it('logs a failed refresh instead of throwing', async () => { + vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(keepOfflineShellFresh).mockRejectedValue(new Error('down')); + const report = vi.fn(); + vi.stubGlobal('reportError', report); + startNativeApp(); + vi.advanceTimersByTime(15_000); + await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error))); + vi.unstubAllGlobals(); + }); + + it('stays quiet when the installed app is older than the offline copy', async () => { + vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(keepOfflineShellFresh).mockRejectedValue( + Object.assign(new Error('not implemented'), { code: 'UNIMPLEMENTED' }) + ); + const report = vi.fn(); + vi.stubGlobal('reportError', report); + startNativeApp(); + vi.advanceTimersByTime(15_000); + await vi.waitFor(() => expect(keepOfflineShellFresh).toHaveBeenCalled()); + // Let the rejection reach its handler. + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + expect(report).not.toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); + + it('follows the link a widget tap launched the app with, once per launch', async () => { + sessionStorage.clear(); + vi.mocked(App.getLaunchUrl).mockResolvedValue({ url: 'com.liketrek.trek://navigate/trips/5?tab=listen' }); + startNativeApp(); + await vi.waitFor(() => expect(openPushTarget).toHaveBeenCalledWith('/trips/5?tab=listen')); + // A reload of the page in the same launch does not follow it again. + vi.mocked(openPushTarget).mockClear(); + startNativeApp(); + await Promise.resolve(); + await Promise.resolve(); + expect(openPushTarget).not.toHaveBeenCalled(); + }); + + it('leaves widget links to the binary when it hands them over as quick actions', async () => { + sessionStorage.clear(); + vi.mocked(hasNativeFeature).mockImplementation((feature) => feature === 'appLinks'); + vi.mocked(App.getLaunchUrl).mockResolvedValue({ url: 'com.liketrek.trek://navigate/trips/5?tab=listen' }); + startNativeApp(); + await vi.waitFor(() => expect(hasNativeFeature).toHaveBeenCalledWith('appLinks')); + await Promise.resolve(); + expect(App.getLaunchUrl).not.toHaveBeenCalled(); + expect(vi.mocked(App.addListener).mock.calls.map(([name]) => String(name))).not.toContain('appUrlOpen'); + expect(openPushTarget).not.toHaveBeenCalled(); + }); + + it('leaves the start page alone for a launch without a TREK link', async () => { + sessionStorage.clear(); + vi.mocked(App.getLaunchUrl).mockResolvedValue({ url: 'https://example.com/elsewhere' }); + startNativeApp(); + await Promise.resolve(); + await Promise.resolve(); + expect(openPushTarget).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts new file mode 100644 index 000000000..27a831bb6 --- /dev/null +++ b/client/src/native/nativeApp.ts @@ -0,0 +1,163 @@ +import { App } from '@capacitor/app'; +import { Keyboard } from '@capacitor/keyboard'; +import { SplashScreen } from '@capacitor/splash-screen'; +import { StatusBar, Style } from '@capacitor/status-bar'; +import { closeTopOverlay } from '../mobile/overlayStack'; +import { useSettingsStore } from '../store/settingsStore'; +import { isEffectivelyOffline } from '../sync/networkMode'; +import { checkAppUpdate, hasNativeFeature, loadNativeCapabilities } from './capabilities'; +import { installNativeGeolocation } from './geolocation'; +import { fadeInImages } from './imageFade'; +import { keepFieldInView } from './keepFieldInView'; +import { prepareKeyboardFields } from './keyboardFields'; +import { keepOfflineShellFresh } from './offlineShell'; +import { isNativeAndroid, isNativeApp, isNativeIos } from './platform'; +import { openPushTarget, startNativePush } from './push'; +import { startQuickActions } from './quickActions'; +import { reportNativeFailure } from './reportFailure'; +import { startSharedFiles } from './sharedFiles'; +import { trackTouchInput } from './touchInput'; +import { APP_URL_SCHEME, isUnimplemented } from './trekShell'; + +/** Long enough that the warm-up never competes with the first screen's requests. */ +const OFFLINE_SHELL_DELAY_MS = 15_000; + +/** + * What the UI does differently when it runs inside the iOS or Android app. + * Everything else is the same UI a browser gets from this server. + */ +export function startNativeApp(): void { + if (!isNativeApp()) return; + + // Marks the app for index.css: no text selection or long-press callout on the + // UI itself, as in any native app. Fields stay selectable there. + document.documentElement.setAttribute('data-native-app', ''); + // iOS only: the page may bounce at its ends there (mobile.css). + if (isNativeIos()) document.documentElement.setAttribute('data-native-ios', ''); + // No hover left behind by a tap, a press that shows, no focus ring after a tap. + trackTouchInput(); + // The keyboard's return key, capitalisation and autocorrect fit the field. + prepareKeyboardFields(); + // Pictures fade in once loaded instead of building up. + fadeInImages(); + + followThemeInStatusBar(); + + // What this binary can do, and whether this server's UI needs a newer one. + void checkAppUpdate(fetchServerFeatures); + // The app's own location under navigator.geolocation, where the binary has it. + void loadNativeCapabilities().then(() => installNativeGeolocation()); + // Booking documents shared to TREK, waiting for a trip to import into. + void startSharedFiles(); + // Taps on TREK notifications open the place they point at. + void loadNativeCapabilities().then(() => startNativePush()); + // A quick action on the app icon opens its page, also the one the app was launched with. + void loadNativeCapabilities().then(() => startQuickActions()); + + // A widget or Live Activity tap opens com.liketrek.trek://navigate/. A + // binary with the feature appLinks hands it over as a quick action instead, + // held until taken, so it is only followed here for older binaries. + void loadNativeCapabilities().then(() => { + if (hasNativeFeature('appLinks')) return; + void App.addListener('appUrlOpen', ({ url }) => { + const prefix = `${APP_URL_SCHEME}://navigate`; + if (url.startsWith(prefix)) openPushTarget(url.slice(prefix.length) || '/'); + }); + // A tap that launched the app comes as the launch URL, not as appUrlOpen. + void openLaunchLink(); + }); + + // A tap on the status bar scrolls the list under it back to the top, as in + // every iOS app (the status-bar plugin fires statusTap on iOS). + window.addEventListener('statusTap', scrollToTop); + + // Android's back gesture: through the app's own history first, and only + // then out of the app, the way a browser tab would behave. + void App.addListener('backButton', ({ canGoBack }) => { + // An open sheet closes first, as on iOS's edge swipe. + if (closeTopOverlay()) return; + if (canGoBack) window.history.back(); + else void App.minimizeApp(); + }); + + requestAnimationFrame(() => { + void SplashScreen.hide(); + }); + + if (isNativeIos()) { + // The "‹ › Done" strip above the keyboard is a web form's, not an app's. + void Keyboard.setAccessoryBarVisible({ isVisible: false }); + keepFieldInView(Keyboard); + } + + // The copy of the UI the app starts from without its server (offlineShell.ts): + // iOS in WebKit's cache, Android in the app's own store. + window.setTimeout(() => { + if (isEffectivelyOffline()) return; + // Not refreshed this time is no harm: the next launch tries again. An app + // older than the offline copy has no such method, which is no failure. + keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language, isNativeAndroid()).catch( + (err: unknown) => { + if (!isUnimplemented(err)) reportNativeFailure(err); + } + ); + }, OFFLINE_SHELL_DELAY_MS); +} + +/** + * Light icons on the dark scheme and dark icons on the light one. Observing + * the class keeps applyAppearance() the only writer of , and it catches + * every way the scheme changes, including "follow the system". + */ +function followThemeInStatusBar(): void { + const root = document.documentElement; + const apply = (): void => { + void StatusBar.setStyle({ style: root.classList.contains('dark') ? Style.Dark : Style.Light }); + }; + apply(); + new MutationObserver(apply).observe(root, { attributes: true, attributeFilter: ['class'] }); +} + +/** The server's feature flags, bounded so a slow server cannot hold anything up. */ +async function fetchServerFeatures(): Promise<{ minNativeShellApi?: unknown }> { + const res = await fetch('/api/health/features', { credentials: 'same-origin', signal: AbortSignal.timeout(8000) }); + if (!res.ok) return {}; + return (await res.json()) as { minNativeShellApi?: unknown }; +} + +/** The launch link this web view has already followed, so a reload does not follow it again. */ +const LAUNCH_LINK_KEY = 'trek_launch_link_done'; + +/** + * A widget or Live Activity tap that starts the app from closed hands it + * com.liketrek.trek://navigate/ as the launch URL. appUrlOpen only fires + * for a running app, so the path was lost and the app opened its start page + * (a packing widget landed on the trip's plan, not its lists). Followed once + * per launch; the trip planner takes a ?tab= on a trip it already shows. + */ +async function openLaunchLink(): Promise { + const prefix = `${APP_URL_SCHEME}://navigate`; + try { + const url = (await App.getLaunchUrl())?.url; + if (!url || !url.startsWith(prefix)) return; + if (sessionStorage.getItem(LAUNCH_LINK_KEY) === url) return; + sessionStorage.setItem(LAUNCH_LINK_KEY, url); + openPushTarget(url.slice(prefix.length) || '/'); + } catch { + /* no launch URL here (an older app binary, or storage blocked): the start page stays */ + } +} + +/** The scrolled list in the middle of the screen, else the page, back to its top. */ +export function scrollToTop(): void { + let el = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2) as HTMLElement | null; + while (el && el !== document.body) { + const overflow = getComputedStyle(el).overflowY; + if ((overflow === 'auto' || overflow === 'scroll') && el.scrollTop > 0) { + el.scrollTo({ top: 0, behavior: 'smooth' }); + return; + } + el = el.parentElement; + } + window.scrollTo({ top: 0, behavior: 'smooth' }); +} diff --git a/client/src/native/nativeDialogs.test.ts b/client/src/native/nativeDialogs.test.ts new file mode 100644 index 000000000..bfc7ed881 --- /dev/null +++ b/client/src/native/nativeDialogs.test.ts @@ -0,0 +1,68 @@ +import { ActionSheet } from '@capacitor/action-sheet'; +import { Capacitor } from '@capacitor/core'; +import { Dialog } from '@capacitor/dialog'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { askNatively, canAskNatively } from './nativeDialogs'; +import { isNativeApp } from './platform'; + +vi.mock('@capacitor/action-sheet', () => ({ + ActionSheet: { showActions: vi.fn() }, + ActionSheetButtonStyle: { Default: 'DEFAULT', Destructive: 'DESTRUCTIVE', Cancel: 'CANCEL' }, +})); +vi.mock('@capacitor/dialog', () => ({ Dialog: { confirm: vi.fn() } })); +vi.mock('@capacitor/core', () => ({ Capacitor: { isPluginAvailable: vi.fn() } })); +vi.mock('./platform', () => ({ isNativeApp: vi.fn() })); +vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() })); + +const question = { title: 'Delete place?', message: 'Gone for good.', confirmLabel: 'Delete', cancelLabel: 'Cancel' }; + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(isNativeApp).mockReturnValue(true); + vi.mocked(Capacitor.isPluginAvailable).mockReturnValue(true); +}); + +describe('canAskNatively', () => { + it('needs the app and both plugins in its binary', () => { + expect(canAskNatively()).toBe(true); + vi.mocked(Capacitor.isPluginAvailable).mockImplementation((name) => name !== 'Dialog'); + expect(canAskNatively()).toBe(false); + vi.mocked(isNativeApp).mockReturnValue(false); + expect(canAskNatively()).toBe(false); + }); +}); + +describe('askNatively', () => { + it('asks a destroying question on a sheet with the action in red, yes only for that action', async () => { + vi.mocked(ActionSheet.showActions).mockResolvedValue({ index: 0, canceled: false }); + expect(await askNatively({ ...question, danger: true })).toBe(true); + expect(ActionSheet.showActions).toHaveBeenCalledWith({ + title: 'Delete place?', + message: 'Gone for good.', + options: [ + { title: 'Delete', style: 'DESTRUCTIVE' }, + { title: 'Cancel', style: 'CANCEL' }, + ], + }); + vi.mocked(ActionSheet.showActions).mockResolvedValue({ index: 1, canceled: false }); + expect(await askNatively({ ...question, danger: true })).toBe(false); + vi.mocked(ActionSheet.showActions).mockResolvedValue({ index: -1, canceled: true }); + expect(await askNatively({ ...question, danger: true })).toBe(false); + }); + + it('asks any other question in an alert', async () => { + vi.mocked(Dialog.confirm).mockResolvedValue({ value: true }); + expect(await askNatively({ ...question, danger: false })).toBe(true); + expect(Dialog.confirm).toHaveBeenCalledWith({ + title: 'Delete place?', + message: 'Gone for good.', + okButtonTitle: 'Delete', + cancelButtonTitle: 'Cancel', + }); + }); + + it('answers null when the system cannot ask, so the HTML dialog takes over', async () => { + vi.mocked(ActionSheet.showActions).mockRejectedValue(new Error('not implemented')); + expect(await askNatively({ ...question, danger: true })).toBeNull(); + }); +}); diff --git a/client/src/native/nativeDialogs.ts b/client/src/native/nativeDialogs.ts new file mode 100644 index 000000000..92ff7960c --- /dev/null +++ b/client/src/native/nativeDialogs.ts @@ -0,0 +1,62 @@ +import { ActionSheet, ActionSheetButtonStyle } from '@capacitor/action-sheet'; +import { Capacitor } from '@capacitor/core'; +import { Dialog } from '@capacitor/dialog'; +import { isNativeApp } from './platform'; +import { reportNativeFailure } from './reportFailure'; + +/** + * A yes-or-no question asked the way the phone asks it. + * + * Asked in HTML, "Delete this place?" is a card drawn by the page, and it + * looks like one. In the app it goes to the system instead: an action sheet + * with the action in red when it destroys something, an alert when it does + * not. That is what iOS and Android show in their own apps for the same + * question, with the system's own animation, sound and accessibility. + * + * Only where the binary carries both plugins: an app from before them keeps + * the HTML dialog, as does a browser. + */ + +export interface NativeQuestion { + title: string; + message?: string; + confirmLabel: string; + cancelLabel: string; + /** Destroys or throws something away: the action shows in red, on a sheet. */ + danger: boolean; +} + +export function canAskNatively(): boolean { + return isNativeApp() && Capacitor.isPluginAvailable('ActionSheet') && Capacitor.isPluginAvailable('Dialog'); +} + +/** + * True when the user chose the action, false when they did not. Null when the + * system could not ask: the caller then shows its HTML dialog, so a question + * is never lost and nothing is done that was not confirmed. + */ +export async function askNatively(q: NativeQuestion): Promise { + try { + if (q.danger) { + const { index } = await ActionSheet.showActions({ + title: q.title, + message: q.message, + options: [ + { title: q.confirmLabel, style: ActionSheetButtonStyle.Destructive }, + { title: q.cancelLabel, style: ActionSheetButtonStyle.Cancel }, + ], + }); + return index === 0; + } + const { value } = await Dialog.confirm({ + title: q.title, + message: q.message ?? '', + okButtonTitle: q.confirmLabel, + cancelButtonTitle: q.cancelLabel, + }); + return value; + } catch (err) { + reportNativeFailure(err); + return null; + } +} diff --git a/client/src/native/nativeFiles.test.ts b/client/src/native/nativeFiles.test.ts new file mode 100644 index 000000000..8e58305d2 --- /dev/null +++ b/client/src/native/nativeFiles.test.ts @@ -0,0 +1,91 @@ +import { Directory, Filesystem } from '@capacitor/filesystem'; +import { Share } from '@capacitor/share'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { hasNativeFeature } from './capabilities'; +import { cacheFileName, fileNameFromUrl, openNativeFile, shareFile } from './nativeFiles'; +import { TrekShell } from './trekShell'; + +vi.mock('@capacitor/filesystem', () => ({ Directory: { Cache: 'CACHE' }, Filesystem: { writeFile: vi.fn() } })); +vi.mock('@capacitor/share', () => ({ Share: { share: vi.fn() } })); +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() })); +vi.mock('./trekShell', () => ({ TrekShell: { previewFile: vi.fn() } })); + +beforeEach(() => { + vi.mocked(Filesystem.writeFile).mockReset().mockResolvedValue({ uri: 'file:///cache/trip.pdf' }); + vi.mocked(Share.share).mockReset().mockResolvedValue({}); + vi.mocked(TrekShell.previewFile).mockReset(); +}); + +describe('cacheFileName', () => { + it('keeps a readable name but nothing that could leave the cache directory', () => { + expect(cacheFileName('Lisbon 2026.pdf')).toBe('Lisbon 2026.pdf'); + expect(cacheFileName('../../etc/passwd')).toBe('_.._etc_passwd'); + expect(cacheFileName('a:b*c?"d"|f\u0001.txt')).toBe('a_b_c__d__e__f_.txt'); + expect(cacheFileName('...hidden')).toBe('hidden'); + expect(cacheFileName(' ')).toBe('download'); + }); +}); + +describe('fileNameFromUrl', () => { + it('takes the decoded last path segment', () => { + expect(fileNameFromUrl('/api/trips/1/files/42/Boarding%20pass.pdf?token=x')).toBe('Boarding pass.pdf'); + expect(fileNameFromUrl('/uploads/files/')).toBe('files'); + expect(fileNameFromUrl('/bad/%E0%A4%A')).toBe('%E0%A4%A'); + }); +}); + +describe('shareFile', () => { + it('writes the blob to the cache and hands it to the share sheet', async () => { + await shareFile(new Blob(['hello'], { type: 'text/plain' }), 'note.txt'); + + expect(Filesystem.writeFile).toHaveBeenCalledWith({ + path: 'note.txt', + data: btoa('hello'), + directory: Directory.Cache, + }); + expect(Share.share).toHaveBeenCalledWith({ files: ['file:///cache/trip.pdf'] }); + }); + + it('treats a dismissed sheet as the user changing their mind', async () => { + vi.mocked(Share.share).mockRejectedValue(new Error('Share canceled')); + await expect(shareFile(new Blob(['x']), 'x.txt')).resolves.toBeUndefined(); + }); + + it('passes a real failure on', async () => { + vi.mocked(Share.share).mockRejectedValue(new Error('No activity found')); + await expect(shareFile(new Blob(['x']), 'x.txt')).rejects.toThrow('No activity found'); + }); +}); + +describe('openNativeFile', () => { + const pdf = () => new Blob(['%PDF'], { type: 'application/pdf' }); + + it('FE-NATIVE-FILES-OPEN-001: shows the file in the system viewer where the app has one, not in the share sheet', async () => { + vi.mocked(hasNativeFeature).mockReturnValue(true); + vi.mocked(TrekShell.previewFile).mockResolvedValue({ result: 'shown' }); + + await openNativeFile(pdf(), 'trip.pdf'); + + expect(TrekShell.previewFile).toHaveBeenCalledWith({ + path: 'file:///cache/trip.pdf', + mimeType: 'application/pdf', + title: 'trip.pdf', + }); + expect(Share.share).not.toHaveBeenCalled(); + }); + + it('FE-NATIVE-FILES-OPEN-002: falls back to the share sheet for an older app, a type nothing shows, or a viewer that fails', async () => { + vi.mocked(hasNativeFeature).mockReturnValue(false); + await openNativeFile(pdf(), 'trip.pdf'); + expect(TrekShell.previewFile).not.toHaveBeenCalled(); + + vi.mocked(hasNativeFeature).mockReturnValue(true); + vi.mocked(TrekShell.previewFile).mockResolvedValueOnce({ result: 'unsupported' }); + await openNativeFile(pdf(), 'trip.pdf'); + vi.mocked(TrekShell.previewFile).mockRejectedValueOnce(new Error('no window')); + await openNativeFile(pdf(), 'trip.pdf'); + + expect(Share.share).toHaveBeenCalledTimes(3); + expect(Share.share).toHaveBeenCalledWith({ files: ['file:///cache/trip.pdf'] }); + }); +}); diff --git a/client/src/native/nativeFiles.ts b/client/src/native/nativeFiles.ts new file mode 100644 index 000000000..7cddbe65a --- /dev/null +++ b/client/src/native/nativeFiles.ts @@ -0,0 +1,78 @@ +import { Directory, Filesystem } from '@capacitor/filesystem'; +import { Share } from '@capacitor/share'; +import { toBase64 } from './blobBase64'; +import { hasNativeFeature } from './capabilities'; +import { TrekShell } from './trekShell'; +import { addToWallet, isWalletPassName } from './wallet'; + +/** Readable, but safe as a single path segment inside the cache directory. */ +export function cacheFileName(filename: string): string { + const cleaned = Array.from(filename, (ch) => (ch.charCodeAt(0) < 32 || '\\/:*?"<>|'.includes(ch) ? '_' : ch)) + .join('') + .trim(); + return cleaned.replace(/^\.+/, '') || 'download'; +} + +export function fileNameFromUrl(url: string): string { + const [path = ''] = url.split('?', 1); + const last = path.split('/').filter(Boolean).pop() ?? ''; + try { + return decodeURIComponent(last); + } catch { + return last; + } +} + +/** + * The app's WebView cannot save a download on its own, so the file goes into + * the app's cache and from there into the system share sheet, which offers + * saving it to Files, opening it in another app or sending it on. + */ +export async function shareFile(blob: Blob, filename: string): Promise { + // A Wallet pass goes to Apple Wallet's own sheet, not to the generic share sheet. + if (isWalletPassName(filename) && (await addToWallet(blob))) return; + await shareCached(await writeToCache(blob, filename)); +} + +/** + * Opens a file to look at it: a PDF to page through, an image, a document, in + * the system's viewer (Quick Look on iOS, the viewing app on Android). An app + * without the viewer, or a type nothing on the device shows, gets the share + * sheet as before, which still previews and saves it. + */ +export async function openNativeFile(blob: Blob, filename: string): Promise { + if (isWalletPassName(filename) && (await addToWallet(blob))) return; + const uri = await writeToCache(blob, filename); + if (hasNativeFeature('filePreview')) { + try { + const { result } = await TrekShell.previewFile({ + path: uri, + mimeType: blob.type || 'application/octet-stream', + title: filename, + }); + if (result === 'shown') return; + } catch { + /* the viewer could not open it: the share sheet still can */ + } + } + await shareCached(uri); +} + +async function writeToCache(blob: Blob, filename: string): Promise { + const { uri } = await Filesystem.writeFile({ + path: cacheFileName(filename), + data: await toBase64(blob), + directory: Directory.Cache, + }); + return uri; +} + +async function shareCached(uri: string): Promise { + try { + await Share.share({ files: [uri] }); + } catch (err) { + // Dismissing the sheet rejects; that is the user's choice, not a failure. + if (/cancel/i.test(String((err as Error)?.message))) return; + throw err; + } +} diff --git a/client/src/native/offlineShell.test.ts b/client/src/native/offlineShell.test.ts new file mode 100644 index 000000000..8d6f85aa1 --- /dev/null +++ b/client/src/native/offlineShell.test.ts @@ -0,0 +1,128 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { keepOfflineShellFresh, manifestFiles } from './offlineShell'; +import { TrekShell } from './trekShell'; + +vi.mock('./trekShell', () => ({ TrekShell: { refreshOfflineCopy: vi.fn() } })); + +const manifest = { + 'index.html': { + file: 'assets/index-a1b2c3d4.js', + css: ['assets/index-e5f6a7b8.css'], + assets: ['assets/poppins-11223344.woff2'], + }, + 'src/pages/AtlasPage.tsx': { file: 'assets/AtlasPage-99887766.js', css: ['assets/index-e5f6a7b8.css'] }, + _shared: { file: 'assets/shared-55443322.js', assets: 'not-a-list' }, + broken: null, +}; + +beforeEach(() => { + vi.mocked(TrekShell.refreshOfflineCopy).mockReset().mockResolvedValue({ saved: true }); + window.localStorage.clear(); +}); + +describe('manifestFiles', () => { + it('collects every chunk, stylesheet and asset once', () => { + expect(manifestFiles(manifest).sort()).toEqual([ + 'assets/AtlasPage-99887766.js', + 'assets/index-a1b2c3d4.js', + 'assets/index-e5f6a7b8.css', + 'assets/poppins-11223344.woff2', + 'assets/shared-55443322.js', + ]); + }); + + it('returns nothing for something that is not a manifest', () => { + expect(manifestFiles(null)).toEqual([]); + expect(manifestFiles('x')).toEqual([]); + }); +}); + +describe('keepOfflineShellFresh', () => { + it('refreshes the stored start page and fetches every file of the build', async () => { + const fetched: string[] = []; + const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + if (url === '/asset-manifest.json') { + expect(init).toEqual({ cache: 'no-store' }); + return new Response(JSON.stringify(manifest)); + } + fetched.push(url); + if (url.includes('shared')) throw new Error('offline for a moment'); + return new Response('x'); + }) as unknown as typeof fetch; + + await keepOfflineShellFresh(fetchImpl); + + expect(TrekShell.refreshOfflineCopy).toHaveBeenCalled(); + expect(fetched.sort()).toEqual([ + '/assets/AtlasPage-99887766.js', + '/assets/index-a1b2c3d4.js', + '/assets/index-e5f6a7b8.css', + '/assets/poppins-11223344.woff2', + '/assets/shared-55443322.js', + ]); + }); + + it('stops after the start page when the build has no manifest', async () => { + const fetchImpl = vi.fn(async () => new Response('', { status: 404 })) as unknown as typeof fetch; + await keepOfflineShellFresh(fetchImpl); + expect(fetchImpl).toHaveBeenCalledTimes(1); + }); + + it('fetches at low priority, only the own language, and once per build', async () => { + const withLocales = { + ...manifest, + '../shared/dist/i18n/de/index.mjs': { file: 'assets/de-aaaa1111.js' }, + '../shared/dist/i18n/fr/index.mjs': { file: 'assets/fr-bbbb2222.js' }, + '../shared/dist/i18n/en/index.mjs': { file: 'assets/en-cccc3333.js' }, + }; + const inits: (RequestInit | undefined)[] = []; + const fetched: string[] = []; + const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + if (url === '/asset-manifest.json') return new Response(JSON.stringify(withLocales)); + fetched.push(url); + inits.push(init); + return new Response('x'); + }) as unknown as typeof fetch; + + await keepOfflineShellFresh(fetchImpl, 'de'); + expect(fetched).toContain('/assets/de-aaaa1111.js'); + expect(fetched).toContain('/assets/en-cccc3333.js'); + expect(fetched).not.toContain('/assets/fr-bbbb2222.js'); + expect(inits.every((i) => (i as { priority?: string } | undefined)?.priority === 'low')).toBe(true); + + const before = fetched.length; + await keepOfflineShellFresh(fetchImpl, 'de'); + expect(fetched.length).toBe(before); + + await keepOfflineShellFresh(fetchImpl, 'fr'); + expect(fetched).toContain('/assets/fr-bbbb2222.js'); + }); + + it('on Android hands the list to the native store instead of fetching it here', async () => { + vi.mocked(TrekShell.refreshOfflineCopy).mockResolvedValue({ saved: true, complete: true }); + const fetchImpl = vi.fn(async (input: RequestInfo | URL) => { + if (String(input) === '/asset-manifest.json') return new Response(JSON.stringify(manifest)); + throw new Error('the native side fetches the files'); + }) as unknown as typeof fetch; + + await keepOfflineShellFresh(fetchImpl, 'en', true); + + expect(fetchImpl).toHaveBeenCalledTimes(1); + expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledTimes(1); + const { files } = vi.mocked(TrekShell.refreshOfflineCopy).mock.calls[0][0] as { files: string[] }; + expect(files).toContain('assets/index-a1b2c3d4.js'); + expect(files).toContain('assets/AtlasPage-99887766.js'); + }); + + it('on Android asks again on the next launch while the store is incomplete', async () => { + vi.mocked(TrekShell.refreshOfflineCopy).mockResolvedValue({ saved: true, complete: false }); + const fetchImpl = vi.fn(async () => new Response(JSON.stringify(manifest))) as unknown as typeof fetch; + + await keepOfflineShellFresh(fetchImpl, 'en', true); + await keepOfflineShellFresh(fetchImpl, 'en', true); + + expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledTimes(2); + }); +}); diff --git a/client/src/native/offlineShell.ts b/client/src/native/offlineShell.ts new file mode 100644 index 000000000..09a715a76 --- /dev/null +++ b/client/src/native/offlineShell.ts @@ -0,0 +1,110 @@ +import { TrekShell } from './trekShell'; + +/** + * The app's stand-in for a service worker, so it starts without its server (a + * trip without reception, a server at home out of reach). WKWebView runs none + * for a domain the app does not list at build time, and Android's web view + * none on a plain-http server, the usual address of a server at home. So the + * native side keeps a copy of the start page (TrekShellPlugin.refreshOfflineCopy) + * and every chunk of the current build: iOS in WebKit's HTTP cache, which this + * fills (the server marks the files immutable), Android in the app's own store, + * which the native side fills from the list this hands it. A cold start without + * the server then loads the stored start page under the server's origin and + * finds all its scripts, including the lazy routes nobody has opened yet. + */ + +const MANIFEST_URL = '/asset-manifest.json'; +/** + * Few at a time and at low priority: the warm-up runs while the user already + * moves through the app, and the page they open must never queue behind it. + * Measured on a phone: four at normal priority held a first visit to Vacay + * back by five to seven seconds right after a server update. + */ +const CONCURRENCY = 2; +/** The build whose files are all in the cache; a launch on the same build skips the walk. */ +const WARMED_KEY = 'trek.offlineShellBuild'; +const LOCALE_KEY = /\/i18n\/([^/]+)\/index\.[cm]?js$/; + +interface ManifestChunk { + file?: string; + css?: string[]; + assets?: string[]; +} + +/** + * Every file of the build, without the translations of other languages: only + * the user's own and English (the fallback) are needed offline, the other 25 + * would cost several megabytes per build for nothing. + */ +export function manifestFiles(manifest: unknown, language?: string): string[] { + if (typeof manifest !== 'object' || manifest === null) return []; + const keep = new Set(['en', language ?? 'en']); + const files = new Set(); + for (const [key, chunk] of Object.entries(manifest as Record)) { + const locale = LOCALE_KEY.exec(key)?.[1]; + if (locale && !keep.has(locale)) continue; + if (typeof chunk?.file === 'string') files.add(chunk.file); + for (const list of [chunk?.css, chunk?.assets]) { + if (Array.isArray(list)) list.forEach((f) => typeof f === 'string' && files.add(f)); + } + } + return [...files]; +} + +/** True when every file was fetched. */ +async function warmCache(files: string[], fetchFile: (path: string) => Promise): Promise { + const queue = [...files]; + let complete = true; + const worker = async (): Promise => { + for (let path = queue.shift(); path !== undefined; path = queue.shift()) { + try { + await fetchFile(`/${path}`); + } catch { + // One missing chunk must not stop the rest; the next launch tries again. + complete = false; + } + } + }; + await Promise.all(Array.from({ length: CONCURRENCY }, worker)); + return complete; +} + +function warmedBuild(): string | null { + try { + return window.localStorage.getItem(WARMED_KEY); + } catch { + return null; + } +} + +function rememberWarmed(build: string): void { + try { + window.localStorage.setItem(WARMED_KEY, build); + } catch { + // Not remembered: the next launch walks the files again, from the cache. + } +} + +export async function keepOfflineShellFresh( + fetchImpl: typeof fetch = fetch, + language?: string, + nativeStore = false +): Promise { + if (!nativeStore) await TrekShell.refreshOfflineCopy(); + const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' }); + if (!response.ok) return; + const files = manifestFiles(await response.json(), language); + // The build and the language together: a new language needs its own chunk. + const build = `${[...files].sort((a, b) => a.localeCompare(b)).find((f) => /index-[^/]+\.js$/.test(f)) ?? files.length}:${language ?? 'en'}`; + if (nativeStore) { + // The native side fetches only what its store lacks, and keeps the start page fresh each time. + const { complete } = await TrekShell.refreshOfflineCopy({ files }); + if (complete) rememberWarmed(build); + return; + } + if (warmedBuild() === build) return; + const complete = await warmCache(files, (path) => + fetchImpl(path, { priority: 'low' } as RequestInit).then((r) => r.blob()) + ); + if (complete) rememberWarmed(build); +} diff --git a/client/src/native/offlineTiles.test.ts b/client/src/native/offlineTiles.test.ts new file mode 100644 index 000000000..0a031aaea --- /dev/null +++ b/client/src/native/offlineTiles.test.ts @@ -0,0 +1,217 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + fromOfflineUrl, + installOfflineProtocol, + offlineProtocol, + offlineStyle, + rewriteDocument, + toOfflineUrl, +} from './offlineTiles'; +import { isNativeIos } from './platform'; + +vi.mock('./platform', () => ({ isNativeIos: vi.fn() })); +// The mechanism is what is tested here; whether the GL maps use it is glSchemes.ts's switch. +vi.mock('./glSchemes', () => ({ GL_MAPS_THROUGH_APP_SCHEMES: true, glMapsThroughAppSchemes: () => true })); + +const cached = new Map(); +const cache = { match: vi.fn(async (url: string) => cached.get(url)?.clone()) }; + +beforeEach(() => { + cached.clear(); + vi.mocked(isNativeIos).mockReturnValue(true); + vi.stubGlobal('caches', { open: vi.fn(async () => cache) }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +function params(url: string, type: 'json' | 'arrayBuffer' | 'image' | 'string') { + return { url, type }; +} + +describe('URL rewriting', () => { + it('moves https URLs onto the protocol and back, and leaves everything else', () => { + expect(toOfflineUrl('https://tiles.openfreemap.org/styles/positron')).toBe( + 'trek-offline://tiles.openfreemap.org/styles/positron' + ); + expect(fromOfflineUrl('trek-offline://tiles.openfreemap.org/styles/positron')).toBe( + 'https://tiles.openfreemap.org/styles/positron' + ); + expect(toOfflineUrl('mapbox://styles/mapbox/streets-v12')).toBe('mapbox://styles/mapbox/streets-v12'); + expect(fromOfflineUrl('https://x.test/a')).toBe('https://x.test/a'); + }); + + it('rewrites the style only inside the iOS app with Cache Storage', () => { + const style = 'https://tiles.openfreemap.org/styles/liberty?key=abc'; + expect(offlineStyle(style)).toBe('trek-offline://tiles.openfreemap.org/styles/liberty?key=abc'); + expect(offlineStyle({ version: 8 })).toEqual({ version: 8 }); + + vi.mocked(isNativeIos).mockReturnValue(false); + expect(offlineStyle(style)).toBe(style); + + vi.mocked(isNativeIos).mockReturnValue(true); + vi.stubGlobal('caches', undefined); + expect(offlineStyle(style)).toBe(style); + }); + + it('points sources, tiles, glyphs and sprites of a style at the protocol', () => { + expect( + rewriteDocument({ + version: 8, + glyphs: 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf', + sprite: [{ id: 'default', url: 'https://tiles.openfreemap.org/sprites/ofm' }, 'odd'], + sources: { + openmaptiles: { type: 'vector', url: 'https://tiles.openfreemap.org/planet' }, + inline: { type: 'raster', tiles: ['https://a.test/{z}/{x}/{y}.png', 7] }, + broken: null, + }, + layers: [], + }) + ).toEqual({ + version: 8, + glyphs: 'trek-offline://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf', + sprite: [{ id: 'default', url: 'trek-offline://tiles.openfreemap.org/sprites/ofm' }, 'odd'], + sources: { + openmaptiles: { type: 'vector', url: 'trek-offline://tiles.openfreemap.org/planet' }, + inline: { type: 'raster', tiles: ['trek-offline://a.test/{z}/{x}/{y}.png', 7] }, + broken: null, + }, + layers: [], + }); + }); + + it('handles a TileJSON, a single sprite URL and things that are not documents', () => { + expect(rewriteDocument({ tiles: ['https://t.test/20250101/{z}/{x}/{y}.pbf'] })).toEqual({ + tiles: ['trek-offline://t.test/20250101/{z}/{x}/{y}.pbf'], + }); + expect(rewriteDocument({ sprite: 'https://s.test/sprite' })).toEqual({ sprite: 'trek-offline://s.test/sprite' }); + expect(rewriteDocument('x')).toBe('x'); + expect(rewriteDocument([1])).toEqual([1]); + }); +}); + +describe('offlineProtocol', () => { + it('answers a document from the network and rewrites it', async () => { + const fetchMock = vi.fn(async () => new Response(JSON.stringify({ tiles: ['https://t.test/{z}/{x}/{y}.pbf'] }))); + vi.stubGlobal('fetch', fetchMock); + const result = await offlineProtocol(params('trek-offline://t.test/planet', 'json'), new AbortController()); + expect(fetchMock).toHaveBeenCalledWith('https://t.test/planet', expect.objectContaining({ mode: 'cors' })); + expect(result.data).toEqual({ tiles: ['trek-offline://t.test/{z}/{x}/{y}.pbf'] }); + }); + + it('falls back to the cached document when the network is gone', async () => { + cached.set('https://t.test/style', new Response(JSON.stringify({ version: 8 }))); + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new TypeError('offline'); + }) + ); + const result = await offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController()); + expect(result.data).toEqual({ version: 8 }); + }); + + it('serves tiles from the cache without asking the network', async () => { + cached.set('https://t.test/1/2/3.pbf', new Response(new Uint8Array([1, 2, 3]))); + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + const result = await offlineProtocol( + params('trek-offline://t.test/1/2/3.pbf', 'arrayBuffer'), + new AbortController() + ); + expect(new Uint8Array(result.data as ArrayBuffer)).toEqual(new Uint8Array([1, 2, 3])); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('fetches an uncached tile, and returns text for string requests', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('hello')) + ); + const tile = await offlineProtocol(params('trek-offline://t.test/9/9/9.png', 'image'), new AbortController()); + expect(new TextDecoder().decode(tile.data as ArrayBuffer)).toBe('hello'); + const text = await offlineProtocol(params('trek-offline://t.test/a.txt', 'string'), new AbortController()); + expect(text.data).toBe('hello'); + }); + + it('fails loudly on an uncached tile offline or an HTTP error', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new TypeError('offline'); + }) + ); + await expect( + offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController()) + ).rejects.toThrow('offline'); + + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('nope', { status: 404 })) + ); + await expect( + offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController()) + ).rejects.toThrow('HTTP 404'); + await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController())).rejects.toThrow( + 'Not available offline' + ); + }); + + it('passes an abort straight through for documents', async () => { + const controller = new AbortController(); + controller.abort(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new DOMException('aborted', 'AbortError'); + }) + ); + await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), controller)).rejects.toThrow('aborted'); + }); +}); + +describe('offlineProtocol without Cache Storage', () => { + it('draws from the network when the web view will not open the cache, and only then fails offline', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + vi.stubGlobal('caches', { + open: vi.fn(async () => { + throw new DOMException('denied', 'SecurityError'); + }), + }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify({ sources: {} }))) + ); + const doc = await offlineProtocol(params('trek-offline://s.test/style.json', 'json'), new AbortController()); + expect(doc.data).toEqual({ sources: {} }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('tile')) + ); + const tile = await offlineProtocol(params('trek-offline://t.test/1/1/1.png', 'image'), new AbortController()); + expect(new TextDecoder().decode(tile.data as ArrayBuffer)).toBe('tile'); + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new TypeError('offline'); + }) + ); + await expect( + offlineProtocol(params('trek-offline://s.test/style.json', 'json'), new AbortController()) + ).rejects.toThrow('Not available offline'); + }); +}); + +describe('installOfflineProtocol', () => { + it('registers only inside the iOS app', () => { + const addProtocol = vi.fn(); + installOfflineProtocol({ addProtocol }); + expect(addProtocol).toHaveBeenCalledWith('trek-offline', offlineProtocol); + + addProtocol.mockClear(); + vi.mocked(isNativeIos).mockReturnValue(false); + installOfflineProtocol({ addProtocol }); + expect(addProtocol).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/native/offlineTiles.ts b/client/src/native/offlineTiles.ts new file mode 100644 index 000000000..676c4e8fb --- /dev/null +++ b/client/src/native/offlineTiles.ts @@ -0,0 +1,135 @@ +import type { AddProtocolAction, GetResourceResponse, RequestParameters } from 'maplibre-gl'; +import { VECTOR_CACHE } from '../sync/glPrefetcher'; +import { openCacheStorage } from '../sync/openCacheStorage'; +import { glMapsThroughAppSchemes } from './glSchemes'; +import { isNativeIos } from './platform'; + +/** + * Offline vector maps for the iOS app. + * + * In a browser the service worker answers MapLibre's requests from the + * 'gl-map-offline' cache that glPrefetcher fills for trips marked for offline. + * The iOS app has no service worker, so nothing reads that cache there. This + * protocol takes the service worker's place: the style URL is rewritten to + * trek-offline://, every https URL inside the style and its TileJSON gets the + * same scheme, and the handler serves them from the cache or the network. + * + * Mapbox GL has no protocol hook, so a Mapbox basemap stays online-only in + * the app. + */ + +const OFFLINE_SCHEME = 'trek-offline'; +const PREFIX = `${OFFLINE_SCHEME}://`; + +/** Whether the iOS app can serve the protocol at all. */ +function offlineProtocolAvailable(): boolean { + return isNativeIos() && typeof caches !== 'undefined'; +} + +/** Whether a style goes through the protocol right now (see glSchemes.ts). */ +function offlineTilesActive(): boolean { + return offlineProtocolAvailable() && glMapsThroughAppSchemes(); +} + +export function toOfflineUrl(url: string): string { + return url.startsWith('https://') ? PREFIX + url.slice('https://'.length) : url; +} + +export function fromOfflineUrl(url: string): string { + return url.startsWith(PREFIX) ? 'https://' + url.slice(PREFIX.length) : url; +} + +/** The style URL to hand MapLibre: rewritten inside the iOS app, untouched anywhere else. */ +export function offlineStyle(style: T): T { + return offlineTilesActive() && typeof style === 'string' ? (toOfflineUrl(style) as T) : style; +} + +type Doc = Record; +/** What a protocol handler may hand MapLibre back. */ +type ProtocolData = Awaited>['data']; + +const isDoc = (value: unknown): value is Doc => typeof value === 'object' && value !== null && !Array.isArray(value); +const rewriteList = (value: unknown): unknown => + Array.isArray(value) ? value.map((v) => (typeof v === 'string' ? toOfflineUrl(v) : v)) : value; + +/** + * Points the URLs inside a style document or a TileJSON at the protocol, so + * that MapLibre asks this handler for the sprite, the glyphs, the TileJSON and + * the tiles as well, not only for the style. + */ +export function rewriteDocument(doc: unknown): unknown { + if (!isDoc(doc)) return doc; + const out: Doc = { ...doc }; + if ('tiles' in out) out.tiles = rewriteList(out.tiles); + if (typeof out.glyphs === 'string') out.glyphs = toOfflineUrl(out.glyphs); + if (typeof out.sprite === 'string') out.sprite = toOfflineUrl(out.sprite); + else if (Array.isArray(out.sprite)) { + out.sprite = out.sprite.map((entry) => + isDoc(entry) && typeof entry.url === 'string' ? { ...entry, url: toOfflineUrl(entry.url) } : entry + ); + } + if (isDoc(out.sources)) { + out.sources = Object.fromEntries( + Object.entries(out.sources).map(([id, source]) => { + if (!isDoc(source)) return [id, source]; + const rewritten: Doc = { ...source }; + if (typeof rewritten.url === 'string') rewritten.url = toOfflineUrl(rewritten.url); + if ('tiles' in rewritten) rewritten.tiles = rewriteList(rewritten.tiles); + return [id, rewritten]; + }) + ); + } + return out; +} + +/** + * Documents are asked of the network first so a changed style shows up, and + * fall back to the cache offline. Tiles, glyphs and sprites never change under + * their URL, so the cache goes first and saves the round trip. + */ +async function load(url: string, networkFirst: boolean, signal: AbortSignal): Promise { + const cache = await openCache(); + if (!networkFirst && cache) { + const cached = await cache.match(url); + if (cached) return cached; + } + try { + const response = await fetch(url, { mode: 'cors', signal }); + if (response.ok) return response; + if (!networkFirst) return response; + } catch (err) { + if (signal.aborted || !networkFirst) throw err; + } + const cached = await cache?.match(url); + if (cached) return cached; + throw new Error(`Not available offline: ${url}`); +} + +/** + * The stored trips' vector cache, or null where the web view will not open it + * (WKWebView can refuse CacheStorage). Without it the map still draws from the + * network: the store is what keeps it offline, not what lets it draw at all. + */ +async function openCache(): Promise { + // Refused, or left pending, by the web view: read from the network instead, + // which is all a cache miss does anyway. + return openCacheStorage(VECTOR_CACHE); +} + +export const offlineProtocol: AddProtocolAction = async ( + params: RequestParameters, + abortController: AbortController +): Promise> => { + const url = fromOfflineUrl(params.url); + const response = await load(url, params.type === 'json', abortController.signal); + if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`); + if (params.type === 'json') return { data: rewriteDocument(await response.json()) as ProtocolData }; + if (params.type === 'string') return { data: await response.text() }; + return { data: await response.arrayBuffer() }; +}; + +export function installOfflineProtocol(maplibre: { + addProtocol: (name: string, action: AddProtocolAction) => void; +}): void { + if (offlineProtocolAvailable()) maplibre.addProtocol(OFFLINE_SCHEME, offlineProtocol); +} diff --git a/client/src/native/platform.test.ts b/client/src/native/platform.test.ts new file mode 100644 index 000000000..96a50ce77 --- /dev/null +++ b/client/src/native/platform.test.ts @@ -0,0 +1,33 @@ +import { Capacitor } from '@capacitor/core'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { isNativeApp, isNativeIos, nativeServerHost } from './platform'; + +vi.mock('@capacitor/core', () => ({ Capacitor: { isNativePlatform: vi.fn(), getPlatform: vi.fn() } })); + +beforeEach(() => { + vi.mocked(Capacitor.isNativePlatform).mockReturnValue(true); + vi.mocked(Capacitor.getPlatform).mockReturnValue('ios'); +}); + +describe('platform', () => { + it('tells the app from a browser', () => { + expect(isNativeApp()).toBe(true); + vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false); + expect(isNativeApp()).toBe(false); + }); + + it('narrows to iOS', () => { + expect(isNativeIos()).toBe(true); + vi.mocked(Capacitor.getPlatform).mockReturnValue('android'); + expect(isNativeIos()).toBe(false); + vi.mocked(Capacitor.getPlatform).mockReturnValue('ios'); + vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false); + expect(isNativeIos()).toBe(false); + }); + + it('names the server the WebView sits on, only inside the app', () => { + expect(nativeServerHost()).toBe(window.location.host); + vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false); + expect(nativeServerHost()).toBeNull(); + }); +}); diff --git a/client/src/native/platform.ts b/client/src/native/platform.ts new file mode 100644 index 000000000..12d0ee973 --- /dev/null +++ b/client/src/native/platform.ts @@ -0,0 +1,19 @@ +import { Capacitor } from '@capacitor/core'; + +/** True inside the iOS and Android apps, where the WebView shows this server's UI. */ +export function isNativeApp(): boolean { + return Capacitor.isNativePlatform(); +} + +export function isNativeIos(): boolean { + return isNativeApp() && Capacitor.getPlatform() === 'ios'; +} + +export function isNativeAndroid(): boolean { + return isNativeApp() && Capacitor.getPlatform() === 'android'; +} + +/** The server the app is connected to: the WebView sits on its origin. */ +export function nativeServerHost(): string | null { + return isNativeApp() ? window.location.host : null; +} diff --git a/client/src/native/priceValue.test.ts b/client/src/native/priceValue.test.ts new file mode 100644 index 000000000..e2cd8d838 --- /dev/null +++ b/client/src/native/priceValue.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { priceValue } from './priceValue'; + +describe('priceValue', () => { + it('reads the store price strings of the usual currencies, in hundredths', () => { + expect(priceValue('9,99 €')).toBe(999); + expect(priceValue('$9.99')).toBe(999); + expect(priceValue('59,99 €')).toBe(5999); + expect(priceValue('¥1,500')).toBe(150000); + expect(priceValue('1.234,50 €')).toBe(123450); + expect(priceValue('CHF 10')).toBe(1000); + }); + + it('has no value for nothing or for a string it cannot read with confidence', () => { + expect(priceValue(undefined)).toBeNull(); + expect(priceValue('')).toBeNull(); + expect(priceValue('free')).toBeNull(); + expect(priceValue('1.2.3')).toBeNull(); + }); +}); diff --git a/client/src/native/priceValue.ts b/client/src/native/priceValue.ts new file mode 100644 index 000000000..0af30b31f --- /dev/null +++ b/client/src/native/priceValue.ts @@ -0,0 +1,14 @@ +/** + * The amount in a store price string such as "9,99 €", "$9.99" or "¥1,500", in + * hundredths; null when it cannot be read with confidence. Only ever compared + * with another price of the same store, never shown. + */ +export function priceValue(label: string | undefined): number | null { + if (!label) return null; + const digits = label.replace(/[^\d.,]/g, ''); + const match = /^(\d{1,3}(?:[.,]\d{3})*|\d+)(?:[.,](\d{1,2}))?$/.exec(digits); + if (!match) return null; + const whole = Number(match[1].replace(/[.,]/g, '')); + const fraction = match[2] ? Number(match[2].padEnd(2, '0')) : 0; + return Number.isFinite(whole) ? whole * 100 + fraction : null; +} diff --git a/client/src/native/push.test.ts b/client/src/native/push.test.ts new file mode 100644 index 000000000..4c2add3e0 --- /dev/null +++ b/client/src/native/push.test.ts @@ -0,0 +1,79 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { hasNativeFeature } from './capabilities'; +import { isNativeApp } from './platform'; +import { + NativePushDenied, + forgetNativePush, + nativePushActive, + nativePushEndpoint, + openPushTarget, + registerNativePush, + startNativePush, +} from './push'; +import { TrekShell } from './trekShell'; + +vi.mock('./platform', () => ({ isNativeApp: vi.fn() })); +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() })); +vi.mock('./trekShell', () => ({ + TrekShell: { + registerPush: vi.fn(), + takeOpenedPush: vi.fn(), + addListener: vi.fn(async () => ({ remove: async () => {} })), + }, +})); + +const SUB = { + endpoint: 'https://push.liketrek.com/v1/apns/production/abcd', + keys: { p256dh: 'BPk', auth: 'aa' }, +}; + +beforeEach(() => { + window.localStorage.clear(); + vi.mocked(isNativeApp).mockReturnValue(true); + vi.mocked(hasNativeFeature).mockReturnValue(true); + vi.mocked(TrekShell.registerPush).mockReset().mockResolvedValue(SUB); + vi.mocked(TrekShell.takeOpenedPush).mockReset().mockResolvedValue({ url: null }); + window.history.replaceState({}, '', '/dashboard'); +}); + +describe('native push', () => { + it('is on only in an iOS binary that has it', () => { + expect(nativePushActive()).toBe(true); + vi.mocked(hasNativeFeature).mockReturnValue(false); + expect(nativePushActive()).toBe(false); + }); + + it('remembers the relay endpoint it subscribed with, and forgets it again', async () => { + expect(await registerNativePush()).toEqual(SUB); + expect(nativePushEndpoint()).toBe(SUB.endpoint); + forgetNativePush(); + expect(nativePushEndpoint()).toBeNull(); + }); + + it('tells a refused permission apart from a failure', async () => { + vi.mocked(TrekShell.registerPush).mockRejectedValue({ code: 'DENIED' }); + await expect(registerNativePush()).rejects.toBeInstanceOf(NativePushDenied); + vi.mocked(TrekShell.registerPush).mockRejectedValue(new Error('apns down')); + await expect(registerNativePush()).rejects.toThrow('apns down'); + expect(nativePushEndpoint()).toBeNull(); + }); + + it('opens a tapped notification inside the app, and never another origin', () => { + const pops = vi.fn(); + window.addEventListener('popstate', pops); + openPushTarget('/trips/12?tab=chat'); + expect(window.location.pathname).toBe('/trips/12'); + expect(window.location.search).toBe('?tab=chat'); + openPushTarget('https://evil.example/phish'); + expect(window.location.pathname).toBe('/trips/12'); + expect(pops).toHaveBeenCalledTimes(1); + window.removeEventListener('popstate', pops); + }); + + it('follows the notification the app was opened from', async () => { + vi.mocked(TrekShell.takeOpenedPush).mockResolvedValue({ url: '/trips/3' }); + await startNativePush(); + expect(window.location.pathname).toBe('/trips/3'); + expect(TrekShell.addListener).toHaveBeenCalledWith('pushOpened', expect.any(Function)); + }); +}); diff --git a/client/src/native/push.ts b/client/src/native/push.ts new file mode 100644 index 000000000..056b0183b --- /dev/null +++ b/client/src/native/push.ts @@ -0,0 +1,85 @@ +import type { PushSubscriptionInput } from '@trek/shared'; +import { hasNativeFeature } from './capabilities'; +import { isNativeApp } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell } from './trekShell'; + +/** + * Push inside the app: the same Web Push subscription a browser makes, only + * the app makes it (TrekShell.registerPush). Its endpoint is liketrek's relay + * for this device's APNs or FCM token and its keys live on the device, so the + * server encrypts exactly as for a browser and the relay hands on ciphertext + * that the app decrypts (iOS: the notification extension, Android: + * TrekPushService). push/webPush.ts takes this path + * wherever the binary reports the nativePush feature; the settings card, the + * test push and the logout teardown stay what they are. + * + * The endpoint is remembered on the device, the way a browser remembers its + * subscription, so the card can say on or off and the logout can name it. + */ +const KEY = 'trek.nativePushEndpoint'; + +export function nativePushActive(): boolean { + return isNativeApp() && hasNativeFeature('nativePush'); +} + +export function nativePushEndpoint(): string | null { + try { + return window.localStorage.getItem(KEY); + } catch { + return null; + } +} + +function rememberEndpoint(endpoint: string | null): void { + try { + if (endpoint) window.localStorage.setItem(KEY, endpoint); + else window.localStorage.removeItem(KEY); + } catch { + // Storage refused: the card then reads off and offers to switch it on again. + } +} + +export class NativePushDenied extends Error {} + +/** Permission, APNs and the device keys, as a subscription the server can store. */ +export async function registerNativePush(): Promise { + try { + const subscription = await TrekShell.registerPush(); + rememberEndpoint(subscription.endpoint); + return subscription; + } catch (err) { + if ((err as { code?: string } | null)?.code === 'DENIED') throw new NativePushDenied(); + throw err; + } +} + +export function forgetNativePush(): void { + rememberEndpoint(null); +} + +/** Opens the place a tapped notification points at, inside the app's own routing. */ +export function openPushTarget(url: string): void { + let target: URL; + try { + target = new URL(url, window.location.origin); + } catch { + return; + } + // Only this server's pages: a notification never navigates the app elsewhere. + if (target.origin !== window.location.origin) return; + window.history.pushState({}, '', `${target.pathname}${target.search}${target.hash}`); + window.dispatchEvent(new PopStateEvent('popstate')); +} + +/** Follows taps on notifications, including the one the app was opened from. */ +export async function startNativePush(): Promise { + if (!nativePushActive()) return; + void TrekShell.addListener('pushOpened', ({ url }) => openPushTarget(url)); + try { + const { url } = await TrekShell.takeOpenedPush(); + if (url) openPushTarget(url); + } catch (err) { + reportNativeFailure(err); + } +} diff --git a/client/src/native/quickActions.test.ts b/client/src/native/quickActions.test.ts new file mode 100644 index 000000000..ec6287e2f --- /dev/null +++ b/client/src/native/quickActions.test.ts @@ -0,0 +1,66 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Trip } from '../types'; +import { hasNativeFeature } from './capabilities'; +import { isNativeApp } from './platform'; +import { openPushTarget } from './push'; +import { publishQuickActions, quickActionsFor, startQuickActions } from './quickActions'; +import { TrekShell } from './trekShell'; + +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() })); +vi.mock('./platform', () => ({ isNativeApp: vi.fn() })); +vi.mock('./push', () => ({ openPushTarget: vi.fn() })); +vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() })); +vi.mock('./trekShell', () => ({ + TrekShell: { setQuickActions: vi.fn(async () => {}), takeQuickAction: vi.fn(), addListener: vi.fn() }, +})); + +const t = ((key: string) => + ({ 'dashboard.newTrip': 'New Trip', 'dashboard.nextTrip': 'Next trip', 'native.widget.today': 'Today' })[key] ?? + key) as never; +const trip = (start: string, end: string) => + ({ id: 7, title: 'Lisbon', start_date: start, end_date: end }) as unknown as Trip; + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(isNativeApp).mockReturnValue(true); + vi.mocked(hasNativeFeature).mockReturnValue(true); +}); + +describe('quickActionsFor', () => { + it('offers "New trip" alone without a trip', () => { + expect(quickActionsFor(null, '2026-11-09', t)).toEqual([ + { type: 'newTrip', title: 'New Trip', icon: 'add', path: '/dashboard?create=1' }, + ]); + }); + + it('adds the trip coming up by its name', () => { + expect(quickActionsFor(trip('2026-12-01', '2026-12-05'), '2026-11-09', t)[1]).toEqual({ + type: 'trip', + title: 'Lisbon', + subtitle: 'Next trip', + icon: 'trip', + path: '/trips/7', + }); + }); + + it('calls a trip that runs today "Today"', () => { + expect(quickActionsFor(trip('2026-11-08', '2026-11-10'), '2026-11-09', t)[1]?.subtitle).toBe('Today'); + }); +}); + +describe('the binary', () => { + it('gets the actions only where it has the feature', async () => { + await publishQuickActions([]); + expect(TrekShell.setQuickActions).toHaveBeenCalledWith({ items: [] }); + vi.mocked(hasNativeFeature).mockReturnValue(false); + await publishQuickActions([]); + expect(TrekShell.setQuickActions).toHaveBeenCalledTimes(1); + }); + + it('opens the action the app was launched with, and listens for the next ones', async () => { + vi.mocked(TrekShell.takeQuickAction).mockResolvedValue({ path: '/trips/7' }); + await startQuickActions(); + expect(openPushTarget).toHaveBeenCalledWith('/trips/7'); + expect(TrekShell.addListener).toHaveBeenCalledWith('quickAction', expect.any(Function)); + }); +}); diff --git a/client/src/native/quickActions.ts b/client/src/native/quickActions.ts new file mode 100644 index 000000000..cd86cd3f1 --- /dev/null +++ b/client/src/native/quickActions.ts @@ -0,0 +1,53 @@ +import type { TranslationFn, Trip } from '../types'; +import { hasNativeFeature } from './capabilities'; +import { isNativeApp } from './platform'; +import { openPushTarget } from './push'; +import { reportNativeFailure } from './reportFailure'; +import { type NativeQuickAction, TrekShell } from './trekShell'; + +/** + * The quick actions a long press on the app icon shows, as in every iOS app: + * "New trip", and the trip coming up (or running today) by its name. Set by + * the UI, so they speak the app's language and follow the trips, and a tap + * opens the path each carries, the way a tap on a notification does. Only + * where the binary reports the feature `quickActions`. + */ + +export function quickActionsActive(): boolean { + return isNativeApp() && hasNativeFeature('quickActions'); +} + +/** The actions for the trip the dashboard leads with (`hero`), or "New trip" alone without one. */ +export function quickActionsFor(hero: Trip | null, today: string, t: TranslationFn): NativeQuickAction[] { + const items: NativeQuickAction[] = [ + { type: 'newTrip', title: t('dashboard.newTrip'), icon: 'add', path: '/dashboard?create=1' }, + ]; + if (hero) { + const running = !!hero.start_date && hero.start_date <= today && (hero.end_date ?? hero.start_date) >= today; + items.push({ + type: 'trip', + title: hero.title, + subtitle: running ? t('native.widget.today') : t('dashboard.nextTrip'), + icon: 'trip', + path: `/trips/${hero.id}`, + }); + } + return items; +} + +export async function publishQuickActions(items: NativeQuickAction[]): Promise { + if (!quickActionsActive()) return; + await TrekShell.setQuickActions({ items }).catch(reportNativeFailure); +} + +/** Opens the action the app was launched with, and every one chosen while it runs. */ +export async function startQuickActions(): Promise { + if (!quickActionsActive()) return; + void TrekShell.addListener('quickAction', ({ path }) => openPushTarget(path)); + try { + const { path } = await TrekShell.takeQuickAction(); + if (path) openPushTarget(path); + } catch (err) { + reportNativeFailure(err); + } +} diff --git a/client/src/native/reportFailure.test.ts b/client/src/native/reportFailure.test.ts new file mode 100644 index 000000000..3cf9dee12 --- /dev/null +++ b/client/src/native/reportFailure.test.ts @@ -0,0 +1,22 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { reportNativeFailure } from './reportFailure'; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('reportNativeFailure', () => { + it('hands the failure to the page error event', () => { + const report = vi.fn(); + vi.stubGlobal('reportError', report); + const err = new Error('share failed'); + reportNativeFailure(err); + expect(report).toHaveBeenCalledWith(err); + }); + + it('does nothing where the runtime has no reportError', () => { + vi.stubGlobal('reportError', undefined); + expect(() => reportNativeFailure(new Error('x'))).not.toThrow(); + }); +}); diff --git a/client/src/native/reportFailure.ts b/client/src/native/reportFailure.ts new file mode 100644 index 000000000..f02396c61 --- /dev/null +++ b/client/src/native/reportFailure.ts @@ -0,0 +1,9 @@ +/** + * For the app's best-effort calls (a haptic tap, the offline start page, a + * share sheet): the failure is not worth a toast, but it must not vanish + * either. reportError() hands it to the page's error event, which + * utils/globalErrorHandlers.ts logs like any other uncaught error. + */ +export function reportNativeFailure(err: unknown): void { + if (typeof globalThis.reportError === 'function') globalThis.reportError(err); +} diff --git a/client/src/native/serverAddress.test.ts b/client/src/native/serverAddress.test.ts new file mode 100644 index 000000000..444fc7a88 --- /dev/null +++ b/client/src/native/serverAddress.test.ts @@ -0,0 +1,216 @@ +import { describe, expect, it, vi } from 'vitest'; +import { candidateUrls, certificateTargetFor, probeDemo, probeServer, type ProbeResponse } from './serverAddress'; + +const features = ( + url: string, + data: unknown = { bookingImport: false, aiParsing: false, nativeApp: true, nativeApi: 3 } +): ProbeResponse => ({ status: 200, data, url }); + +describe('candidateUrls', () => { + it('tries https before http when no scheme was typed', () => { + expect(candidateUrls('trek.example.com')).toEqual(['https://trek.example.com', 'http://trek.example.com']); + expect(candidateUrls(' 192.168.1.10:3001/ ')).toEqual(['https://192.168.1.10:3001', 'http://192.168.1.10:3001']); + }); + + it('keeps an explicit scheme and path, without query, hash or trailing slashes', () => { + expect(candidateUrls('http://nas.local:3001/trek/?x=1#y')).toEqual(['http://nas.local:3001/trek']); + expect(candidateUrls('HTTPS://Trek.Example.com//')).toEqual(['https://trek.example.com']); + }); + + it('returns nothing for empty input or other schemes', () => { + expect(candidateUrls(' ')).toEqual([]); + expect(candidateUrls('ftp://trek.example.com')).toEqual([]); + expect(candidateUrls('javascript://alert(1)')).toEqual([]); + }); +}); + +describe('certificateTargetFor', () => { + it('keeps a certificate for the https address the typed text stands for', () => { + expect(certificateTargetFor('Trek.Example.com')).toEqual({ host: 'trek.example.com', port: 443 }); + expect(certificateTargetFor(' nas.local:8443/trek ')).toEqual({ host: 'nas.local', port: 8443 }); + expect(certificateTargetFor('https://trek.example.com:443/')).toEqual({ host: 'trek.example.com', port: 443 }); + }); + + it('has no target for a plain http address or nothing typed', () => { + expect(certificateTargetFor('http://nas.local:3001')).toBeNull(); + expect(certificateTargetFor('')).toBeNull(); + expect(certificateTargetFor(' ')).toBeNull(); + expect(certificateTargetFor('ftp://trek.example.com')).toBeNull(); + }); +}); + +describe('probeServer', () => { + it('accepts a server at the minimum native API version or above', async () => { + for (const nativeApi of [3, 4]) { + const data = { bookingImport: false, nativeApp: true, nativeApi }; + const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features', data)); + expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' }); + } + }); + + it('calls a server below the minimum native API version too old', async () => { + const data = { bookingImport: false, nativeApp: true, nativeApi: 2 }; + const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features', data)); + expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: false, reason: 'tooOld' }); + }); + + it('calls a server that speaks to the app but reports no native API version too old', async () => { + const data = { bookingImport: false, nativeApp: true }; + const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features', data)); + expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: false, reason: 'tooOld' }); + }); + + it('accepts a server that reports nativeApp and follows its redirect', async () => { + const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features')); + expect(await probeServer('http://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' }); + expect(get).toHaveBeenCalledWith('http://trek.example.com/api/health/features'); + }); + + it('falls back to the candidate itself when the final URL is not the probe path', async () => { + const get = vi.fn().mockResolvedValue(features('https://sso.example.com/login')); + expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' }); + }); + + it('moves on to plain http when https cannot be reached', async () => { + const get = vi + .fn() + .mockRejectedValueOnce(new Error('ECONNREFUSED')) + .mockResolvedValueOnce(features('http://192.168.1.10:3001/api/health/features')); + expect(await probeServer('192.168.1.10:3001', get)).toEqual({ ok: true, url: 'http://192.168.1.10:3001' }); + expect(get).toHaveBeenNthCalledWith(2, 'http://192.168.1.10:3001/api/health/features'); + }); + + it('names a TREK server without the native flag as too old', async () => { + const get = vi + .fn() + .mockResolvedValue( + features('https://old.example.com/api/health/features', { bookingImport: true, aiParsing: false }) + ); + expect(await probeServer('https://old.example.com', get)).toEqual({ ok: false, reason: 'tooOld' }); + }); + + it('tells a server that is not TREK apart from one that is not there', async () => { + const html = vi + .fn() + .mockResolvedValue({ status: 200, data: '', url: 'https://x.example.com/api/health/features' }); + expect(await probeServer('https://x.example.com', html)).toEqual({ ok: false, reason: 'notTrek' }); + + const missing = vi + .fn() + .mockResolvedValue({ status: 404, data: {}, url: 'https://x.example.com/api/health/features' }); + expect(await probeServer('https://x.example.com', missing)).toEqual({ ok: false, reason: 'notTrek' }); + + const down = vi.fn().mockRejectedValue(new Error('timeout')); + expect(await probeServer('x.example.com', down)).toEqual({ ok: false, reason: 'unreachable' }); + }); + + it('keeps the most telling failure across candidates', async () => { + const get = vi + .fn() + .mockResolvedValueOnce(features('https://nas.local/api/health/features', { bookingImport: false })) + .mockRejectedValueOnce(new Error('ECONNREFUSED')); + expect(await probeServer('nas.local', get)).toEqual({ ok: false, reason: 'tooOld' }); + }); + + it('refuses input that is not an address', async () => { + const get = vi.fn(); + expect(await probeServer('', get)).toEqual({ ok: false, reason: 'invalid' }); + expect(get).not.toHaveBeenCalled(); + }); +}); + +describe('probeDemo', () => { + it('probes the public demo server the address screen offers', async () => { + const get = vi.fn().mockResolvedValue(features('https://demo.liketrek.com/api/health/features')); + expect(await probeDemo(get)).toEqual({ ok: true, url: 'https://demo.liketrek.com' }); + expect(get).toHaveBeenCalledWith('https://demo.liketrek.com/api/health/features'); + }); +}); + +describe('probeServer behind a sign-in proxy', () => { + it('reports the gate, the server it guards and the host its sign-in lives on', async () => { + const get = vi.fn().mockResolvedValue({ + status: 200, + url: 'https://pangolin.example.com/auth/resource/3?redirect=https%3A%2F%2Ftrek.example.com', + data: 'Pangolin
    ', + } satisfies ProbeResponse); + expect(await probeServer('trek.example.com', get)).toEqual({ + ok: false, + reason: 'authGate', + url: 'https://trek.example.com', + gate: { kind: 'pangolin', loginHost: 'pangolin.example.com' }, + }); + }); + + it('asks the start page for the sign-in host when the API path only got a 401', async () => { + const get = vi.fn(async (url: string): Promise => + url.endsWith('/api/health/features') + ? { status: 401, url, data: 'Authelia' } + : { + status: 200, + url: 'https://auth.example.com/?rd=https%3A%2F%2Ftrek.example.com%2F', + data: 'Authelia', + } + ); + const result = await probeServer('https://trek.example.com', get); + expect(result).toMatchObject({ reason: 'authGate', gate: { kind: 'authelia', loginHost: 'auth.example.com' } }); + expect(get).toHaveBeenCalledWith('https://trek.example.com/'); + }); + + it('keeps calling an address that is simply something else not TREK', async () => { + const get = vi + .fn() + .mockResolvedValue({ status: 200, url: 'https://x.example.com/api/health/features', data: { hello: 1 } }); + expect(await probeServer('https://x.example.com', get)).toEqual({ ok: false, reason: 'notTrek' }); + }); +}); + +describe('probeServer behind mutual TLS', () => { + const asked = (status: number, sent: boolean, data: unknown = ''): ProbeResponse => ({ + status, + data, + url: 'https://trek.example.com/api/health/features', + clientCert: { requested: true, sent }, + }); + + it('names a handshake the proxy broke off for want of a certificate, with the host to add one for', async () => { + const get = vi.fn().mockResolvedValue(asked(0, false)); + expect(await probeServer('trek.example.com', get)).toEqual({ + ok: false, + reason: 'clientCert', + url: 'https://trek.example.com', + cert: { host: 'trek.example.com', port: 443, sent: false }, + }); + }); + + it("names Cloudflare's 403 without a certificate the same way, port included", async () => { + const get = vi.fn().mockResolvedValue(asked(403, false, 'Access denied')); + const result = await probeServer('https://Trek.Example.com:8443', get); + expect(result.reason).toBe('clientCert'); + expect(result.cert).toEqual({ host: 'trek.example.com', port: 8443, sent: false }); + }); + + it('says the proxy refused the certificate the app showed', async () => { + const get = vi.fn().mockResolvedValue(asked(400, true, '400 The SSL certificate error')); + expect((await probeServer('https://trek.example.com', get)).cert?.sent).toBe(true); + }); + + it('connects where the proxy asked and TREK answered, with or without a certificate', async () => { + const trek = { bookingImport: false, nativeApp: true, nativeApi: 3 }; + for (const sent of [true, false]) { + const get = vi.fn().mockResolvedValue(asked(200, sent, trek)); + expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' }); + } + }); + + it('keeps a failed connection without an ask unreachable, and ranks the ask above it', async () => { + const down = vi.fn().mockResolvedValue({ status: 0, data: '', url: 'https://trek.example.com' }); + expect(await probeServer('https://trek.example.com', down)).toEqual({ ok: false, reason: 'unreachable' }); + + const mixed = vi + .fn() + .mockResolvedValueOnce(asked(0, false)) + .mockResolvedValueOnce({ status: 0, data: '', url: 'http://trek.example.com' }); + expect((await probeServer('trek.example.com', mixed)).reason).toBe('clientCert'); + }); +}); diff --git a/client/src/native/serverAddress.ts b/client/src/native/serverAddress.ts new file mode 100644 index 000000000..79eade814 --- /dev/null +++ b/client/src/native/serverAddress.ts @@ -0,0 +1,174 @@ +import { detectAuthGate, type AuthGate } from './authGate'; +import { DEMO_SERVER_URL } from './links'; + +/** + * Turns what someone typed into the app's address field into a TREK server it + * can load, or a reason it cannot. + */ + +export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'authGate' | 'clientCert' | 'tooOld'; + +/** + * A proxy in front of the server asked for a client certificate (mutual TLS) + * and let the check through without one. `sent`: the app showed its stored + * certificate and the proxy refused it all the same. + */ +export interface ClientCertDemand { + host: string; + port: number; + sent: boolean; +} + +type ProbeResult = + | { ok: true; url: string; reason?: undefined; gate?: undefined; cert?: undefined } + /** + * `authGate`: a sign-in page of the user's own stands in front of TREK + * (authGate.ts); `url` is the server address it guards. `clientCert`: a proxy + * wants a client certificate, `cert` says for which host and whether one was shown. + */ + | { ok: false; reason: ProbeFailure; url?: string; gate?: AuthGate; cert?: ClientCertDemand }; + +export interface ProbeResponse { + status: number; + data: unknown; + /** The URL after redirects. */ + url: string; + headers?: Record; + /** Whether the server asked for a client certificate, and whether the app showed one (native requests only). */ + clientCert?: { requested: boolean; sent: boolean }; +} +export type ProbeGet = (url: string) => Promise; + +const FEATURES_PATH = '/api/health/features'; + +/** + * The oldest server API this app can work with (`nativeApi` in the features + * response). 3 is TREK 5.1.4, whose UI follows a widget or Live Activity tap + * that starts the app; 2 was 5.1.3, the first server whose sign-in from the app + * does not end in the browser. A server without the field is older still. Raising it + * goes with SERVER_CHECK in TrekServerStore (iOS and Android), so a server the + * app remembers from before is checked against the new minimum once. + */ +const MIN_NATIVE_API = 3; + +function normalize(raw: string): string | null { + let parsed: URL; + try { + parsed = new URL(raw); + } catch { + return null; + } + if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || !parsed.hostname) return null; + return parsed.origin + parsed.pathname.replace(/\/+$/, ''); +} + +/** + * Without a scheme, https comes first and plain http second: a server on the + * home network is often reached as a bare IP and port without TLS. + */ +export function candidateUrls(input: string): string[] { + const trimmed = input.trim(); + if (!trimmed) return []; + const candidates = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) + ? [normalize(trimmed)] + : [normalize(`https://${trimmed}`), normalize(`http://${trimmed}`)]; + return candidates.filter((url): url is string => url !== null); +} + +/** + * The host and port a client certificate added on the address screen, before + * any check, is kept for: the https address the typed text stands for. Null + * for nothing typed or a plain http address, which never gets a certificate. + */ +export function certificateTargetFor(input: string): { host: string; port: number } | null { + const https = candidateUrls(input).find((url) => url.startsWith('https://')); + if (!https) return null; + const url = new URL(https); + return { host: url.hostname.toLowerCase(), port: url.port ? Number(url.port) : 443 }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function judge(response: ProbeResponse): ProbeResult { + if (response.status !== 200 || !isRecord(response.data)) return { ok: false, reason: 'notTrek' }; + if (response.data.nativeApp === true) { + const api = response.data.nativeApi; + if (typeof api !== 'number' || api < MIN_NATIVE_API) return { ok: false, reason: 'tooOld' }; + // Follow a redirect (http to https, a canonical host) so the app loads the + // address the server actually answers on. + const base = response.url.endsWith(FEATURES_PATH) ? response.url.slice(0, -FEATURES_PATH.length) : null; + return { ok: true, url: (base && normalize(base)) || '' }; + } + return 'bookingImport' in response.data ? { ok: false, reason: 'tooOld' } : { ok: false, reason: 'notTrek' }; +} + +const FAILURE_RANK: Record = { + invalid: 0, + unreachable: 1, + notTrek: 2, + authGate: 3, + clientCert: 4, + tooOld: 5, +}; + +/** + * A server that asked for a client certificate and did not answer with TREK: + * the TLS handshake failed (status 0, as nginx, Caddy and Traefik do), or the + * proxy answered with its own refusal (Cloudflare's 403, nginx's 400). + */ +function clientCertDemand(candidate: string, response: ProbeResponse): ClientCertDemand | null { + if (!response.clientCert?.requested) return null; + const url = new URL(candidate); + return { host: url.hostname.toLowerCase(), port: url.port ? Number(url.port) : 443, sent: response.clientCert.sent }; +} + +/** + * A gate that did not send the check to its sign-in page (an API path can get a + * bare 401 where a browser gets redirected) is asked once more for the start + * page, which is what the app's web view will load, to learn the host its + * sign-in lives on. + */ +async function withLoginHost(candidate: string, gate: AuthGate, get: ProbeGet): Promise { + if (gate.loginHost || gate.kind === 'basic') return gate; + try { + const page = await get(candidate + '/'); + const found = detectAuthGate(candidate + '/', page); + return found?.loginHost ? { ...gate, loginHost: found.loginHost } : gate; + } catch { + return gate; + } +} + +export async function probeServer(input: string, get: ProbeGet): Promise { + const candidates = candidateUrls(input); + if (!candidates.length) return { ok: false, reason: 'invalid' }; + + let best: ProbeResult = { ok: false, reason: 'unreachable' }; + for (const candidate of candidates) { + let response: ProbeResponse; + try { + response = await get(candidate + FEATURES_PATH); + } catch { + continue; + } + const cert = clientCertDemand(candidate, response); + let verdict = response.status === 0 && !cert ? ({ ok: false, reason: 'unreachable' } as const) : judge(response); + if (verdict.ok) return { ok: true, url: verdict.url || candidate }; + if (cert) { + verdict = { ok: false, reason: 'clientCert', url: candidate, cert }; + } else if (verdict.reason === 'notTrek') { + const gate = detectAuthGate(candidate + FEATURES_PATH, response); + if (gate) + verdict = { ok: false, reason: 'authGate', url: candidate, gate: await withLoginHost(candidate, gate, get) }; + } + if (!best.ok && FAILURE_RANK[verdict.reason] > FAILURE_RANK[best.reason]) best = verdict; + } + return best; +} + +/** The address screen's "Try the demo": the same probe, against the public demo server. */ +export function probeDemo(get: ProbeGet): Promise { + return probeServer(DEMO_SERVER_URL, get); +} diff --git a/client/src/native/shareLink.test.ts b/client/src/native/shareLink.test.ts new file mode 100644 index 000000000..c76c46420 --- /dev/null +++ b/client/src/native/shareLink.test.ts @@ -0,0 +1,40 @@ +import { Share } from '@capacitor/share'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { isNativeApp } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { canShareLink, shareLink } from './shareLink'; + +vi.mock('@capacitor/share', () => ({ Share: { share: vi.fn() } })); +vi.mock('./platform', () => ({ isNativeApp: vi.fn() })); +vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() })); +vi.mock('../utils/fileShare', () => ({ canShareText: vi.fn(() => false) })); + +beforeEach(() => { + vi.mocked(Share.share).mockReset().mockResolvedValue({ activityType: undefined }); + vi.mocked(reportNativeFailure).mockClear(); + vi.mocked(isNativeApp).mockReturnValue(true); +}); + +describe('shareLink', () => { + it('uses the native sheet inside the app', async () => { + expect(canShareLink()).toBe(true); + expect(await shareLink('https://trek.example/s/abc', 'Trip')).toBe(true); + expect(Share.share).toHaveBeenCalledWith({ url: 'https://trek.example/s/abc', title: 'Trip', dialogTitle: 'Trip' }); + }); + + it('treats a closed sheet as no share, without a failure report', async () => { + vi.mocked(Share.share).mockRejectedValue(new Error('Share canceled')); + expect(await shareLink('https://trek.example/s/abc')).toBe(false); + expect(reportNativeFailure).not.toHaveBeenCalled(); + }); + + it('falls back to the Web Share API in a browser, and offers nothing without one', async () => { + vi.mocked(isNativeApp).mockReturnValue(false); + expect(canShareLink()).toBe(false); + const share = vi.fn(async () => {}); + vi.stubGlobal('navigator', { share }); + expect(await shareLink('https://trek.example/s/abc')).toBe(true); + expect(share).toHaveBeenCalledWith({ url: 'https://trek.example/s/abc', title: undefined }); + vi.unstubAllGlobals(); + }); +}); diff --git a/client/src/native/shareLink.ts b/client/src/native/shareLink.ts new file mode 100644 index 000000000..3b22326e9 --- /dev/null +++ b/client/src/native/shareLink.ts @@ -0,0 +1,33 @@ +import { Share } from '@capacitor/share'; +import { canShareText } from '../utils/fileShare'; +import { isNativeApp } from './platform'; +import { reportNativeFailure } from './reportFailure'; + +/** + * Handing a link to the system share sheet, the way a native app offers + * "Share…" next to "Copy": Messages, Mail, AirDrop, WhatsApp. Inside the apps + * through Capacitor's Share, in a browser through the Web Share API where it + * exists. Where neither does, `canShareLink` is false and the caller shows + * only the copy button. + */ +export function canShareLink(): boolean { + return isNativeApp() || canShareText(); +} + +/** True when a target took the link, false when the sheet was closed or failed. */ +export async function shareLink(url: string, title?: string): Promise { + try { + if (isNativeApp()) { + await Share.share({ url, title, dialogTitle: title }); + return true; + } + await navigator.share({ url, title }); + return true; + } catch (err) { + // Closing the sheet rejects too; only a real failure is worth a report. + const name = (err as { name?: string; message?: string } | null)?.name ?? ''; + const message = (err as { message?: string } | null)?.message ?? ''; + if (name !== 'AbortError' && !/cancel/i.test(message)) reportNativeFailure(err); + return false; + } +} diff --git a/client/src/native/sharedFiles.test.ts b/client/src/native/sharedFiles.test.ts new file mode 100644 index 000000000..64e268f45 --- /dev/null +++ b/client/src/native/sharedFiles.test.ts @@ -0,0 +1,90 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { hasNativeFeature } from './capabilities'; +import { linkOf, startSharedFiles, toFile, useSharedImportStore } from './sharedFiles'; +import { TrekShell } from './trekShell'; + +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn(), loadNativeCapabilities: vi.fn(async () => ({})) })); +vi.mock('./trekShell', () => ({ + TrekShell: { addListener: vi.fn(async () => ({ remove: async () => {} })), takeSharedFile: vi.fn() }, + isUnimplemented: () => false, +})); + +const PDF = { name: 'booking.pdf', mimeType: 'application/pdf', data: btoa('%PDF-1.4 hello') }; + +beforeEach(() => { + useSharedImportStore.setState({ file: null, tripId: null, link: null }); + vi.mocked(hasNativeFeature).mockReturnValue(true); + vi.mocked(TrekShell.takeSharedFile).mockReset().mockResolvedValue({ file: null }); +}); + +describe('shared booking documents', () => { + it('turns the base64 the native side sends into a File', async () => { + const file = toFile(PDF); + expect(file.name).toBe('booking.pdf'); + expect(file.type).toBe('application/pdf'); + expect(await file.text()).toBe('%PDF-1.4 hello'); + }); + + it('picks up a document shared before the UI ran, and the next ones as they come', async () => { + vi.mocked(TrekShell.takeSharedFile).mockResolvedValue({ file: PDF }); + await startSharedFiles(); + expect(useSharedImportStore.getState().file?.name).toBe('booking.pdf'); + + const listener = vi.mocked(TrekShell.addListener).mock.calls[0][1] as unknown as (p: typeof PDF) => void; + listener({ ...PDF, name: 'train.ics', mimeType: 'text/calendar' }); + expect(useSharedImportStore.getState().file?.name).toBe('train.ics'); + }); + + it('hands the file over once a trip is picked, and empties the queue', () => { + useSharedImportStore.getState().setFile(toFile(PDF)); + useSharedImportStore.getState().chooseTrip(7); + expect(useSharedImportStore.getState().tripId).toBe(7); + expect(useSharedImportStore.getState().take()?.name).toBe('booking.pdf'); + expect(useSharedImportStore.getState()).toMatchObject({ file: null, tripId: null }); + }); + + it('takes the trip the share sheet already picked', async () => { + vi.mocked(TrekShell.takeSharedFile).mockResolvedValue({ file: { ...PDF, tripId: 12 } }); + await startSharedFiles(); + expect(useSharedImportStore.getState()).toMatchObject({ tripId: 12 }); + expect(useSharedImportStore.getState().file?.name).toBe('booking.pdf'); + }); + + it('keeps the address of a shared page, and holds the picked trip back until the link is decided on', async () => { + const page = { name: 'hotel.html', mimeType: 'text/html', data: btoa('') }; + vi.mocked(TrekShell.takeSharedFile).mockResolvedValue({ + file: { ...page, tripId: 12, url: 'https://hotel.example/stay', title: 'Hotel Kanra' }, + }); + await startSharedFiles(); + expect(useSharedImportStore.getState()).toMatchObject({ + tripId: null, + link: { url: 'https://hotel.example/stay', title: 'Hotel Kanra', presetTripId: 12 }, + }); + }); + + it('takes http(s) links only, titled by the host when the page has none', () => { + const base = { name: 'link.url', mimeType: 'text/uri-list', data: '' }; + expect(linkOf({ ...base, url: 'https://maps.app.goo.gl/x' })).toEqual({ + url: 'https://maps.app.goo.gl/x', + title: 'maps.app.goo.gl', + presetTripId: null, + }); + expect(linkOf({ ...base, url: 'javascript:alert(1)' })).toBeNull(); + expect(linkOf({ ...base, url: 'not a url' })).toBeNull(); + expect(linkOf(base)).toBeNull(); + }); + + it('forgets the link along with the file', () => { + useSharedImportStore.getState().setFile(toFile(PDF), { url: 'https://a.example/', title: 'A', presetTripId: null }); + useSharedImportStore.getState().setFile(null, { url: 'https://a.example/', title: 'A', presetTripId: null }); + expect(useSharedImportStore.getState().link).toBeNull(); + }); + + it('does nothing in a binary without the feature', async () => { + vi.mocked(hasNativeFeature).mockReturnValue(false); + vi.mocked(TrekShell.addListener).mockClear(); + await startSharedFiles(); + expect(TrekShell.addListener).not.toHaveBeenCalled(); + expect(TrekShell.takeSharedFile).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/native/sharedFiles.ts b/client/src/native/sharedFiles.ts new file mode 100644 index 000000000..4e5faf701 --- /dev/null +++ b/client/src/native/sharedFiles.ts @@ -0,0 +1,103 @@ +import { create } from 'zustand'; +import { collabApi } from '../api/client'; +import { hasNativeFeature, loadNativeCapabilities } from './capabilities'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell, isUnimplemented, type SharedFilePayload } from './trekShell'; + +/** + * What was shared to TREK: a booking document ("Open in TREK" on a PDF, a + * calendar entry, a Wallet pass or a mail), or a web page or link. The native + * side hands it over as base64 (TrekShell.takeSharedFile and the sharedFile + * event); here it becomes a File waiting for a trip: NativeImportSheet asks + * which one, and the trip's booking import opens with the file already chosen + * (BookingImportModal). A page or a link also carries its address, and the + * sheet asks first whether it goes to the trip's links or is read as a booking. + */ + +/** A shared page or link, which can be kept among a trip's links. */ +export interface SharedLink { + url: string; + title: string; + /** The trip the share sheet picked for it, held back until it is clear what to do with the link. */ + presetTripId: number | null; +} + +interface SharedImportState { + file: File | null; + /** The trip whose booking import takes the file; the planner of that trip takes it from here. */ + tripId: number | null; + link: SharedLink | null; + setFile: (file: File | null, link?: SharedLink | null) => void; + chooseTrip: (tripId: number) => void; + /** The booking import took the file: the queue is empty again. */ + take: () => File | null; +} + +export const useSharedImportStore = create((set, get) => ({ + file: null, + tripId: null, + link: null, + setFile: (file, link = null) => set({ file, tripId: null, link: file ? link : null }), + chooseTrip: (tripId) => set({ tripId }), + take: () => { + const { file } = get(); + set({ file: null, tripId: null, link: null }); + return file; + }, +})); + +export function toFile(payload: SharedFilePayload): File { + const binary = atob(payload.data); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return new File([bytes], payload.name || 'booking', { type: payload.mimeType || 'application/octet-stream' }); +} + +/** The link a payload carries: an http(s) address only, titled by the page or its host. */ +export function linkOf(payload: SharedFilePayload): SharedLink | null { + const raw = payload.url?.trim(); + if (!raw) return null; + let url: URL; + try { + url = new URL(raw); + } catch { + return null; + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') return null; + const title = payload.title?.trim() || url.host; + return { + url: url.href, + title: title.slice(0, 200), + presetTripId: typeof payload.tripId === 'number' ? payload.tripId : null, + }; +} + +/** + * Keeps a shared link among the trip's links (Collaboration, Links), titled as + * the page is. Online only, like adding a link in the app: the caller says so + * when it fails. The trip's other members get it live over the WebSocket. + */ +export async function saveSharedLink(tripId: number, link: SharedLink): Promise { + await collabApi.createLink(tripId, { title: link.title, url: link.url }); +} + +/** Picks up a document shared before the UI ran, and listens for the next ones. */ +export async function startSharedFiles(): Promise { + await loadNativeCapabilities(); + if (!hasNativeFeature('sharedFiles')) return; + const accept = (payload: SharedFilePayload | null) => { + if (!payload?.data) return; + const store = useSharedImportStore.getState(); + const link = linkOf(payload); + store.setFile(toFile(payload), link); + // The share sheet asked for the trip already; NativeImportSheet opens it. A link + // keeps that trip in hand instead, until the sheet knows what to do with it. + if (!link && typeof payload.tripId === 'number') store.chooseTrip(payload.tripId); + }; + void TrekShell.addListener('sharedFile', accept); + try { + accept((await TrekShell.takeSharedFile()).file); + } catch (err) { + if (!isUnimplemented(err)) reportNativeFailure(err); + } +} diff --git a/client/src/native/tileCache.test.ts b/client/src/native/tileCache.test.ts new file mode 100644 index 000000000..432fb0fbb --- /dev/null +++ b/client/src/native/tileCache.test.ts @@ -0,0 +1,73 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { hasNativeFeature } from './capabilities'; +import { isNativeApp, isNativeIos } from './platform'; +import { mapboxTileCacheRequest, nativeRasterTemplate, tileCacheActive, toTileCacheUrl } from './tileCache'; + +vi.mock('./platform', () => ({ isNativeIos: vi.fn(), isNativeApp: vi.fn() })); +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() })); +// The mechanism is what is tested here; whether the GL maps use it is glSchemes.ts's switch. +vi.mock('./glSchemes', () => ({ GL_MAPS_THROUGH_APP_SCHEMES: true })); + +beforeEach(() => { + vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(isNativeApp).mockReturnValue(true); + vi.mocked(hasNativeFeature).mockReturnValue(true); +}); + +describe('tileCache', () => { + it('is on only in an app binary that has the store', () => { + expect(tileCacheActive()).toBe(true); + vi.mocked(hasNativeFeature).mockReturnValue(false); + expect(tileCacheActive()).toBe(false); + vi.mocked(hasNativeFeature).mockReturnValue(true); + vi.mocked(isNativeIos).mockReturnValue(false); + vi.mocked(isNativeApp).mockReturnValue(false); + expect(tileCacheActive()).toBe(false); + }); + + it('on Android keeps the store but leaves every URL as it is: the WebView client takes the requests', () => { + vi.mocked(isNativeIos).mockReturnValue(false); + expect(tileCacheActive()).toBe(true); + expect(nativeRasterTemplate('https://{s}.tiles.example.com/{z}/{x}/{y}.png')).toBe( + 'https://{s}.tiles.example.com/{z}/{x}/{y}.png' + ); + expect(mapboxTileCacheRequest('https://a.tiles.mapbox.com/v4/x/1/2/3.vector.pbf', 'Tile').url).toBe( + 'https://a.tiles.mapbox.com/v4/x/1/2/3.vector.pbf' + ); + }); + + it('swaps only the scheme, so the store knows where the tile lives', () => { + expect(toTileCacheUrl('https://a.tile.example.com/1/2/3.png?k=v')).toBe( + 'trek-tile://a.tile.example.com/1/2/3.png?k=v' + ); + expect(toTileCacheUrl('http://insecure.example.com/x')).toBe('http://insecure.example.com/x'); + }); + + it('routes Leaflet raster templates through the store only where there is one', () => { + expect(nativeRasterTemplate('https://{s}.tiles.example.com/{z}/{x}/{y}.png')).toBe( + 'trek-tile://{s}.tiles.example.com/{z}/{x}/{y}.png' + ); + vi.mocked(hasNativeFeature).mockReturnValue(false); + expect(nativeRasterTemplate('https://{s}.tiles.example.com/{z}/{x}/{y}.png')).toBe( + 'https://{s}.tiles.example.com/{z}/{x}/{y}.png' + ); + }); + + it('sends what a Mapbox map draws through the store, never its telemetry', () => { + expect( + mapboxTileCacheRequest('https://api.mapbox.com/styles/v1/mapbox/streets-v12?access_token=pk', 'Style').url + ).toBe('trek-tile://api.mapbox.com/styles/v1/mapbox/streets-v12?access_token=pk'); + expect(mapboxTileCacheRequest('https://a.tiles.mapbox.com/v4/x/1/2/3.vector.pbf', 'Tile').url).toMatch( + /^trek-tile:/ + ); + expect(mapboxTileCacheRequest('https://events.mapbox.com/events/v2', 'Unknown').url).toBe( + 'https://events.mapbox.com/events/v2' + ); + expect(mapboxTileCacheRequest('https://api.mapbox.com/map-sessions/v1', 'Unknown').url).toBe( + 'https://api.mapbox.com/map-sessions/v1' + ); + expect(mapboxTileCacheRequest('https://tiles.openfreemap.org/planet/1/2/3.pbf', 'Tile').url).toBe( + 'https://tiles.openfreemap.org/planet/1/2/3.pbf' + ); + }); +}); diff --git a/client/src/native/tileCache.ts b/client/src/native/tileCache.ts new file mode 100644 index 000000000..879b3a64a --- /dev/null +++ b/client/src/native/tileCache.ts @@ -0,0 +1,73 @@ +import { hasNativeFeature } from './capabilities'; +import { GL_MAPS_THROUGH_APP_SCHEMES } from './glSchemes'; +import { isNativeApp, isNativeIos } from './platform'; + +/** + * The iOS app's own tile store (TrekTileSchemeHandler.swift), reached through + * the trek-tile:// scheme. + * + * WKWebView runs no service worker for a self-hosted server, so on iOS nothing + * kept the map tiles a user had looked at. Binaries that report the tileCache + * feature serve every trek-tile:// request from a store on disk, filled as the + * tiles are viewed and kept for at most 30 days (Mapbox's limit for a device + * cache, applied to every provider alike), and from the network otherwise. The + * URL keeps its host and path, only the scheme changes, so the handler knows + * where the tile really lives. + * + * Nothing is prefetched through here: Mapbox forbids bulk downloads, and the + * OpenFreeMap region a trip stores goes through Cache Storage (offlineTiles.ts). + */ +const TILE_CACHE_SCHEME = 'trek-tile'; + +/** + * Whether the app keeps the Mapbox map's resources itself, so a Mapbox map works + * offline where it was viewed. On Android the app's WebView client takes those + * requests as they are (tiles/TrekTileStore.kt), so only iOS rewrites URLs. + */ +export function tileCacheActive(): boolean { + return isNativeApp() && hasNativeFeature('tileCache'); +} + +/** Whether a GL map keeps what it showed in the store (see glSchemes.ts for why not, for now). */ +export function glTileStoreActive(): boolean { + return GL_MAPS_THROUGH_APP_SCHEMES && tileSchemeActive(); +} + +/** Whether URLs go through the trek-tile:// scheme: the iOS store only. */ +function tileSchemeActive(): boolean { + return isNativeIos() && hasNativeFeature('tileCache'); +} + +/** https://host/path?query -> trek-tile://host/path?query. Anything else stays. */ +export function toTileCacheUrl(url: string): string { + return url.startsWith('https://') ? `${TILE_CACHE_SCHEME}://${url.slice('https://'.length)}` : url; +} + +/** A raster tile template for Leaflet, through the store where the app has one. */ +export function nativeRasterTemplate(template: string): string { + return tileSchemeActive() ? toTileCacheUrl(template) : template; +} + +const MAPBOX_HOST = /^https:\/\/(?:api\.mapbox\.com|[a-z0-9-]+\.tiles\.mapbox\.com)\//i; +/** What a map draws; telemetry and anything else keeps going straight out. */ +const CACHED_RESOURCES = new Set([ + 'Style', + 'Source', + 'Tile', + 'Glyphs', + 'SpriteImage', + 'SpriteJSON', + 'Image', + 'Iconset', + 'Model', +]); + +/** + * Mapbox GL's transformRequest for the iOS app: the map's own resources from + * Mapbox's servers go through the store, events and sessions never do. + */ +export function mapboxTileCacheRequest(url: string, resourceType?: string): { url: string } { + if (!glTileStoreActive() || !MAPBOX_HOST.test(url)) return { url }; + if (resourceType && !CACHED_RESOURCES.has(resourceType)) return { url }; + return { url: toTileCacheUrl(url) }; +} diff --git a/client/src/native/touchInput.test.ts b/client/src/native/touchInput.test.ts new file mode 100644 index 000000000..cf66bd347 --- /dev/null +++ b/client/src/native/touchInput.test.ts @@ -0,0 +1,56 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { TOUCH_INPUT_ATTR, trackTouchInput } from './touchInput'; + +const root = document.documentElement; +let stop: (() => void) | null = null; + +afterEach(() => { + stop?.(); + stop = null; +}); + +function pointer(type: string, pointerType: string) { + const e = new Event(type, { bubbles: true }) as PointerEvent; + Object.defineProperty(e, 'pointerType', { value: pointerType }); + window.dispatchEvent(e); +} + +describe('trackTouchInput', () => { + it('starts as touch and follows the pointer that was used last', () => { + stop = trackTouchInput(); + expect(root.hasAttribute(TOUCH_INPUT_ATTR)).toBe(true); + pointer('pointermove', 'mouse'); + expect(root.hasAttribute(TOUCH_INPUT_ATTR)).toBe(false); + pointer('pointerdown', 'touch'); + expect(root.hasAttribute(TOUCH_INPUT_ATTR)).toBe(true); + pointer('pointerdown', 'pen'); + expect(root.hasAttribute(TOUCH_INPUT_ATTR)).toBe(true); + }); + + it('keeps the mouseover a tap makes up from reaching any handler', () => { + stop = trackTouchInput(); + const el = document.createElement('button'); + document.body.appendChild(el); + const seen = vi.fn(); + el.addEventListener('mouseover', seen); + el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + expect(seen).not.toHaveBeenCalled(); + + pointer('pointermove', 'mouse'); + el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + expect(seen).toHaveBeenCalledTimes(1); + el.remove(); + }); + + it('takes everything back when stopped', () => { + stop = trackTouchInput(); + stop(); + stop = null; + expect(root.hasAttribute(TOUCH_INPUT_ATTR)).toBe(false); + const seen = vi.fn(); + document.body.addEventListener('mouseover', seen); + document.body.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + expect(seen).toHaveBeenCalledTimes(1); + document.body.removeEventListener('mouseover', seen); + }); +}); diff --git a/client/src/native/touchInput.ts b/client/src/native/touchInput.ts new file mode 100644 index 000000000..4ef19574a --- /dev/null +++ b/client/src/native/touchInput.ts @@ -0,0 +1,58 @@ +/** + * Whether a finger or a pointer drives the app right now, for the styles that + * only make sense with one of them. + * + * After a tap, iOS and Android send the mouse events a mouse would have sent: + * mouseover first, which React reads as onMouseEnter, and WebKit sets :hover on + * the tapped element. Neither is ever taken back by a mouseout, so the tint a + * hover gives stays on the button until the next tap lands elsewhere, and on a + * phone that reads as a web page. While a finger is in use carries + * data-touch-input: the build guards every :hover rule with it + * (postcss/touchHover.js), and the made-up mouseover and mouseout stop here + * before any handler sees them. A real pointer (an iPad trackpad or mouse) + * clears the mark on its first move, and hover works as on a computer. + * + * Only the app calls this. In a browser a tablet keeps tap-to-hover, which is + * how its users reach controls that show on hover. + */ + +export const TOUCH_INPUT_ATTR = 'data-touch-input'; + +export function trackTouchInput(root: HTMLElement = document.documentElement, win: Window = window): () => void { + const setTouch = (on: boolean) => { + if (on === root.hasAttribute(TOUCH_INPUT_ATTR)) return; + if (on) root.setAttribute(TOUCH_INPUT_ATTR, ''); + else root.removeAttribute(TOUCH_INPUT_ATTR); + }; + // A phone starts with a finger; a trackpad says otherwise as soon as it moves. + setTouch(true); + + const onPointerDown = (e: PointerEvent) => setTouch(e.pointerType !== 'mouse'); + const onPointerMove = (e: PointerEvent) => { + if (e.pointerType === 'mouse') setTouch(false); + }; + // Captured on the window, ahead of React's listener on the root and of every element's. + const swallow = (e: Event) => { + if (root.hasAttribute(TOUCH_INPUT_ATTR)) e.stopImmediatePropagation(); + }; + // WebKit applies :active on a phone only where a touchstart listener exists. + const noop = () => {}; + + const opts = { capture: true, passive: true } as const; + win.addEventListener('pointerdown', onPointerDown, opts); + win.addEventListener('pointerover', onPointerMove, opts); + win.addEventListener('pointermove', onPointerMove, opts); + win.addEventListener('mouseover', swallow, true); + win.addEventListener('mouseout', swallow, true); + win.document.addEventListener('touchstart', noop, { passive: true }); + + return () => { + win.removeEventListener('pointerdown', onPointerDown, opts); + win.removeEventListener('pointerover', onPointerMove, opts); + win.removeEventListener('pointermove', onPointerMove, opts); + win.removeEventListener('mouseover', swallow, true); + win.removeEventListener('mouseout', swallow, true); + win.document.removeEventListener('touchstart', noop); + root.removeAttribute(TOUCH_INPUT_ATTR); + }; +} diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts new file mode 100644 index 000000000..ea5670079 --- /dev/null +++ b/client/src/native/trekShell.ts @@ -0,0 +1,371 @@ +import { registerPlugin } from '@capacitor/core'; +import type { NativeCapabilities } from './capabilities'; + +/** + * The app's own native plugin, implemented in + * ios/App/App/TrekShellPlugin.swift and + * android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java. + * + * The app is a frame around the UI the user's server delivers, so what the + * web side needs from it is small: which server that is, a way to change it, + * a system browser for the sign-ins a WebView cannot do, and on iOS the + * offline copy of the start page that stands in for the missing service + * worker. + */ +export interface TrekShellPlugin { + /** + * `previousUrl`: the server this app remembered before an update asked for a + * newer one (SERVER_CHECK in TrekServerStore). Set only while no server is, + * so the address screen can check it again, pre-filled. + */ + /** + * The server picked, the one before an update asked to check it again, and + * why its page did not load last time (taken once; builds before 5.1.4 leave + * it out). + */ + getServer(): Promise<{ url: string | null; previousUrl?: string | null; failure?: string | null }>; + /** + * Remembers the server and loads it. The current page is gone afterwards. + * `signInHosts` are the hosts of a proxy's sign-in page in front of it + * (authGate.ts): only they may load in the web view besides the server. + * `welcome` is the one-time code of a TREK Cloud purchase: the first load + * opens the server's welcome page with it, which signs the buyer in. A build + * without this option ignores it and opens the server as usual. + * `labels` are the words of the bar the app shows over a proxy's sign-in page, + * or over an error page in place of the server's (a proxy's block page), in the + * user's language: the server's UI is not there to say them. + */ + setServer(options: { + url: string; + signInHosts?: string[]; + welcome?: string; + labels?: { signInHint: string; changeServer: string; errorPageHint?: string }; + }): Promise; + /** Forgets the server and returns to the address screen. */ + resetServer(): Promise; + /** Loads the remembered server again, after it could not be reached. */ + reload(): Promise; + /** + * Opens `url` in the system browser and resolves with the URL it was sent + * back to under `callbackScheme`. Rejects with code `CANCELLED` when the + * user closes the browser. + */ + authenticate(options: { url: string; callbackScheme: string }): Promise<{ url: string }>; + /** + * Android: a return to the sign-in scheme that found no authenticate() call + * waiting, because the app was started anew meanwhile. Handed out once, and + * only for two minutes, as long as the server keeps its code. Not in iOS builds, nor in Android builds before 5.1.4. + */ + takeAuthCallback(): Promise<{ url: string | null }>; + /** + * Stores the server's start page for a start without the server. Android + * also downloads the build's `files` the copy does not hold yet (an Android + * build before the offline copy resolves `saved: false`); iOS keeps those in + * WebKit's HTTP cache instead and ignores them. + */ + refreshOfflineCopy(options?: { files?: string[] }): Promise<{ saved: boolean; complete?: boolean }>; + /** Starts on that copy under the server's origin. False when there is none. */ + openOfflineCopy(): Promise<{ opened: boolean }>; + /** What this binary offers the UI (native/capabilities.ts). Missing before shell API 2. */ + getCapabilities(): Promise; + /** Feature tileCache: what the map tile store takes on disk, and its limit (iOS: every map; Android: Mapbox's). */ + getTileCacheUsage(): Promise<{ bytes: number; limit: number }>; + /** Feature tileCache: empties the map tile store. */ + clearTileCache(): Promise; + /** Feature biometricLock: which biometry the device offers for the app lock. */ + biometryInfo(): Promise<{ available: boolean; type: string }>; + /** Feature biometricLock: Face ID, Touch ID or the passcode. Rejects with CANCELLED or FAILED. */ + authenticateBiometric(options: { reason: string }): Promise<{ ok: true }>; + /** Feature biometricLock: a blurred cover in the app switcher while the lock is on. */ + setPrivacyCover(options: { enabled: boolean }): Promise; + /** Feature geolocation: starts the native location stream (the "location" event). */ + startLocation(options: { highAccuracy: boolean }): Promise; + stopLocation(): Promise; + addListener( + event: 'location', + listener: (payload: NativeLocationPayload) => void + ): Promise<{ remove: () => Promise }>; + addListener( + event: 'sharedFile', + listener: (payload: SharedFilePayload) => void + ): Promise<{ remove: () => Promise }>; + /** Feature sharedFiles: the booking document shared to TREK before the UI ran. */ + takeSharedFile(): Promise<{ file: SharedFilePayload | null }>; + /** Feature nativePush: permission, APNs and the device keys, as a Web Push subscription. Rejects with DENIED. */ + registerPush(): Promise<{ endpoint: string; keys: { p256dh: string; auth: string } }>; + /** Feature nativePush: the notification the app was opened from, before the UI ran. */ + takeOpenedPush(): Promise<{ url: string | null }>; + /** Feature widgets: what the home-screen widget shows (native/widgets.ts), as JSON. */ + /** Feature widgetTrips adds `key`: "trip." for one trip's snapshot, "trips" for the list a widget picks from. */ + setWidgetSnapshot(options: { json: string; key?: string }): Promise; + /** Feature liveActivity: starts the travel day's Live Activity, or updates the running one. */ + syncTripDay(options: { + tripTitle: string; + path: string; + dayLabel: string; + nextName: string; + nextTime?: string; + done: number; + total: number; + /** Android: minutes after midnight of the next stop, for the countdown in the Live Update. */ + nextMinutes?: number; + /** Android: each stop's colour (#rrggbb) for the Live Update's segments. */ + colors?: (string | null)[]; + /** iOS: the day's flight near or in the air, drawn as a boarding pass; older binaries ignore it. */ + flight?: { + number: string; + from: string; + to: string; + dep: number; + arr: number; + depTime: string; + arrTime: string; + delay?: number; + airborne?: boolean; + }; + }): Promise<{ running: boolean }>; + endTripDay(): Promise; + /** Feature storeKit (iOS) or playBilling (Android): the store's price strings for the products it knows. */ + storeProducts(options: { + ids: string[]; + }): Promise<{ products: { id: string; displayPrice: string }[]; sandbox?: boolean }>; + /** + * The purchase sheet. Set when bought: on iOS `jws`, the signed transaction; on + * Android `purchaseToken`, which the control plane verifies with Google Play. + */ + storePurchase(options: { productId: string }): Promise<{ + /** `subscribed`: this store account already holds a delivered subscription, so nothing was bought. */ + kind: 'bought' | 'cancelled' | 'pending' | 'failed' | 'subscribed'; + jws?: string; + purchaseToken?: string; + productId?: string; + transactionId?: string; + }>; + /** Marks a purchase delivered once its instance exists (Android: acknowledges it with Google Play). */ + storeFinish(options: { transactionId: string }): Promise; + /** iOS, feature wallet: adds a .pkpass (base64) to Apple Wallet, or opens it there when it is already in. */ + addToWallet(options: { data: string }): Promise<{ result: 'added' | 'opened' | 'cancelled' }>; + /** + * Shows a file written to the app's cache (a file:// path) in the system's + * viewer: Quick Look on iOS, the app that views the type on Android. Feature + * "filePreview"; "unsupported" where nothing on the device shows the type. + */ + previewFile(options: { + path: string; + mimeType: string; + title?: string; + }): Promise<{ result: 'shown' | 'unsupported' }>; + /** iOS, feature storeKit: the newest active subscription under `prefix` on this Apple ID, if any. */ + storeRestore(options: { prefix: string }): Promise<{ jws?: string; transactionId?: string }>; + /** + * Whether this Apple ID or Google account holds a delivered subscription under + * `prefix`, read without asking for a password. Not in builds before 5.1.4. + */ + storeHeld(options: { prefix: string }): Promise<{ held: boolean }>; + /** Feature watch: what the Apple Watch app shows (native/watch.ts), as JSON, sent on through WatchConnectivity. */ + setWatchSnapshot(options: { json: string }): Promise; + /** Feature watch: the ticks the watch sent since the last call, oldest first (parsed by parseWatchActions). */ + takeWatchActions(): Promise<{ actions: unknown[] }>; + /** Feature watch: the watch sent a tick; takeWatchActions has it. */ + addListener(event: 'watchAction', listener: () => void): Promise<{ remove: () => Promise }>; + addListener( + event: 'pushOpened', + listener: (payload: { url: string }) => void + ): Promise<{ remove: () => Promise }>; + /** Android, feature googleWallet: opens a Google Wallet save link (https://pay.google.com/gp/v/save/...). */ + addToGoogleWallet(options: { url: string }): Promise<{ result: 'opened' }>; + /** Android, feature windowLayout: the window's size classes and a foldable's posture and hinge. */ + getWindowLayout(): Promise; + /** + * Feature clientCertificate: a GET against the user's server for the address + * screen, made natively. It shows the stored client certificate to that server + * when asked and reports whether the server asked (`certRequested`) and got + * one (`certSent`). A failed connection resolves with status 0. + */ + requestServer(options: { url: string; timeoutMs?: number }): Promise; + /** + * Feature clientCertificate: the stored client certificate, or null, and the + * last server that asked for one while the app ran (`served`: it got one). + */ + clientCertificate(): Promise<{ + certificate: ClientCertificateInfo | null; + request?: { host: string; port: number; served: boolean }; + }>; + /** + * Feature clientCertificate: picks a .p12/.pfx file, asks for its password + * (with `labels`, the UI's words) until it opens, and keeps it for the server + * at host and port, replacing any other. + */ + importClientCertificate(options: { + host: string; + port: number; + labels: ClientCertificateLabels; + }): Promise; + /** Feature clientCertificate: forgets the stored client certificate. */ + removeClientCertificate(): Promise; + addListener( + event: 'windowLayout', + listener: (payload: NativeWindowLayout) => void + ): Promise<{ remove: () => Promise }>; + /** Android, feature playBilling: a paid subscription never delivered (cleared while the app was closed). */ + storeUnfinished(options: { prefix: string }): Promise; + /** Android, feature playBilling: a pending payment cleared while the app runs. */ + addListener( + event: 'storeTransaction', + listener: (payload: StoreRestoreResult) => void + ): Promise<{ remove: () => Promise }>; + /** + * Feature keyCommands (iOS, Android): the shortcuts a hardware keyboard has right now, + * with their names in the UI's language. The app lists them in the overlay a + * held Command key shows and in the iPadOS menu bar, Android in its + * keyboard shortcuts list. + */ + setKeyCommands(options: { commands: NativeKeyCommand[] }): Promise; + /** Feature keyCommands: one of those shortcuts was pressed. */ + addListener( + event: 'keyCommand', + listener: (payload: { id: string }) => void + ): Promise<{ remove: () => Promise }>; + /** Feature quickActions (iOS): the actions a long press on the app icon shows, in the UI's language. */ + setQuickActions(options: { items: NativeQuickAction[] }): Promise; + /** + * Feature quickActions: the action the app was launched with, before the UI ran. + * With the feature appLinks also a widget or Live Activity tap, as its path. + */ + takeQuickAction(): Promise<{ path: string | null }>; + /** Feature quickActions: an action chosen (with appLinks: a widget tapped) while the app was running. */ + addListener( + event: 'quickAction', + listener: (payload: { path: string }) => void + ): Promise<{ remove: () => Promise }>; +} + +/** One quick action on the app icon: what it says, and the path in the UI it opens. */ +export interface NativeQuickAction { + /** Stable name, e.g. "newTrip". */ + type: string; + title: string; + subtitle?: string; + /** 'add' or 'trip'. */ + icon: 'add' | 'trip'; + /** A path of this server's UI, starting with "/". */ + path: string; +} + +/** What Google Play Billing answers a restore with (Android, feature playBilling), beside iOS's `jws`. */ +export interface StoreRestoreResult { + jws?: string; + purchaseToken?: string; + productId?: string; + transactionId?: string; +} + +/** A keyboard shortcut as the app registers it (UIKeyCommand on iOS, a KeyboardShortcutInfo on Android). */ +export interface NativeKeyCommand { + id: string; + title: string; + /** The key: a character, or one of 'left', 'right', 'up', 'down', 'escape'. */ + input: string; + /** Any of 'command', 'shift', 'option', 'control'. */ + modifiers: string[]; +} + +/** A document shared to TREK, as the native side reads it. */ +export interface SharedFilePayload { + name: string; + mimeType: string; + /** base64 */ + data: string; + /** Set when the share sheet already asked which trip it belongs to (feature shareSheet). */ + tripId?: number; + /** The http(s) address of a shared page or link, which can go to the trip's links instead. */ + url?: string; + /** The page's title, for that link. */ + title?: string; +} + +/** + * The window as the Android app sees it (feature windowLayout): its size in CSS + * pixels, Android's size classes, and a foldable's posture with the hinge's + * place in the window. `posture` is none on a device without a fold. + */ +export interface NativeWindowLayout { + width: number; + height: number; + widthClass: 'compact' | 'medium' | 'expanded'; + heightClass: 'compact' | 'medium' | 'expanded'; + posture: 'none' | 'flat' | 'halfOpened'; + orientation?: 'vertical' | 'horizontal'; + separating?: boolean; + occluding?: boolean; + /** The fold's rectangle on the screen, in CSS pixels: geometry, not text sides. */ + hinge?: Pick; +} + +/** A position, or an error shaped like GeolocationPositionError (1 denied, 2 unavailable). */ +export type NativeLocationPayload = + | { + latitude: number; + longitude: number; + accuracy: number; + altitude: number | null; + speed: number | null; + heading: number | null; + timestamp: number; + error?: undefined; + } + | { error: { code: number; message: string } }; + +interface NativeServerResponse { + status: number; + data: unknown; + url: string; + headers?: Record; + certRequested: boolean; + certSent: boolean; + /** host:port of the server that asked. */ + certHost?: string; + /** Why the connection failed, when status is 0. */ + error?: string; +} + +export interface ClientCertificateInfo { + host: string; + port: number; + /** The certificate's common name. */ + subject: string; + /** The issuer's common name. */ + issuer: string; + /** Expiry, in milliseconds since 1970. */ + notAfter: number; +} + +export interface ClientCertificateLabels { + title: string; + message: string; + placeholder: string; + ok: string; + cancel: string; + wrongPassword: string; +} + +export type ClientCertificateFailure = 'format' | 'no_key' | 'expired' | 'not_yet_valid' | 'store'; + +export interface ClientCertificateImport { + result: 'imported' | 'cancelled' | 'failed'; + failure?: ClientCertificateFailure; + certificate?: ClientCertificateInfo; +} + +export const TrekShell = registerPlugin('TrekShell'); + +export const APP_URL_SCHEME = 'com.liketrek.trek'; + +/** + * True for the rejection Capacitor gives when the installed app has no such + * native method: the UI comes from the server, so a newer server can call into + * an app binary that predates the method. + */ +export function isUnimplemented(err: unknown): boolean { + return typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'UNIMPLEMENTED'; +} diff --git a/client/src/native/useNativeQuestion.ts b/client/src/native/useNativeQuestion.ts new file mode 100644 index 000000000..bd2e21f47 --- /dev/null +++ b/client/src/native/useNativeQuestion.ts @@ -0,0 +1,45 @@ +import { useEffect, useRef, useState } from 'react'; +import { askNatively, canAskNatively, type NativeQuestion } from './nativeDialogs'; + +/** + * Asks `question` through the system once each time `open` turns true, and + * hands the answer to `answer`. Returns whether the caller should draw its own + * HTML dialog instead: always in a browser or an app without the plugins, and + * when the system could not ask. A null question (one the system cannot show, + * such as one with a list under it) is always asked in HTML. + */ +export function useNativeQuestion( + open: boolean, + question: NativeQuestion | null, + answer: (yes: boolean) => void +): boolean { + const native = question !== null && canAskNatively(); + const [failed, setFailed] = useState(false); + // A closed question forgets that the system failed it, so the next one is asked natively again. + const [wasOpen, setWasOpen] = useState(open); + if (open !== wasOpen) { + setWasOpen(open); + if (!open) setFailed(false); + } + // Asked once per opening, also when StrictMode runs the effect twice. + const asked = useRef(false); + const latest = useRef({ question, answer }); + useEffect(() => { + latest.current = { question, answer }; + }); + + useEffect(() => { + if (!open) { + asked.current = false; + return; + } + if (!native || asked.current || !latest.current.question) return; + asked.current = true; + void askNatively(latest.current.question).then((yes) => { + if (yes === null) setFailed(true); + else latest.current.answer(yes); + }); + }, [open, native]); + + return !native || failed; +} diff --git a/client/src/native/wallet.test.ts b/client/src/native/wallet.test.ts new file mode 100644 index 000000000..f76042d49 --- /dev/null +++ b/client/src/native/wallet.test.ts @@ -0,0 +1,215 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const env = vi.hoisted(() => ({ ios: true, android: false, wallet: true, googleWallet: false })); +const shell = vi.hoisted(() => ({ addToWallet: vi.fn(), addToGoogleWallet: vi.fn() })); +const report = vi.hoisted(() => vi.fn()); + +vi.mock('./platform', () => ({ isNativeIos: () => env.ios, isNativeAndroid: () => env.android })); +vi.mock('./capabilities', () => ({ + hasNativeFeature: (name: string) => + (name === 'wallet' && env.wallet) || (name === 'googleWallet' && env.googleWallet), +})); +vi.mock('./trekShell', () => ({ TrekShell: shell })); +vi.mock('./reportFailure', () => ({ reportNativeFailure: report })); + +import { + _resetGoogleWalletAvailability, + addReservationToGoogleWallet, + addReservationToWallet, + addToWallet, + bookingWallet, + canAddToGoogleWallet, + canAddToWallet, + isWalletPassName, + loadGoogleWalletAvailability, +} from './wallet'; + +const pass = new Blob(['PK\u0003\u0004pass'], { type: 'application/vnd.apple.pkpass' }); + +beforeEach(() => { + env.ios = true; + env.android = false; + env.wallet = true; + env.googleWallet = false; + shell.addToWallet.mockReset(); + shell.addToGoogleWallet.mockReset(); + report.mockReset(); +}); + +describe('Apple Wallet', () => { + it('knows a pass by its name', () => { + expect(isWalletPassName('Boarding Pass.pkpass')).toBe(true); + expect(isWalletPassName('TICKET.PKPASS ')).toBe(true); + expect(isWalletPassName('passes.pkpasses')).toBe(false); + expect(isWalletPassName('booking.pdf')).toBe(false); + }); + + it('is offered only on iOS with the wallet feature', () => { + expect(canAddToWallet()).toBe(true); + env.wallet = false; + expect(canAddToWallet()).toBe(false); + env.wallet = true; + env.ios = false; + expect(canAddToWallet()).toBe(false); + }); + + it('hands the pass to Wallet as base64', async () => { + shell.addToWallet.mockResolvedValue({ result: 'added' }); + expect(await addToWallet(pass)).toBe(true); + const { data } = shell.addToWallet.mock.calls[0][0] as { data: string }; + expect(atob(data)).toBe('PK\u0003\u0004pass'); + }); + + it('falls back quietly for a broken pass or no Wallet, and reports anything else', async () => { + shell.addToWallet.mockRejectedValue({ code: 'INVALID' }); + expect(await addToWallet(pass)).toBe(false); + shell.addToWallet.mockRejectedValue({ code: 'UNAVAILABLE' }); + expect(await addToWallet(pass)).toBe(false); + expect(report).not.toHaveBeenCalled(); + + shell.addToWallet.mockRejectedValue(new Error('bridge gone')); + expect(await addToWallet(pass)).toBe(false); + expect(report).toHaveBeenCalledTimes(1); + }); + + it('does not touch the bridge where it cannot add a pass', async () => { + env.ios = false; + expect(await addToWallet(pass)).toBe(false); + expect(shell.addToWallet).not.toHaveBeenCalled(); + }); +}); + +describe('a booking into Wallet', () => { + const answer = (status: number) => + vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(status === 200 ? pass : '{}', { status })); + + it('fetches the booking pass in the user language and hands it to Wallet', async () => { + const fetchSpy = answer(200); + shell.addToWallet.mockResolvedValue({ result: 'added' }); + expect(await addReservationToWallet(42, 7, 'de')).toBe('added'); + expect(fetchSpy).toHaveBeenCalledWith('/api/trips/42/reservations/7/wallet-pass?lang=de', { + credentials: 'include', + }); + fetchSpy.mockRestore(); + }); + + it('tells an undated booking from a failure', async () => { + let fetchSpy = answer(422); + expect(await addReservationToWallet(42, 7, 'en')).toBe('undated'); + fetchSpy.mockRestore(); + fetchSpy = answer(502); + expect(await addReservationToWallet(42, 7, 'en')).toBe('failed'); + fetchSpy.mockRestore(); + fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('offline')); + expect(await addReservationToWallet(42, 7, 'en')).toBe('failed'); + fetchSpy.mockRestore(); + }); + + it('fails when Wallet does not take the pass', async () => { + const fetchSpy = answer(200); + shell.addToWallet.mockRejectedValue({ code: 'INVALID' }); + expect(await addReservationToWallet(42, 7, 'en')).toBe('failed'); + fetchSpy.mockRestore(); + }); +}); + +describe('Google Wallet', () => { + beforeEach(() => { + env.ios = false; + env.android = true; + env.wallet = false; + env.googleWallet = true; + _resetGoogleWalletAvailability(); + }); + + const available = (body: unknown, status = 200) => + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify(body), { status })) + ); + + it('offers no button until the server says Google Wallet works, and asks it once', async () => { + expect(bookingWallet()).toBeNull(); + available({ available: false }); + expect(await loadGoogleWalletAvailability(42)).toBe(false); + expect(bookingWallet()).toBeNull(); + available({ available: true }); + expect(await loadGoogleWalletAvailability(42)).toBe(false); + expect(fetch).not.toHaveBeenCalled(); + _resetGoogleWalletAvailability(); + expect(await loadGoogleWalletAvailability(42)).toBe(true); + expect(fetch).toHaveBeenCalledWith('/api/trips/42/reservations/google-wallet', { credentials: 'include' }); + expect(bookingWallet()).toBe('google'); + vi.unstubAllGlobals(); + }); + + it('an older server without the route, or one offline, offers none', async () => { + available({}, 404); + expect(await loadGoogleWalletAvailability(42)).toBe(false); + _resetGoogleWalletAvailability(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new Error('offline'); + }) + ); + expect(await loadGoogleWalletAvailability(42)).toBe(false); + vi.unstubAllGlobals(); + }); + + it('is offered only on Android with the googleWallet feature, and names its wallet', async () => { + expect(canAddToGoogleWallet()).toBe(true); + available({ available: true }); + await loadGoogleWalletAvailability(42); + vi.unstubAllGlobals(); + expect(bookingWallet()).toBe('google'); + env.googleWallet = false; + expect(canAddToGoogleWallet()).toBe(false); + expect(bookingWallet()).toBeNull(); + env.ios = true; + env.android = false; + env.wallet = true; + expect(bookingWallet()).toBe('apple'); + }); + + it('asks this server for the save link in the user language and opens it in the app', async () => { + const saveUrl = 'https://pay.google.com/gp/v/save/jwt'; + const fetchMock = vi.fn(async () => new Response(JSON.stringify({ saveUrl }), { status: 200 })); + vi.stubGlobal('fetch', fetchMock); + shell.addToGoogleWallet.mockResolvedValue({ result: 'opened' }); + expect(await addReservationToGoogleWallet(42, 7, 'de')).toBe('added'); + expect(fetchMock).toHaveBeenCalledWith('/api/trips/42/reservations/7/wallet-pass/google?lang=de', { + credentials: 'include', + }); + expect(shell.addToGoogleWallet).toHaveBeenCalledWith({ url: saveUrl }); + vi.unstubAllGlobals(); + }); + + it('an undated booking, a refusal or a link the app will not open is a clear outcome', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('', { status: 422 })) + ); + expect(await addReservationToGoogleWallet(42, 7, 'en')).toBe('undated'); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('', { status: 404 })) + ); + expect(await addReservationToGoogleWallet(42, 7, 'en')).toBe('failed'); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify({ saveUrl: 'x' }), { status: 200 })) + ); + shell.addToGoogleWallet.mockRejectedValue({ code: 'INVALID' }); + expect(await addReservationToGoogleWallet(42, 7, 'en')).toBe('failed'); + expect(report).not.toHaveBeenCalled(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new Error('offline'); + }) + ); + expect(await addReservationToGoogleWallet(42, 7, 'en')).toBe('failed'); + vi.unstubAllGlobals(); + }); +}); diff --git a/client/src/native/wallet.ts b/client/src/native/wallet.ts new file mode 100644 index 000000000..c58779931 --- /dev/null +++ b/client/src/native/wallet.ts @@ -0,0 +1,165 @@ +import { useEffect, useSyncExternalStore } from 'react'; +import { toBase64 } from './blobBase64'; +import { hasNativeFeature } from './capabilities'; +import { isNativeAndroid, isNativeIos } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell } from './trekShell'; + +/** A file that is a single Apple Wallet pass, by its name (the MIME type is often missing). */ +export function isWalletPassName(filename: string): boolean { + return /\.pkpass$/i.test(filename.trim()); +} + +/** Whether this app can hand a pass to Apple Wallet itself (iOS, feature wallet). */ +export function canAddToWallet(): boolean { + return isNativeIos() && hasNativeFeature('wallet'); +} + +/** + * Hands a booking's Wallet pass to Apple Wallet: the system sheet with the pass + * and "Add", or the pass opened in Wallet when it is already there. True when + * Wallet took it over (including the user closing the sheet); false when the app + * cannot, so the caller falls back to the share sheet. + */ +export async function addToWallet(blob: Blob): Promise { + if (!canAddToWallet()) return false; + try { + await TrekShell.addToWallet({ data: await toBase64(blob) }); + return true; + } catch (err) { + // INVALID (not really a pass) and UNAVAILABLE fall back to the share sheet quietly. + const code = (err as { code?: unknown })?.code; + if (code !== 'INVALID' && code !== 'UNAVAILABLE') reportNativeFailure(err); + return false; + } +} + +/** What a tap on "Add to Apple Wallet" came to. */ +export type ReservationWalletOutcome = 'added' | 'undated' | 'failed'; + +/** + * A booking's pass, made by this server (GET .../reservations/:id/wallet-pass, + * signed by the TREK services) and handed to Apple Wallet's sheet. `undated`: + * the booking has no date yet, which Wallet needs to bring the pass up. + */ +export async function addReservationToWallet( + tripId: number, + reservationId: number, + language: string +): Promise { + let response: Response; + try { + response = await fetch( + `/api/trips/${tripId}/reservations/${reservationId}/wallet-pass?lang=${encodeURIComponent(language)}`, + { credentials: 'include' } + ); + } catch { + return 'failed'; + } + if (response.status === 422) return 'undated'; + if (!response.ok) return 'failed'; + return (await addToWallet(await response.blob())) ? 'added' : 'failed'; +} + +/** Whether this app can hand a booking to Google Wallet (Android, feature googleWallet). */ +export function canAddToGoogleWallet(): boolean { + return isNativeAndroid() && hasNativeFeature('googleWallet'); +} + +/** + * Whether this server can make Google Wallet passes, asked once per session + * (GET /api/trips/:tripId/reservations/google-wallet): the TREK services can + * only once liketrek has a Wallet issuer, and an older server has no such route. + * Until it says yes the Android app offers no button, so nobody taps one that + * can only fail. + */ +let googleState: 'unknown' | 'asking' | 'yes' | 'no' = 'unknown'; +const googleListeners = new Set<() => void>(); + +function setGoogleState(next: typeof googleState): void { + googleState = next; + for (const listener of googleListeners) listener(); +} + +/** Read through a call, so a check after setGoogleState() sees the new state rather than a narrowed one. */ +function googleSaidYes(): boolean { + return googleState === 'yes'; +} + +export async function loadGoogleWalletAvailability(tripId: number): Promise { + if (!canAddToGoogleWallet()) return false; + if (googleState === 'yes' || googleState === 'no') return googleState === 'yes'; + if (googleState === 'asking') return false; + setGoogleState('asking'); + try { + const response = await fetch(`/api/trips/${tripId}/reservations/google-wallet`, { credentials: 'include' }); + const body = response.ok ? ((await response.json()) as { available?: unknown }) : {}; + setGoogleState(body.available === true ? 'yes' : 'no'); + } catch { + // Offline: ask again next time. + setGoogleState('unknown'); + } + return googleSaidYes(); +} + +/** True once this server has said Google Wallet works; asks it the first time a booking shows. */ +export function useGoogleWalletAvailable(tripId: number): boolean { + const available = useSyncExternalStore((listener) => { + googleListeners.add(listener); + return () => googleListeners.delete(listener); + }, googleSaidYes); + useEffect(() => { + void loadGoogleWalletAvailability(tripId); + }, [tripId]); + return available; +} + +/** The wallet a booking's button adds to here, if any: Apple Wallet on iOS, Google Wallet on Android where the server can. */ +export function bookingWallet(): 'apple' | 'google' | null { + if (canAddToWallet()) return 'apple'; + if (canAddToGoogleWallet() && googleState === 'yes') return 'google'; + return null; +} + +/** Test helper: forget what the server said. */ +export function _resetGoogleWalletAvailability(): void { + googleState = 'unknown'; + googleListeners.clear(); +} + +/** + * A booking as a Google Wallet pass: this server asks the TREK services for a + * save link (GET .../reservations/:id/wallet-pass/google), and the app opens it, + * where Google Wallet shows the pass with its own Save button. `undated`: the + * booking has no date yet. + */ +export async function addReservationToGoogleWallet( + tripId: number, + reservationId: number, + language: string +): Promise { + if (!canAddToGoogleWallet()) return 'failed'; + let response: Response; + try { + response = await fetch( + `/api/trips/${tripId}/reservations/${reservationId}/wallet-pass/google?lang=${encodeURIComponent(language)}`, + { credentials: 'include' } + ); + } catch { + return 'failed'; + } + if (response.status === 422) return 'undated'; + // Google Wallet went away here (switched off, issuer gone): the button goes with it. + if (response.status === 404) setGoogleState('no'); + if (!response.ok) return 'failed'; + try { + const { saveUrl } = (await response.json()) as { saveUrl?: unknown }; + if (typeof saveUrl !== 'string') return 'failed'; + await TrekShell.addToGoogleWallet({ url: saveUrl }); + return 'added'; + } catch (err) { + const code = (err as { code?: unknown })?.code; + if (code !== 'INVALID' && code !== 'UNAVAILABLE') reportNativeFailure(err); + return 'failed'; + } +} diff --git a/client/src/native/watch.test.ts b/client/src/native/watch.test.ts new file mode 100644 index 000000000..299dc5491 --- /dev/null +++ b/client/src/native/watch.test.ts @@ -0,0 +1,397 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Day, PackingItem, Place, Reservation, TodoItem, Trip } from '../types'; + +vi.mock('./platform', () => ({ isNativeIos: vi.fn(() => true) })); +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn((feature: string) => feature === 'watch') })); +vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() })); +vi.mock('./trekShell', () => ({ + TrekShell: { + setWatchSnapshot: vi.fn(async () => {}), + takeWatchActions: vi.fn(async () => ({ actions: [] as unknown[] })), + }, +})); + +import { hasNativeFeature } from './capabilities'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell } from './trekShell'; +import { + applyWatchActions, + buildWatchSnapshot, + fitWatchSnapshot, + parseWatchActions, + publishWatch, + takeWatchActions, + watchBooking, + watchDays, + watchPacking, + watchTodos, + type WatchSnapshot, +} from './watch'; +import { upcomingReservations } from './widgetExtras'; + +const trip = { id: 7, title: 'Autumn in Kyoto', start_date: '2026-11-17', end_date: '2026-11-25' } as unknown as Trip; + +const day = (id: number, n: number, date: string | null, stops: Record[]) => + ({ + id, + trip_id: 7, + day_number: n, + date, + assignments: stops.map((place, i) => ({ id: id * 10 + i, order_index: i, place })), + }) as unknown as Day; + +const reservation = (fields: Partial & { id: number; title: string; type: string }): Reservation => + ({ trip_id: 7, status: 'confirmed', ...fields }) as Reservation; + +const flight = reservation({ + id: 1, + title: 'LH 716', + type: 'flight', + reservation_time: '2026-11-17T13:05', + reservation_end_time: '2026-11-18T08:50', + confirmation_number: ' K7Q2XD ', + metadata: JSON.stringify({ airline: 'Lufthansa', flight_number: 'LH 716', seat: '42A' }), + endpoints: [ + { + role: 'to', + sequence: 1, + name: 'Tokyo Haneda', + code: 'HND', + lat: 35.5494, + lng: 139.7798, + timezone: 'Asia/Tokyo', + local_time: null, + local_date: null, + }, + { + role: 'from', + sequence: 0, + name: 'Frankfurt', + code: 'FRA', + lat: 50.0379, + lng: 8.5622, + timezone: 'Europe/Berlin', + local_time: null, + local_date: null, + }, + ], +}); + +const hotel = reservation({ + id: 2, + title: 'Hotel Kanra Kyoto', + type: 'hotel', + day_id: 2, + end_day_id: 3, + accommodation_place_id: 50, + accommodation_name: 'Hotel Kanra Kyoto', + metadata: JSON.stringify({ check_in_time: '15:00', check_out_time: '11:00' }), +}); + +const places = [{ id: 50, lat: 34.99, lng: 135.76, address: 'Kyoto' }] as unknown as Place[]; + +const days = [ + day(1, 1, '2026-11-17', []), + day(2, 2, '2026-11-18', [ + { + name: 'Fushimi Inari', + place_time: '08:30', + end_time: '10:30', + lat: 34.967146, + lng: 135.772673, + address: '68 Fukakusa', + category: { color: '#D6273B', icon: 'Landmark' }, + }, + { name: 'Nishiki Market', place_time: null, lat: null, lng: null }, + ]), + day(3, 3, '2026-11-19', []), +]; + +describe('watchDays', () => { + it('lists the days in order with their stops, coordinates and the timed bookings of their date', () => { + const bookings = [ + watchBooking(flight, { day: '2026-11-17', time: '13:05' }, { dayDates: new Map(), places: new Map() }), + ]; + const out = watchDays([days[2], days[0], days[1]], bookings); + expect(out.map((d) => d.number)).toEqual([1, 2, 3]); + expect(out[0].stops).toEqual([ + { + name: 'LH 716', + minutes: 785, + symbol: 'airplane', + booking: 'flight', + address: 'Frankfurt', + lat: 50.0379, + lng: 8.5622, + }, + ]); + expect(out[1].stops[0]).toEqual({ + name: 'Fushimi Inari', + minutes: 510, + endMinutes: 630, + symbol: 'building.columns.fill', + color: '#D6273B', + address: '68 Fukakusa', + lat: 34.96715, + lng: 135.77267, + }); + expect(out[1].stops[1]).toEqual({ name: 'Nishiki Market' }); + }); + + it('prefers the stop time set on the day over the place time', () => { + const custom = day(4, 1, '2026-11-20', []); + custom.assignments = [ + { id: 1, order_index: 0, assignment_time: '09:15', place: { name: 'Gion', place_time: '18:00' } }, + ] as unknown as Day['assignments']; + expect(watchDays([custom], [])[0].stops[0].minutes).toBe(555); + }); +}); + +describe('watchBooking', () => { + it('carries the reference, seat, carrier, both airports and the departure zone', () => { + const b = watchBooking(flight, { day: '2026-11-17', time: '13:05' }, { dayDates: new Map(), places: new Map() }); + expect(b).toMatchObject({ + id: 1, + kind: 'flight', + confirmed: true, + date: '2026-11-17', + time: '13:05', + endDate: '2026-11-18', + endTime: '08:50', + zone: 'Europe/Berlin', + endZone: 'Asia/Tokyo', + code: 'K7Q2XD', + carrier: 'Lufthansa LH 716', + seat: '42A', + from: { name: 'Frankfurt', code: 'FRA' }, + to: { name: 'Tokyo Haneda', code: 'HND' }, + }); + }); + + it('gives a stay its check-in, check-out, dates from its days and the hotel as the place to go', () => { + const dayDates = new Map([ + [2, '2026-11-18'], + [3, '2026-11-19'], + ]); + const b = watchBooking(hotel, { day: '2026-11-18', time: null }, { dayDates, places: new Map([[50, places[0]]]) }); + expect(b).toMatchObject({ + kind: 'hotel', + time: '15:00', + endDate: '2026-11-19', + endTime: '11:00', + checkIn: '15:00', + checkOut: '11:00', + location: 'Hotel Kanra Kyoto', + lat: 34.99, + lng: 135.76, + }); + }); +}); + +describe('upcomingReservations', () => { + it('keeps a stay that is running when asked to', () => { + const dayDates = new Map([ + [2, '2026-11-18'], + [3, '2026-11-19'], + ]); + expect(upcomingReservations([hotel], { dayDates, today: '2026-11-19' })).toEqual([]); + expect(upcomingReservations([hotel], { dayDates, today: '2026-11-19', running: true })).toHaveLength(1); + }); +}); + +describe('the arrival zone', () => { + it('falls back to the arrival timezone in the metadata and is left out without one', () => { + const noEndpoints = reservation({ + id: 9, + title: 'LH 717', + type: 'flight', + reservation_time: '2026-11-25T10:00', + metadata: JSON.stringify({ departure_timezone: 'Asia/Tokyo', arrival_timezone: 'Europe/Berlin' }), + }); + const b = watchBooking( + noEndpoints, + { day: '2026-11-25', time: '10:00' }, + { dayDates: new Map(), places: new Map() } + ); + expect(b).toMatchObject({ zone: 'Asia/Tokyo', endZone: 'Europe/Berlin' }); + const plain = watchBooking(hotel, { day: '2026-11-18', time: null }, { dayDates: new Map(), places: new Map() }); + expect(plain).not.toHaveProperty('endZone'); + }); +}); + +describe('the lists', () => { + it('puts the packing still to do first and counts what is packed', () => { + const items = [ + { id: 1, name: 'Passport', checked: 1, category: 'Documents', sort_order: 0 }, + { id: 2, name: 'Rain jacket', checked: 0, category: 'Clothes', sort_order: 1 }, + ] as PackingItem[]; + expect(watchPacking(items)).toEqual({ + items: [ + { id: 2, name: 'Rain jacket', done: false, group: 'Clothes' }, + { id: 1, name: 'Passport', done: true, group: 'Documents' }, + ], + packed: 1, + total: 2, + }); + expect(watchPacking([])).toBeUndefined(); + }); + + it('orders the to-dos by done, due date, then priority', () => { + const todo = (id: number, fields: Partial) => + ({ + id, + name: `T${id}`, + checked: 0, + due_date: null, + priority: 0, + sort_order: id, + category: null, + ...fields, + }) as TodoItem; + const out = watchTodos([ + todo(1, { checked: 1 }), + todo(2, {}), + todo(3, { due_date: '2026-11-15', priority: 1 }), + todo(4, { priority: 3 }), + todo(5, { due_date: '2026-11-10' }), + ]); + expect(out?.items.map((i) => i.id)).toEqual([5, 3, 4, 2, 1]); + expect(out?.items[1]).toEqual({ id: 3, name: 'T3', done: false, due: '2026-11-15', priority: 1 }); + expect(out?.open).toBe(4); + }); +}); + +describe('buildWatchSnapshot', () => { + const src = { + trip, + days, + places, + reservations: [ + flight, + hotel, + reservation({ id: 3, title: 'Old', type: 'tour', reservation_time: '2026-11-01T10:00' }), + ], + packing: [], + todos: [], + today: '2026-11-07', + hour12: false, + place: 'Kyoto, Japan', + applied: ['a1'], + now: new Date('2026-11-07T10:00:00Z'), + }; + + it('carries the trip, its days, the bookings ahead and the applied ticks', () => { + const snapshot = buildWatchSnapshot(src); + expect(snapshot.v).toBe(1); + expect(snapshot.generatedAt).toBe('2026-11-07T10:00:00.000Z'); + expect(snapshot.trip).toEqual({ + id: 7, + title: 'Autumn in Kyoto', + start: '2026-11-17', + end: '2026-11-25', + place: 'Kyoto, Japan', + }); + expect(snapshot.bookings.map((b) => b.id)).toEqual([1, 2]); + expect(snapshot.days).toHaveLength(3); + expect(snapshot.applied).toEqual(['a1']); + expect(snapshot).not.toHaveProperty('packing'); + }); + + it('is an empty snapshot without a trip', () => { + expect(buildWatchSnapshot({ ...src, trip: null })).toMatchObject({ trip: null, days: [], bookings: [] }); + }); +}); + +describe('fitWatchSnapshot', () => { + const big = (): WatchSnapshot => ({ + v: 1, + generatedAt: '', + hour12: false, + trip: { id: 1, title: 'T', start: '', end: '', cover: 'x'.repeat(20_000) }, + days: [], + bookings: [], + packing: { + items: Array.from({ length: 400 }, (_, i) => ({ + id: i, + name: `Item number ${i} with a long name`, + done: i % 2 === 0, + })), + packed: 200, + total: 400, + }, + applied: [], + }); + + it('leaves a small snapshot alone', () => { + const small = { ...big(), packing: undefined, trip: null }; + expect(fitWatchSnapshot(small)).toBe(small); + }); + + it('drops the cover, then the done items, then halves the lists until it fits', () => { + const fitted = fitWatchSnapshot(big(), 6_000); + expect(fitted.trip?.cover).toBeUndefined(); + expect(fitted.packing?.items.every((i) => !i.done)).toBe(true); + expect(JSON.stringify(fitted).length).toBeLessThanOrEqual(6_000); + expect(fitted.packing?.total).toBe(400); + }); +}); + +describe('the watch actions', () => { + it('keeps only well-formed ticks', () => { + const good = { id: 'u1', tripId: 7, list: 'packing', itemId: 3, done: true }; + expect( + parseWatchActions([good, { ...good, list: 'budget' }, { ...good, itemId: '3' }, null, 'x', { ...good, id: '' }]) + ).toEqual([good]); + expect(parseWatchActions({})).toEqual([]); + }); + + it('applies them in order through the toggles and answers their ids, failed ones included', async () => { + const calls: string[] = []; + const toggles = { + packing: vi.fn(async (trip: number, id: number, done: boolean) => { + calls.push(`p${trip}:${id}:${done}`); + }), + todo: vi.fn(async () => { + calls.push('t'); + throw new Error('offline'); + }), + }; + const ids = await applyWatchActions( + [ + { id: 'a', tripId: 7, list: 'packing', itemId: 1, done: true }, + { id: 'b', tripId: 7, list: 'todo', itemId: 2, done: false }, + ], + toggles + ); + expect(calls).toEqual(['p7:1:true', 't']); + expect(ids).toEqual(['a', 'b']); + expect(reportNativeFailure).toHaveBeenCalled(); + }); + + it('takes them from the app, and nothing on a binary without the watch', async () => { + vi.mocked(TrekShell.takeWatchActions).mockResolvedValueOnce({ + actions: [{ id: 'z', tripId: 1, list: 'todo', itemId: 9, done: true }, { bad: 1 }], + }); + expect(await takeWatchActions()).toEqual([{ id: 'z', tripId: 1, list: 'todo', itemId: 9, done: true }]); + vi.mocked(hasNativeFeature).mockReturnValueOnce(false); + expect(await takeWatchActions()).toEqual([]); + }); +}); + +describe('publishWatch', () => { + it('hands the fitted snapshot to the app', async () => { + const snapshot = buildWatchSnapshot({ + trip: null, + days: [], + places: [], + reservations: [], + packing: [], + todos: [], + today: '2026-11-07', + hour12: true, + now: new Date('2026-11-07T10:00:00Z'), + }); + await publishWatch(snapshot); + expect(TrekShell.setWatchSnapshot).toHaveBeenCalledWith({ json: JSON.stringify(snapshot) }); + }); +}); diff --git a/client/src/native/watch.ts b/client/src/native/watch.ts new file mode 100644 index 000000000..e2cad9768 --- /dev/null +++ b/client/src/native/watch.ts @@ -0,0 +1,473 @@ +import type { Day, PackingItem, Place, Reservation, TodoItem, Trip } from '../types'; +import { parseReservationMetadata } from '../utils/flightLegs'; +import { splitReservationDateTime } from '../utils/formatters'; +import { hasNativeFeature } from './capabilities'; +import { isNativeIos } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell } from './trekShell'; +import { bookingKind, stopLook, upcomingReservations } from './widgetExtras'; +import { RESERVATION_SYMBOLS, mergeByTime, minutesOf, type WidgetWeather } from './widgets'; + +/** + * What the Apple Watch app shows (client/ios/App/TREKWatch), built from the + * trips this device keeps offline, like the widgets' snapshot, and handed to + * the app (TrekShell.setWatchSnapshot), which passes it on through + * WatchConnectivity. The watch has no session of its own, so this carries the + * whole trip it needs: every day with its stops and their coordinates, the + * bookings with their reference, seat and platform, the packing list and the + * to-dos with their ids. It carries data only; the watch says everything in its + * own languages and formats the times itself. + * + * What the watch ticks off comes back as WatchActions (parseWatchActions) and + * goes through the trip store's toggles, i.e. the repos and the mutation queue, + * exactly as a tap in the app would. The Swift side of the shape is + * client/ios/App/TREKWatchKit/WatchSnapshot.swift. + */ + +interface WatchStop { + name: string; + /** Minutes after midnight, and the end when the stop has one. */ + minutes?: number; + endMinutes?: number; + symbol?: string; + color?: string; + address?: string; + lat?: number; + lng?: number; + /** Set for a booking on the day's timeline: its kind (flight, hotel, ...). */ + booking?: string; + note?: string; +} + +interface WatchDay { + /** yyyy-MM-dd; missing on a day without a date. */ + date?: string; + /** 1-based position in the trip. */ + number: number; + title?: string; + stops: WatchStop[]; +} + +interface WatchPoint { + name: string; + code?: string; + lat?: number; + lng?: number; +} + +interface WatchBooking { + id: number; + title: string; + /** flight, train, bus, car, cruise, hotel, restaurant, event, tour, other */ + kind: string; + confirmed: boolean; + /** yyyy-MM-dd and HH:mm (24 hours) of the start, and of the end. */ + date?: string; + time?: string; + endDate?: string; + endTime?: string; + /** The IANA zone the start is local to, when the booking names one (a departure airport). */ + zone?: string; + /** The zone the end is local to (the arrival airport), so a long flight lands at the right hour. */ + endZone?: string; + from?: WatchPoint; + to?: WatchPoint; + /** The booking reference. */ + code?: string; + /** "Lufthansa LH 716", "ICE 597". */ + carrier?: string; + seat?: string; + platform?: string; + /** Where it is: the hotel, the restaurant's address. */ + location?: string; + lat?: number; + lng?: number; + /** A stay's check-in and check-out times, HH:mm. */ + checkIn?: string; + checkOut?: string; +} + +interface WatchItem { + id: number; + name: string; + done: boolean; + /** The packing category or to-do category. */ + group?: string; + /** yyyy-MM-dd */ + due?: string; + /** 0 none ... 3 high. */ + priority?: number; +} + +export interface WatchSnapshot { + v: 1; + /** When the phone built it, ISO 8601. */ + generatedAt: string; + /** The user's clock in TREK's settings. */ + hour12: boolean; + trip: { + id: number; + title: string; + start: string; + end: string; + place?: string; + /** The cover as a base64 JPEG; the app scales it down for the watch. */ + cover?: string; + } | null; + days: WatchDay[]; + bookings: WatchBooking[]; + weather?: WidgetWeather; + packing?: { items: WatchItem[]; packed: number; total: number }; + todos?: { items: WatchItem[]; open: number; total: number }; + /** The ids of the watch's own actions this phone has applied, newest last. */ + applied: string[]; +} + +/** A tick from the watch: one packing item or to-do set done or not. */ +interface WatchAction { + id: string; + tripId: number; + list: 'packing' | 'todo'; + itemId: number; + done: boolean; +} + +const MAX_DAYS = 45; +const MAX_STOPS = 24; +const MAX_BOOKINGS = 12; +const MAX_NAME = 80; + +const text = (value: string | null | undefined, max = MAX_NAME): string | undefined => { + const trimmed = value?.trim(); + return trimmed ? trimmed.slice(0, max) : undefined; +}; + +const coordinate = (value: number | null | undefined): number | undefined => + typeof value === 'number' && Number.isFinite(value) ? Math.round(value * 1e5) / 1e5 : undefined; + +/** Leaves out what is undefined, so the JSON the watch gets stays small. */ +function compact(value: T): T { + return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T; +} + +function placeStop(a: NonNullable[number]): WatchStop | null { + const place = a.place; + if (!place?.name) return null; + const start = minutesOf(a.assignment_time ?? place.place_time); + const end = minutesOf(a.assignment_end_time ?? place.end_time); + const look = stopLook(place.category); + return compact({ + name: place.name.slice(0, MAX_NAME), + minutes: start ?? undefined, + endMinutes: start != null && end != null && end > start ? end : undefined, + symbol: look.symbol ?? undefined, + color: look.color ?? undefined, + address: text(place.address, 120), + lat: coordinate(place.lat), + lng: coordinate(place.lng), + note: text(a.notes, 140), + }); +} + +/** The trip's days in order, each with its stops and the timed bookings of its date merged in by time. */ +export function watchDays(days: Day[], bookings: WatchBooking[]): WatchDay[] { + return [...days] + .sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0)) + .slice(0, MAX_DAYS) + .map((day, index) => { + const date = day.date ? day.date.slice(0, 10) : undefined; + const stops = [...(day.assignments ?? [])] + .sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0)) + .map(placeStop) + .filter((s): s is WatchStop => s !== null); + const booked = date + ? bookings + .filter((b) => b.date === date && b.time) + .map((b) => + compact({ + name: b.title, + minutes: minutesOf(b.time) ?? undefined, + symbol: RESERVATION_SYMBOLS[b.kind] ?? 'bookmark.fill', + booking: b.kind, + address: b.from?.name ?? b.location, + lat: b.from?.lat ?? b.lat, + lng: b.from?.lng ?? b.lng, + }) + ) + : []; + return compact({ + date, + number: index + 1, + title: text(day.title), + stops: mergeByTime(stops, booked).slice(0, MAX_STOPS), + }); + }); +} + +function point(e: NonNullable[number] | undefined): WatchPoint | undefined { + if (!e) return undefined; + return compact({ + name: e.name.slice(0, MAX_NAME), + code: text(e.code, 8), + lat: coordinate(e.lat), + lng: coordinate(e.lng), + }); +} + +/** "Lufthansa LH 716" from the flight's airline and number, "ICE 597" from a train's. */ +function carrierOf(meta: Record): string | undefined { + const str = (key: string) => (typeof meta[key] === 'string' ? (meta[key] as string).trim() : ''); + const number = str('flight_number') || str('train_number'); + const joined = [str('airline'), number].filter(Boolean).join(' '); + return text(joined, 40); +} + +type PlaceLookup = Map>; + +const metaText = (meta: Record, key: string, max = 20) => + typeof meta[key] === 'string' ? text(meta[key] as string, max) : undefined; + +/** Where a booking is: its hotel or place with coordinates, else what its location field says. */ +function whereOf(r: Reservation, places: PlaceLookup): Pick { + const placeId = r.accommodation_place_id ?? r.place_id; + const place = placeId == null ? undefined : places.get(placeId); + const named = r.accommodation_name || r.location || r.place_name; + return { location: text(named || place?.address), lat: coordinate(place?.lat), lng: coordinate(place?.lng) }; +} + +/** When a booking starts and ends; a stay without times of its own takes its check-in and check-out. */ +function timesOf( + r: Reservation, + start: { day: string | null; time: string | null }, + meta: Record, + dayDates: Map +): Pick { + const end = splitReservationDateTime(r.reservation_end_time); + const endDay = r.end_day_id == null ? undefined : dayDates.get(r.end_day_id); + return { + date: start.day ?? undefined, + time: start.time ?? metaText(meta, 'check_in_time'), + endDate: end.date ?? endDay, + endTime: end.time ?? metaText(meta, 'check_out_time'), + }; +} + +/** A booking with what the watch shows of it: the reference, seat, platform, both ends and where to go. */ +export function watchBooking( + r: Reservation, + start: { day: string | null; time: string | null }, + { dayDates, places }: { dayDates: Map; places: PlaceLookup } +): WatchBooking { + const meta = parseReservationMetadata(r); + const legs = [...(r.endpoints ?? [])].sort((a, b) => a.sequence - b.sequence); + const from = legs.find((e) => e.role === 'from'); + const to = [...legs].reverse().find((e) => e.role === 'to'); + return compact({ + id: r.id, + title: r.title.slice(0, MAX_NAME), + kind: bookingKind(r.type), + confirmed: r.status === 'confirmed', + ...timesOf(r, start, meta, dayDates), + zone: text(from?.timezone || metaText(meta, 'departure_timezone', 40), 40), + endZone: text(to?.timezone || metaText(meta, 'arrival_timezone', 40), 40), + from: point(from), + to: point(to), + code: text(r.confirmation_number, 40), + carrier: carrierOf(meta), + seat: metaText(meta, 'seat'), + platform: metaText(meta, 'platform'), + ...whereOf(r, places), + checkIn: metaText(meta, 'check_in_time'), + checkOut: metaText(meta, 'check_out_time'), + }); +} + +/** The packing list, items still to pack first, each group in the list's order. */ +export function watchPacking(items: PackingItem[]): WatchSnapshot['packing'] { + if (items.length === 0) return undefined; + const sorted = [...items].sort((a, b) => Number(!!a.checked) - Number(!!b.checked) || a.sort_order - b.sort_order); + return { + items: sorted.map((i) => + compact({ id: i.id, name: i.name.slice(0, MAX_NAME), done: !!i.checked, group: text(i.category, 40) }) + ), + packed: items.filter((i) => i.checked).length, + total: items.length, + }; +} + +/** The to-dos, open ones first by due date (undated last) and priority, then the done ones. */ +export function watchTodos(items: TodoItem[]): WatchSnapshot['todos'] { + if (items.length === 0) return undefined; + const rank = (i: TodoItem) => [i.checked ? 1 : 0, i.due_date ? 0 : 1] as const; + const sorted = [...items].sort((a, b) => { + const [doneA, undatedA] = rank(a); + const [doneB, undatedB] = rank(b); + if (doneA !== doneB) return doneA - doneB; + if (undatedA !== undatedB) return undatedA - undatedB; + if (a.due_date && b.due_date && a.due_date !== b.due_date) return a.due_date.localeCompare(b.due_date); + return (b.priority ?? 0) - (a.priority ?? 0) || (a.sort_order ?? 0) - (b.sort_order ?? 0); + }); + return { + items: sorted.map((i) => + compact({ + id: i.id, + name: i.name.slice(0, MAX_NAME), + done: !!i.checked, + group: text(i.category, 40), + due: i.due_date ? i.due_date.slice(0, 10) : undefined, + priority: i.priority ? Math.max(0, Math.min(3, i.priority)) : undefined, + }) + ), + open: items.filter((i) => !i.checked).length, + total: items.length, + }; +} + +interface WatchSources { + trip: Trip | null; + days: Day[]; + places: Place[]; + reservations: Reservation[]; + packing: PackingItem[]; + todos: TodoItem[]; + today: string; + hour12: boolean; + place?: string | null; + cover?: string | null; + weather?: WidgetWeather | null; + applied?: string[]; + now?: Date; +} + +export function buildWatchSnapshot(src: WatchSources): WatchSnapshot { + const { trip } = src; + const base = { + v: 1 as const, + generatedAt: (src.now ?? new Date()).toISOString(), + hour12: src.hour12, + applied: src.applied ?? [], + }; + if (!trip) return { ...base, trip: null, days: [], bookings: [] }; + const dayDates = new Map(src.days.map((d) => [d.id, (d.date ?? '').slice(0, 10)])); + const places = new Map(src.places.map((p) => [p.id, p])); + const dated = upcomingReservations(src.reservations, { dayDates, today: src.today, running: true }); + const bookings = dated.map(({ r, day, time }) => watchBooking(r, { day, time }, { dayDates, places })); + // The days get every booking of their date; the list only the ones ahead. + const all = upcomingReservations(src.reservations, { dayDates, today: '0000-00-00' }).map(({ r, day, time }) => + watchBooking(r, { day, time }, { dayDates, places }) + ); + return compact({ + ...base, + trip: compact({ + id: trip.id, + title: trip.title, + start: trip.start_date ?? '', + end: trip.end_date ?? '', + place: text(src.place), + cover: src.cover ?? undefined, + }), + days: watchDays(src.days, all), + bookings: bookings.slice(0, MAX_BOOKINGS), + weather: src.weather ?? undefined, + packing: watchPacking(src.packing), + todos: watchTodos(src.todos), + }); +} + +const bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).length; + +/** + * The snapshot cut down to `max` bytes of JSON, for WatchConnectivity's + * payload limit: first the cover goes (the app adds a small one back itself + * when it fits), then the done to-dos and packed items, then the lists are + * halved, then the days far from today. + */ +export function fitWatchSnapshot(snapshot: WatchSnapshot, max = 48_000): WatchSnapshot { + let fitted = snapshot; + const steps: ((s: WatchSnapshot) => WatchSnapshot)[] = [ + (s) => (s.trip?.cover ? { ...s, trip: { ...s.trip, cover: undefined } } : s), + (s) => ({ + ...s, + packing: s.packing && { ...s.packing, items: s.packing.items.filter((i) => !i.done) }, + todos: s.todos && { ...s.todos, items: s.todos.items.filter((i) => !i.done) }, + }), + ...[0, 1, 2, 3].map(() => (s: WatchSnapshot) => ({ + ...s, + packing: s.packing && { ...s.packing, items: s.packing.items.slice(0, Math.ceil(s.packing.items.length / 2)) }, + todos: s.todos && { ...s.todos, items: s.todos.items.slice(0, Math.ceil(s.todos.items.length / 2)) }, + })), + (s) => ({ + ...s, + days: s.days.map((d) => ({ ...d, stops: d.stops.map((stop) => ({ ...stop, note: undefined })) })), + }), + (s) => ({ ...s, days: s.days.slice(0, 14) }), + ]; + for (const step of steps) { + if (bytes(fitted) <= max) break; + fitted = step(fitted); + } + return fitted; +} + +export function watchActive(): boolean { + return isNativeIos() && hasNativeFeature('watch'); +} + +export async function publishWatch(snapshot: WatchSnapshot): Promise { + if (!watchActive()) return; + await TrekShell.setWatchSnapshot({ json: JSON.stringify(fitWatchSnapshot(snapshot)) }).catch(reportNativeFailure); +} + +/** The actions the watch queued, as the app hands them over; anything malformed is dropped. */ +export function parseWatchActions(raw: unknown): WatchAction[] { + if (!Array.isArray(raw)) return []; + return raw.flatMap((entry): WatchAction[] => { + if (typeof entry !== 'object' || entry === null) return []; + const { id, tripId, list, itemId, done } = entry as Record; + const valid = + typeof id === 'string' && + id.length > 0 && + id.length <= 64 && + Number.isInteger(tripId) && + (list === 'packing' || list === 'todo') && + Number.isInteger(itemId) && + typeof done === 'boolean'; + return valid ? [{ id, tripId: tripId as number, list, itemId: itemId as number, done }] : []; + }); +} + +interface WatchToggles { + packing: (tripId: number, id: number, done: boolean) => Promise; + todo: (tripId: number, id: number, done: boolean) => Promise; +} + +/** + * Applies the watch's ticks in the order they were made, through the given + * toggles (the trip store's, which write through the repos and the mutation + * queue). Answers the ids it applied; a tick whose write failed is applied too, + * as the toggle has already rolled it back and told the user. + */ +export async function applyWatchActions(actions: WatchAction[], toggles: WatchToggles): Promise { + const applied: string[] = []; + for (const action of actions) { + try { + await toggles[action.list](action.tripId, action.itemId, action.done); + } catch (err: unknown) { + reportNativeFailure(err); + } + applied.push(action.id); + } + return applied; +} + +/** Takes the ticks the watch sent while the UI was not running, and with them the ones just arriving. */ +export async function takeWatchActions(): Promise { + if (!watchActive()) return []; + try { + const { actions } = await TrekShell.takeWatchActions(); + return parseWatchActions(actions); + } catch (err: unknown) { + reportNativeFailure(err); + return []; + } +} diff --git a/client/src/native/watchListChanges.test.ts b/client/src/native/watchListChanges.test.ts new file mode 100644 index 000000000..15cee9489 --- /dev/null +++ b/client/src/native/watchListChanges.test.ts @@ -0,0 +1,71 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { offlineDb } from '../db/offlineDb'; +import type { PackingItem, TodoItem } from '../types'; +import { onWatchListsChange } from './watchListChanges'; + +// FE-NATIVE-WATCHSYNC-001 onwards: the watch hears of a list change at once, not on the next refresh. + +const packing = (id: number, checked: number) => + ({ id, trip_id: 1, name: `Item ${id}`, checked }) as unknown as PackingItem; +const todo = (id: number, checked: number) => ({ id, trip_id: 1, name: `Task ${id}`, checked }) as unknown as TodoItem; + +/** Long enough for the live query to answer and the settle window to pass. */ +const settled = () => new Promise((resolve) => setTimeout(resolve, 120)); + +describe('onWatchListsChange', () => { + let stop: (() => void) | null = null; + + beforeEach(async () => { + await offlineDb.packingItems.clear(); + await offlineDb.todoItems.clear(); + await offlineDb.packingItems.put(packing(1, 0)); + await offlineDb.todoItems.put(todo(2, 0)); + }); + + afterEach(() => { + stop?.(); + stop = null; + }); + + it('FE-NATIVE-WATCHSYNC-001: subscribing is no change, a tick on the packing list is', async () => { + const run = vi.fn(); + stop = onWatchListsChange(run, 20); + await settled(); + expect(run).not.toHaveBeenCalled(); + + await offlineDb.packingItems.put(packing(1, 1)); + await settled(); + expect(run).toHaveBeenCalledTimes(1); + }); + + it('FE-NATIVE-WATCHSYNC-002: a to-do ticked, here or by another member, counts as well', async () => { + const run = vi.fn(); + stop = onWatchListsChange(run, 20); + await settled(); + await offlineDb.todoItems.put(todo(2, 1)); + await settled(); + expect(run).toHaveBeenCalledTimes(1); + }); + + it('FE-NATIVE-WATCHSYNC-003: a run of ticks settles into one refresh', async () => { + const run = vi.fn(); + stop = onWatchListsChange(run, 60); + await settled(); + await offlineDb.packingItems.put(packing(1, 1)); + await offlineDb.packingItems.put(packing(3, 0)); + await offlineDb.todoItems.put(todo(2, 1)); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(run).toHaveBeenCalledTimes(1); + }); + + it('FE-NATIVE-WATCHSYNC-004: after the unsubscribe nothing is called any more', async () => { + const run = vi.fn(); + stop = onWatchListsChange(run, 20); + await settled(); + stop(); + stop = null; + await offlineDb.packingItems.put(packing(1, 1)); + await settled(); + expect(run).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/native/watchListChanges.ts b/client/src/native/watchListChanges.ts new file mode 100644 index 000000000..f4f86f763 --- /dev/null +++ b/client/src/native/watchListChanges.ts @@ -0,0 +1,42 @@ +import { liveQuery } from 'dexie'; +import { offlineDb } from '../db/offlineDb'; + +/** Long enough to take a run of ticks (or a synced batch) as one change, short enough to read as instant. */ +const SETTLE_MS = 300; + +/** + * Calls `run` once the packing lists or the to-dos this device keeps offline + * have changed, after they settled: a tick in the app, a tick from the watch + * written through, or another member's tick arriving over the WebSocket (the + * remote event handler writes it to the same tables). The watch's snapshot is + * built from those tables, so this is what keeps the watch as current as the + * phone instead of waiting for the next quarter-hour refresh. + * + * The first answer of the query is the state at subscription, not a change, and + * is skipped. Returns the unsubscribe. + */ +export function onWatchListsChange(run: () => void, settleMs = SETTLE_MS): () => void { + let first = true; + let timer: ReturnType | null = null; + const subscription = liveQuery(() => + Promise.all([offlineDb.packingItems.toArray(), offlineDb.todoItems.toArray()]) + ).subscribe({ + next: () => { + if (first) { + first = false; + return; + } + if (timer) clearTimeout(timer); + timer = setTimeout(() => { + timer = null; + run(); + }, settleMs); + }, + // A failed read changes nothing on the watch; the next write tries again. + error: () => undefined, + }); + return () => { + if (timer) clearTimeout(timer); + subscription.unsubscribe(); + }; +} diff --git a/client/src/native/widgetExtras.test.ts b/client/src/native/widgetExtras.test.ts new file mode 100644 index 000000000..4fb185194 --- /dev/null +++ b/client/src/native/widgetExtras.test.ts @@ -0,0 +1,162 @@ +import { describe, expect, it } from 'vitest'; +import type { PackingItem, Reservation, TodoItem } from '../types'; +import { bookingsAhead, packingSummary, stopLook, temperature, todosSummary, tripPlace } from './widgetExtras'; + +const reservation = (over: Partial): Reservation => + ({ id: 1, trip_id: 1, title: 'Booking', status: 'confirmed', type: 'other', ...over }) as Reservation; + +const todo = (over: Partial): TodoItem => + ({ + id: 1, + trip_id: 1, + name: 'Task', + category: null, + checked: 0, + sort_order: 0, + due_date: null, + description: null, + assigned_user_id: null, + priority: 0, + ...over, + }) as TodoItem; + +describe('bookingsAhead', () => { + const days = new Map([[7, '2026-11-09']]); + const time = (t: string) => `T${t}`; + + it('lists the bookings from today on, soonest first, with their kind, legs and status', () => { + const list = bookingsAhead( + [ + reservation({ id: 1, title: 'Old', reservation_time: '2026-11-01T10:00' }), + reservation({ + id: 2, + title: 'Dinner', + type: 'restaurant', + reservation_time: '2026-11-08T19:30', + status: 'pending', + location: 'Pontocho', + }), + reservation({ + id: 3, + title: 'LH 716', + type: 'flight', + reservation_time: '2026-11-08T13:05', + endpoints: [ + { + role: 'to', + sequence: 1, + name: 'Tokyo Haneda', + code: 'HND', + lat: 0, + lng: 0, + timezone: null, + local_time: null, + local_date: null, + }, + { + role: 'from', + sequence: 0, + name: 'Frankfurt', + code: 'FRA', + lat: 0, + lng: 0, + timezone: null, + local_time: null, + local_date: null, + }, + ], + }), + reservation({ id: 4, title: 'Museum', type: 'activity', day_id: 7 }), + reservation({ id: 5, title: 'Undated' }), + reservation({ id: 6, title: 'Cancelled', reservation_time: '2026-11-08T08:00', status: 'cancelled' }), + reservation({ id: 7, title: 'Staged', reservation_time: '2026-11-08T08:00', ingest_state: 'staged' }), + ], + { dayDates: days, today: '2026-11-06', tripPath: '/trips/1', formatTime: time } + ); + expect(list.map((b) => b.title)).toEqual(['LH 716', 'Dinner', 'Museum', 'Undated']); + expect(list[0]).toEqual({ + title: 'LH 716', + kind: 'flight', + date: '2026-11-08', + time: 'T13:05', + detail: 'FRA → HND', + confirmed: true, + path: '/trips/1?tab=transports', + }); + expect(list[1]).toMatchObject({ + kind: 'restaurant', + detail: 'Pontocho', + confirmed: false, + path: '/trips/1?tab=buchungen', + }); + expect(list[2]).toMatchObject({ kind: 'tour', date: '2026-11-09', time: null }); + expect(list[3]).toMatchObject({ kind: 'other', date: null }); + }); + + it('stops at the limit', () => { + const many = Array.from({ length: 8 }, (_, i) => reservation({ id: i, reservation_time: `2026-11-1${i}T10:00` })); + expect( + bookingsAhead(many, { dayDates: new Map(), today: '2026-11-06', tripPath: '/trips/1', formatTime: (t) => t }) + ).toHaveLength(5); + }); +}); + +describe('todosSummary', () => { + it('counts the open ones and orders them by due date, then priority', () => { + const summary = todosSummary( + [ + todo({ id: 1, name: 'Done', checked: 1 }), + todo({ id: 2, name: 'Someday', priority: 3 }), + todo({ id: 3, name: 'Soon', due_date: '2026-11-08' }), + todo({ id: 4, name: 'First', due_date: '2026-11-07T00:00:00' }), + todo({ id: 5, name: 'Low', priority: 1 }), + ], + '/trips/1?tab=listen' + ); + expect(summary.open).toBe(4); + expect(summary.total).toBe(5); + expect(summary.items.map((i) => i.name)).toEqual(['First', 'Soon', 'Someday', 'Low']); + expect(summary.items[0]).toEqual({ name: 'First', due: '2026-11-07', priority: 0 }); + }); +}); + +describe('packingSummary', () => { + it('counts packed against all, and is null without a list', () => { + const items = [{ checked: 1 }, { checked: 0 }, { checked: 1 }] as PackingItem[]; + expect(packingSummary(items, '/p')).toEqual({ packed: 2, total: 3, path: '/p' }); + expect(packingSummary([], '/p')).toBeNull(); + }); +}); + +describe('tripPlace', () => { + it('names the town and country most places share, without postcodes', () => { + expect( + tripPlace([ + { address: '68 Fukakusa Yabunouchicho, Fushimi Ward, 612-0882 Kyoto, Japan' }, + { address: 'Nakagyo Ward, 604-8054 Kyoto, Japan' }, + { address: '1-1 Chiyoda, 100-8111 Tokyo, Japan' }, + { address: null }, + { address: 'Nowhere' }, + ]) + ).toBe('Kyoto, Japan'); + }); + + it('is null without usable addresses', () => { + expect(tripPlace([{ address: 'Main Street' }, { address: '' }])).toBeNull(); + }); +}); + +describe('stopLook and temperature', () => { + it('maps a category to a colour and an SF Symbol, ignoring what it cannot use', () => { + expect(stopLook({ color: '#E8A13A', icon: 'Coffee' })).toEqual({ color: '#E8A13A', symbol: 'cup.and.saucer.fill' }); + expect(stopLook({ color: 'red', icon: 'Unknown' })).toEqual({ color: null, symbol: null }); + expect(stopLook({ color: '#84cc16', icon: '🌿' })).toEqual({ color: '#84cc16', symbol: 'leaf.fill' }); + expect(stopLook(null)).toEqual({ color: null, symbol: null }); + }); + + it('converts to Fahrenheit only when asked, rounded', () => { + expect(temperature(18.4, 'celsius')).toBe(18); + expect(temperature(20, 'fahrenheit')).toBe(68); + expect(temperature(-0.6, undefined)).toBe(-1); + }); +}); diff --git a/client/src/native/widgetExtras.ts b/client/src/native/widgetExtras.ts new file mode 100644 index 000000000..ef1765548 --- /dev/null +++ b/client/src/native/widgetExtras.ts @@ -0,0 +1,277 @@ +import type { PackingItem, Place, Reservation, TodoItem } from '../types'; +import { splitReservationDateTime } from '../utils/formatters'; + +/** + * The parts of the widget snapshot beyond the trip and today's stops: the + * bookings ahead, the to-dos, the packing list, the destination's name, and + * how a stop looks (its category's colour and an SF Symbol for its icon). + * Pure, so the shapes the widgets get are tested here; the Swift side is in + * client/ios/App/TREKWidgets/WidgetSnapshot.swift. + */ + +export interface WidgetBooking { + title: string; + kind: string; + date: string | null; + time: string | null; + detail: string | null; + confirmed: boolean; + path: string; +} + +export interface WidgetTodos { + open: number; + total: number; + items: { name: string; due: string | null; priority: number }[]; + path: string; +} + +export interface WidgetPacking { + packed: number; + total: number; + path: string; +} + +/** The lucide icon names categories use (components/shared/categoryIcons.ts), as SF Symbols. */ +const SYMBOLS: Record = { + MapPin: 'mappin', + Building2: 'building.2.fill', + BedDouble: 'bed.double.fill', + UtensilsCrossed: 'fork.knife', + Utensils: 'fork.knife', + Landmark: 'building.columns.fill', + ShoppingBag: 'bag.fill', + Store: 'storefront.fill', + Bus: 'bus.fill', + Train: 'tram.fill', + Car: 'car.fill', + Plane: 'airplane', + Ship: 'ferry.fill', + Bike: 'bicycle', + Activity: 'figure.run', + Dumbbell: 'dumbbell.fill', + Mountain: 'mountain.2.fill', + Tent: 'tent.fill', + Anchor: 'sailboat.fill', + Coffee: 'cup.and.saucer.fill', + Beer: 'mug.fill', + Wine: 'wineglass.fill', + Camera: 'camera.fill', + Music: 'music.note', + Theater: 'theatermasks.fill', + Ticket: 'ticket.fill', + TreePine: 'tree.fill', + Waves: 'water.waves', + Leaf: 'leaf.fill', + Flower2: 'camera.macro', + Sun: 'sun.max.fill', + Globe: 'globe.europe.africa.fill', + Compass: 'safari.fill', + Flag: 'flag.fill', + Navigation: 'location.north.fill', + Map: 'map.fill', + Church: 'building.columns.fill', + Library: 'books.vertical.fill', + Home: 'house.fill', + Cross: 'cross.case.fill', + Heart: 'heart.fill', + Star: 'star.fill', + CreditCard: 'creditcard.fill', + Wifi: 'wifi', + Luggage: 'suitcase.rolling.fill', + Backpack: 'backpack.fill', + Zap: 'bolt.fill', + // The emoji icons of the categories older installs were seeded with. + '🏨': 'bed.double.fill', + '🍽️': 'fork.knife', + '🏛️': 'building.columns.fill', + '🛍️': 'bag.fill', + '🚌': 'bus.fill', + '🎯': 'figure.walk', + '☕': 'cup.and.saucer.fill', + '🏖️': 'beach.umbrella.fill', + '🌿': 'leaf.fill', + '📍': 'mappin', +}; + +const HEX = /^#[0-9a-f]{6}$/i; + +/** A stop's colour and symbol from its place's category; nulls when it has none. */ +export function stopLook(category: { color?: string | null; icon?: string | null } | null | undefined): { + color: string | null; + symbol: string | null; +} { + return { + color: category?.color && HEX.test(category.color) ? category.color : null, + symbol: (category?.icon && SYMBOLS[category.icon]) || null, + }; +} + +/** The booking kinds the widget draws; the rest of RESERVATION_TYPES fold into these. */ +const KINDS: Record = { + flight: 'flight', + train: 'train', + transit: 'train', + cable_car: 'train', + bus: 'bus', + car: 'car', + taxi: 'car', + bicycle: 'car', + cruise: 'cruise', + ferry: 'cruise', + hotel: 'hotel', + restaurant: 'restaurant', + event: 'event', + tour: 'tour', + activity: 'tour', +}; + +function bookingDetail(r: Reservation): string | null { + const legs = [...(r.endpoints ?? [])].sort((a, b) => a.sequence - b.sequence); + const from = legs.find((e) => e.role === 'from'); + const to = [...legs].reverse().find((e) => e.role === 'to'); + if (from && to) return `${from.code || from.name} → ${to.code || to.name}`; + return r.location?.trim() || r.accommodation_name || r.place_name || null; +} + +/** Transport bookings open on the trip's transports tab, the rest on its bookings tab. */ +const TRANSPORT_KINDS = new Set(['flight', 'train', 'bus', 'car', 'cruise']); + +/** A booking with the day it falls on and its start time, as the widgets order them. */ +interface DatedReservation { + r: Reservation; + /** yyyy-MM-dd: its own date, else the date of the day it is placed on. */ + day: string | null; + /** HH:mm, 24 hours. */ + time: string | null; +} + +/** + * The trip's bookings from today on, soonest first: those without a date at + * the end, cancelled ones and drafts an import still waits on left out. With + * `running`, a booking that started before today but ends today or later (the + * hotel the trip sleeps in) stays in. + */ +export function upcomingReservations( + reservations: Reservation[], + { dayDates, today, running = false }: { dayDates: Map; today: string; running?: boolean } +): DatedReservation[] { + const dayOf = (date: string | null, dayId: number | null | undefined) => + date ?? (dayId != null ? (dayDates.get(dayId) ?? null) : null); + return reservations + .filter((r) => r.status !== 'cancelled' && (r.ingest_state ?? 'live') === 'live') + .map((r) => { + const { date, time } = splitReservationDateTime(r.reservation_time); + const day = dayOf(date, r.day_id); + const end = running ? dayOf(splitReservationDateTime(r.reservation_end_time).date, r.end_day_id) : null; + return { r, day, time, end }; + }) + .filter(({ day, end }) => day == null || day >= today || (end != null && end >= today)) + .sort((a, b) => { + if (a.day !== b.day) return a.day == null ? 1 : b.day == null ? -1 : a.day.localeCompare(b.day); + return (a.time ?? '99:99').localeCompare(b.time ?? '99:99'); + }) + .map(({ r, day, time }) => ({ r, day, time })); +} + +/** The kind a booking type is drawn as. */ +export function bookingKind(type: string): string { + return KINDS[type] ?? 'other'; +} + +/** The trip's bookings from today on, soonest first, as the widgets show them. */ +export function bookingsAhead( + reservations: Reservation[], + { + dayDates, + today, + tripPath, + formatTime, + limit = 5, + }: { + /** The trip's day ids to their dates, for bookings placed on a day without a date of their own. */ + dayDates: Map; + today: string; + tripPath: string; + formatTime: (time: string) => string; + limit?: number; + } +): WidgetBooking[] { + return upcomingReservations(reservations, { dayDates, today }) + .slice(0, limit) + .map(({ r, day, time }) => { + const kind = bookingKind(r.type); + return { + title: r.title, + kind, + date: day, + time: time ? formatTime(time) : null, + detail: bookingDetail(r), + confirmed: r.status === 'confirmed', + path: `${tripPath}?tab=${TRANSPORT_KINDS.has(kind) ? 'transports' : 'buchungen'}`, + }; + }); +} + +/** Open to-dos first by due date (undated last), then by priority, highest first. */ +export function todosSummary(items: TodoItem[], path: string, limit = 6): WidgetTodos { + const open = items.filter((i) => !i.checked); + const sorted = [...open].sort((a, b) => { + if (a.due_date !== b.due_date) { + if (!a.due_date) return 1; + if (!b.due_date) return -1; + return a.due_date.localeCompare(b.due_date); + } + return (b.priority ?? 0) - (a.priority ?? 0) || a.sort_order - b.sort_order; + }); + return { + open: open.length, + total: items.length, + items: sorted.slice(0, limit).map((i) => ({ + name: i.name, + due: i.due_date ? i.due_date.slice(0, 10) : null, + priority: Math.max(0, Math.min(3, i.priority ?? 0)), + })), + path, + }; +} + +/** Packed items against all of them; null without a packing list. */ +export function packingSummary(items: PackingItem[], path: string): WidgetPacking | null { + if (items.length === 0) return null; + return { packed: items.filter((i) => i.checked).length, total: items.length, path }; +} + +/** + * Where the trip goes, in a few words: the town and country most of its + * places share, read off their addresses ("…, 600-8216 Kyoto, Japan"). + */ +export function tripPlace(places: Pick[]): string | null { + const counts = new Map(); + for (const { address } of places) { + const parts = (address ?? '') + .split(',') + .map((p) => p.trim()) + .filter(Boolean); + if (parts.length < 2) continue; + const country = parts[parts.length - 1]; + const town = parts[parts.length - 2].replace(/\b[\dA-Z]{0,4}[\d][\d\s-]*\b/g, '').trim(); + if (!town || /\d/.test(country)) continue; + const key = `${town}, ${country}`; + counts.set(key, (counts.get(key) ?? 0) + 1); + } + let best: string | null = null; + let most = 0; + for (const [key, count] of counts) { + if (count > most) { + best = key; + most = count; + } + } + return best; +} + +/** Celsius to the user's unit, rounded. */ +export function temperature(celsius: number, unit: string | undefined): number { + return Math.round(unit === 'fahrenheit' ? (celsius * 9) / 5 + 32 : celsius); +} diff --git a/client/src/native/widgetFlight.test.ts b/client/src/native/widgetFlight.test.ts new file mode 100644 index 000000000..bfd64b4a9 --- /dev/null +++ b/client/src/native/widgetFlight.test.ts @@ -0,0 +1,143 @@ +// FE-NATIVE-WIDGETFLIGHT-001 to FE-NATIVE-WIDGETFLIGHT-008 +import type { FlightLiveLeg } from '@trek/shared'; +import { describe, expect, it } from 'vitest'; + +import { pickWidgetLeg, widgetFlight } from './widgetFlight'; +import { liveFlightOf } from './widgets'; + +const DEP = Date.parse('2026-06-11T11:50:00Z'); +const ARR = Date.parse('2026-06-11T20:35:00Z'); +const H = 3_600_000; +const CLOCK = { locale: 'en-GB', timeFormat: '24h' }; + +function leg(over: Partial = {}): FlightLiveLeg { + return { + reservation_id: 6, + leg_index: 0, + callsign: 'DLH400', + flight_number: 'LH 400', + service_date: '2026-06-11', + origin: { code: 'FRA', name: 'Frankfurt', lat: 50.03, lng: 8.57, timezone: 'Europe/Berlin' }, + destination: { code: 'JFK', name: 'New York JFK', lat: 40.64, lng: -73.78, timezone: 'America/New_York' }, + phase: 'scheduled', + scheduled_departure: new Date(DEP).toISOString(), + scheduled_arrival: new Date(ARR).toISOString(), + departed_at: null, + landed_at: null, + estimated_arrival: null, + departure_delay_min: null, + arrival_delay_min: null, + progress: null, + distance_total_km: null, + distance_remaining_km: null, + position: null, + aircraft: null, + last_seen_at: null, + fetched_at: null, + stale: false, + source: null, + ...over, + }; +} + +describe('pickWidgetLeg', () => { + it('FE-NATIVE-WIDGETFLIGHT-001: prefers the flight in the air', () => { + const ahead = leg({ reservation_id: 7 }); + const flying = leg({ reservation_id: 8, phase: 'airborne' }); + expect(pickWidgetLeg([ahead, flying], DEP)?.reservation_id).toBe(8); + }); + + it('FE-NATIVE-WIDGETFLIGHT-002: takes the earliest within a week and drops one more than two hours landed', () => { + const later = leg({ + reservation_id: 9, + scheduled_departure: new Date(DEP + 48 * H).toISOString(), + scheduled_arrival: new Date(ARR + 48 * H).toISOString(), + }); + expect(pickWidgetLeg([later, leg()], DEP - H)?.reservation_id).toBe(6); + expect(pickWidgetLeg([leg()], ARR + 3 * H)).toBeNull(); + expect(pickWidgetLeg([leg()], DEP - 8 * 24 * H)).toBeNull(); + }); +}); + +describe('widgetFlight', () => { + it('FE-NATIVE-WIDGETFLIGHT-003: sends the schedule in seconds and the clock at each airport', () => { + const flight = widgetFlight([leg()], DEP - H, '/trips/1', CLOCK); + expect(flight).toMatchObject({ + number: 'LH 400', + from: 'FRA', + to: 'JFK', + dep: DEP / 1000, + arr: ARR / 1000, + depTime: '13:50', + arrTime: '16:35', + path: '/trips/1?booking=6', + }); + expect(flight?.arrExpected).toBeUndefined(); + expect(flight?.landed).toBeUndefined(); + }); + + it('FE-NATIVE-WIDGETFLIGHT-004: adds what the feed observed while the flight is in the air', () => { + const flight = widgetFlight( + [ + leg({ + phase: 'airborne', + departed_at: new Date(DEP + 20 * 60_000).toISOString(), + estimated_arrival: new Date(ARR + 15 * 60_000).toISOString(), + arrival_delay_min: 15, + aircraft: { registration: 'D-AIXA', type: 'A359' }, + last_seen_at: new Date(DEP + 2 * H).toISOString(), + }), + ], + DEP + 2 * H, + '/trips/1', + CLOCK + ); + expect(flight).toMatchObject({ + depActual: (DEP + 20 * 60_000) / 1000, + arrExpected: (ARR + 15 * 60_000) / 1000, + arrTimeExpected: '16:50', + delay: 15, + aircraft: 'A359 D-AIXA', + }); + }); + + it('FE-NATIVE-WIDGETFLIGHT-005: says landed once touched down, and nothing without a flight', () => { + expect( + widgetFlight([leg({ phase: 'landed', landed_at: new Date(ARR).toISOString() })], ARR + H, '/trips/1', CLOCK) + ?.landed + ).toBe(true); + expect(widgetFlight([], DEP, '/trips/1', CLOCK)).toBeUndefined(); + }); +}); + +describe('liveFlightOf', () => { + it('FE-NATIVE-WIDGETFLIGHT-006: holds the Live Activity from three hours before take-off to an hour after touchdown', () => { + const flight = widgetFlight([leg()], DEP - H, '/trips/1', CLOCK); + const at = (ms: number) => liveFlightOf(flight, ms / 1000); + expect(at(DEP - 4 * H)).toBeUndefined(); + expect(at(DEP - 2 * H)).toMatchObject({ + number: 'LH 400', + from: 'FRA', + to: 'JFK', + depTime: '13:50', + arrTime: '16:35', + }); + expect(at(ARR + 2 * H)).toBeUndefined(); + expect(liveFlightOf({ ...(flight as NonNullable), landed: true }, (DEP + H) / 1000)).toBeUndefined(); + expect(liveFlightOf(undefined, DEP / 1000)).toBeUndefined(); + }); +}); + +describe('widget phase', () => { + it('FE-NATIVE-WIDGETFLIGHT-007: a late departure goes along as the expected one, and the flight in the air says so', () => { + const late = widgetFlight([leg({ departure_delay_min: 40 })], DEP, '/trips/1', CLOCK); + expect(late?.depExpected).toBe(DEP / 1000 + 40 * 60); + expect(late?.airborne).toBeUndefined(); + expect(widgetFlight([leg({ phase: 'airborne' })], DEP + H, '/trips/1', CLOCK)?.airborne).toBe(true); + expect(liveFlightOf(late, DEP / 1000)?.dep).toBe(DEP / 1000 + 40 * 60); + }); + + it('FE-NATIVE-WIDGETFLIGHT-008: a flight the feed lost in the air stops being picked two hours after arrival', () => { + expect(pickWidgetLeg([leg({ phase: 'airborne' })], ARR + 3 * H)).toBeNull(); + }); +}); diff --git a/client/src/native/widgetFlight.ts b/client/src/native/widgetFlight.ts new file mode 100644 index 000000000..cfd112c08 --- /dev/null +++ b/client/src/native/widgetFlight.ts @@ -0,0 +1,127 @@ +import type { FlightLiveLeg } from '@trek/shared'; +import { airportTime, toMs } from '../utils/flightLiveModel'; + +/** + * The flight a home-screen widget follows: the trip's next one or the one in + * the air. Times go along as epoch seconds so the widget moves its countdown + * and its aircraft on with the clock between two snapshots; the clock times + * at either airport go along formatted, since the widget has no zone data. + * Optional on the native side (WidgetSnapshot.swift, WidgetSnapshot.kt): an + * older app binary ignores it. + */ +export interface WidgetFlight { + number: string; + from: string; + to: string; + fromCity?: string; + toCity?: string; + /** Planned departure and arrival, epoch seconds. */ + dep: number; + arr: number; + /** Observed take-off, epoch seconds. */ + depActual?: number; + /** Before take-off: the planned departure plus the delay seen so far, epoch seconds. */ + depExpected?: number; + /** The feed sees the aircraft in the air right now. */ + airborne?: boolean; + /** Touchdown once landed, else the estimate while in the air, epoch seconds. */ + arrExpected?: number; + landed?: boolean; + /** Clock times at the airports: planned departure, planned arrival, expected arrival. */ + depTime: string; + arrTime: string; + arrTimeExpected?: string; + /** Minutes late against the schedule (negative when early). */ + delay?: number; + /** "A359 D-AIXA". */ + aircraft?: string; + /** When the feed last heard the aircraft, epoch seconds. */ + seen?: number; + path: string; +} + +/** How long after landing the widget keeps the flight before moving on to the next. */ +const KEEP_AFTER_LANDING_S = 2 * 60 * 60; +/** How far ahead a flight is worth the widget's attention. */ +const LOOK_AHEAD_S = 7 * 24 * 60 * 60; + +const sec = (ms: number | null): number | undefined => (ms == null ? undefined : Math.round(ms / 1000)); + +/** + * The leg to show: one in the air or rolling first, else the earliest whose + * arrival (with two hours' grace) is still ahead and that departs within a week. + */ +export function pickWidgetLeg(legs: FlightLiveLeg[], nowMs: number): FlightLiveLeg | null { + const now = nowMs / 1000; + const arrivalOf = (l: FlightLiveLeg) => + sec(toMs(l.landed_at) ?? toMs(l.estimated_arrival) ?? toMs(l.scheduled_arrival)); + // A leg the feed lost in the air still counts only until two hours after its arrival. + const moving = legs.find((l) => { + const arr = arrivalOf(l); + return (l.phase === 'airborne' || l.phase === 'taxiing') && (arr == null || arr + KEEP_AFTER_LANDING_S > now); + }); + if (moving) return moving; + return ( + legs + .filter((l) => { + const dep = sec(toMs(l.scheduled_departure)); + const arr = sec(toMs(l.landed_at) ?? toMs(l.scheduled_arrival)); + return dep != null && arr != null && arr + KEEP_AFTER_LANDING_S > now && dep - now < LOOK_AHEAD_S; + }) + .sort((a, b) => (toMs(a.scheduled_departure) ?? 0) - (toMs(b.scheduled_departure) ?? 0))[0] ?? null + ); +} + +/** What the feed observed about a leg, for the widget: each part only when it is known. */ +function observed( + leg: FlightLiveLeg, + depSeconds: number, + time: (ms: number, tz: string | null) => string +): Partial { + const landed = toMs(leg.landed_at); + const expected = landed ?? (leg.phase === 'airborne' ? toMs(leg.estimated_arrival) : null); + const lateBy = leg.departure_delay_min ?? 0; + const delay = leg.arrival_delay_min ?? leg.departure_delay_min; + const aircraft = [leg.aircraft?.type, leg.aircraft?.registration].filter(Boolean).join(' '); + return { + ...(leg.departed_at + ? { depActual: sec(toMs(leg.departed_at)) } + : lateBy > 0 + ? { depExpected: depSeconds + lateBy * 60 } + : {}), + ...(leg.phase === 'airborne' ? { airborne: true } : {}), + ...(expected != null + ? { arrExpected: sec(expected), arrTimeExpected: time(expected, leg.destination.timezone) } + : {}), + ...(landed != null ? { landed: true } : {}), + ...(delay != null ? { delay } : {}), + ...(aircraft ? { aircraft } : {}), + ...(leg.last_seen_at ? { seen: sec(toMs(leg.last_seen_at)) } : {}), + }; +} + +export function widgetFlight( + legs: FlightLiveLeg[], + nowMs: number, + tripPath: string, + clock: { locale: string; timeFormat: string } +): WidgetFlight | undefined { + const leg = pickWidgetLeg(legs, nowMs); + const dep = leg ? toMs(leg.scheduled_departure) : null; + const arr = leg ? toMs(leg.scheduled_arrival) : null; + if (!leg || dep == null || arr == null) return undefined; + const time = (ms: number, tz: string | null) => airportTime(ms, tz, clock.locale, clock.timeFormat); + return { + number: leg.flight_number, + from: leg.origin.code, + to: leg.destination.code, + ...(leg.origin.name ? { fromCity: leg.origin.name } : {}), + ...(leg.destination.name ? { toCity: leg.destination.name } : {}), + dep: Math.round(dep / 1000), + arr: Math.round(arr / 1000), + depTime: time(dep, leg.origin.timezone), + arrTime: time(arr, leg.destination.timezone), + ...observed(leg, Math.round(dep / 1000), time), + path: `${tripPath}?booking=${leg.reservation_id}`, + }; +} diff --git a/client/src/native/widgetMedia.ts b/client/src/native/widgetMedia.ts new file mode 100644 index 000000000..82938c8d1 --- /dev/null +++ b/client/src/native/widgetMedia.ts @@ -0,0 +1,107 @@ +import { fetchWeather } from '../services/weatherQueue'; +import { temperature } from './widgetExtras'; +import type { WidgetWeather } from './widgets'; + +/** + * The two things the widget snapshot needs from the network: the weather where + * the trip is, and the trip's cover as a small JPEG the widget can draw without + * a session of its own. Both are best effort: offline or failing, the widget + * simply goes without them, and both are kept so a quarter-hourly sync does not + * fetch them again. + */ + +const WEATHER_TTL_MS = 60 * 60 * 1000; +const weatherCache = new Map(); + +export async function widgetWeather( + { lat, lng }: { lat: number; lng: number }, + { date, lang, unit, place }: { date: string; lang: string; unit: string | undefined; place?: string | null } +): Promise { + const key = `${lat.toFixed(2)},${lng.toFixed(2)},${date},${lang},${unit ?? ''}`; + const hit = weatherCache.get(key); + if (hit && Date.now() - hit.at < WEATHER_TTL_MS) return hit.value; + let value: WidgetWeather | null = null; + try { + const w = await fetchWeather(lat, lng, date, lang); + if (!w.error && Number.isFinite(w.temp)) { + value = { + temp: temperature(w.temp, unit), + ...(w.temp_max != null ? { high: temperature(w.temp_max, unit) } : {}), + ...(w.temp_min != null ? { low: temperature(w.temp_min, unit) } : {}), + main: w.main, + label: w.description, + ...(place ? { place } : {}), + ...(w.precipitation_probability_max != null ? { rain: Math.round(w.precipitation_probability_max) } : {}), + }; + } + } catch { + // Offline or the provider failed: the widget shows no weather until the next sync. + value = null; + } + weatherCache.set(key, { at: Date.now(), value }); + return value; +} + +const COVER_KEY = 'trek.widgetCovers'; +/** Covers kept, one per trip a widget can show (widgetTripChoices). */ +const COVER_KEEP = 6; +const COVER_MAX_PX = 720; +const COVER_MAX_BYTES = 15 * 1024 * 1024; +/** Kept under this so the keychain item the widget reads stays small. */ +const COVER_MAX_BASE64 = 160_000; + +function storedCovers(): { url: string; data: string }[] { + try { + const raw = localStorage.getItem(COVER_KEY); + const parsed: unknown = raw ? JSON.parse(raw) : []; + return Array.isArray(parsed) ? (parsed as { url: string; data: string }[]) : []; + } catch { + return []; + } +} + +function storedCover(url: string): string | null { + return storedCovers().find((c) => c.url === url)?.data ?? null; +} + +/** Newest first, the oldest dropped past COVER_KEEP. */ +function storeCover(url: string, data: string): void { + try { + const rest = storedCovers().filter((c) => c.url !== url); + localStorage.setItem(COVER_KEY, JSON.stringify([{ url, data }, ...rest].slice(0, COVER_KEEP))); + } catch { + // Storage full: the cover is fetched again next time, nothing else depends on it. + } +} + +/** + * The cover at `url` scaled to fit COVER_MAX_PX, as base64 JPEG without the + * data: prefix. Null without a cover, offline, or for anything not an image. + */ +export async function widgetCover(url: string | null | undefined): Promise { + if (!url) return null; + const stored = storedCover(url); + if (stored) return stored; + try { + const res = await fetch(url, { credentials: 'include', signal: AbortSignal.timeout(10_000) }); + const length = Number(res.headers.get('content-length') ?? 0); + if (!res.ok || length > COVER_MAX_BYTES) return null; + const blob = await res.blob(); + if (!blob.type.startsWith('image/') || blob.size > COVER_MAX_BYTES) return null; + const bitmap = await createImageBitmap(blob); + const scale = Math.min(1, COVER_MAX_PX / Math.max(bitmap.width, bitmap.height)); + const canvas = document.createElement('canvas'); + canvas.width = Math.round(bitmap.width * scale); + canvas.height = Math.round(bitmap.height * scale); + canvas.getContext('2d')?.drawImage(bitmap, 0, 0, canvas.width, canvas.height); + bitmap.close(); + let data = canvas.toDataURL('image/jpeg', 0.74).split(',')[1] ?? ''; + if (data.length > COVER_MAX_BASE64) data = canvas.toDataURL('image/jpeg', 0.5).split(',')[1] ?? ''; + if (!data || data.length > COVER_MAX_BASE64) return null; + storeCover(url, data); + return data; + } catch { + // Offline, a timeout or an image the WebView cannot decode: no cover this time. + return null; + } +} diff --git a/client/src/native/widgetOnline.ts b/client/src/native/widgetOnline.ts new file mode 100644 index 000000000..21b3f875b --- /dev/null +++ b/client/src/native/widgetOnline.ts @@ -0,0 +1,227 @@ +import { CONTINENT_MAP } from '@trek/shared'; +import apiClient, { collabApi, packingApi } from '../api/client'; +import type { PackingItem } from '../types'; + +/** + * The widget parts that only the server knows: the packing bags with their + * weights, the countries of the Atlas, and the trip's chat and polls. Each is + * best effort, so offline or with the addon off the widget goes without it; + * client/ios/App/TREKWidgets/WidgetSnapshot.swift reads the shapes. + */ + +interface WidgetBag { + name: string; + color: string; + grams: number; + limit?: number; + packed: number; + total: number; +} + +export interface WidgetPackingDetail { + bags: WidgetBag[]; + missing: { name: string; category: string | null; color: string | null }[]; +} + +export interface WidgetAtlas { + count: number; + codes: string[]; + /** The latest visited, newest first, with their names in the user's language. */ + recent: { code: string; name: string }[]; + continents: { name: string; count: number }[]; + trips?: number; + days?: number; +} + +export interface WidgetCollab { + members: { name: string; initials: string }[]; + messages: { author: string; initials: string; text: string; at: string | null; mine: boolean }[]; + poll?: { question: string; options: { label: string; votes: number }[]; voters: number }; + path: string; +} + +const HEX = /^#[0-9a-f]{6}$/i; + +/** + * Server answers kept for a while: the widgets sync every quarter hour for up + * to six trips, and bags, chat and polls do not change that fast. + */ +const NETWORK_TTL_MS = 10 * 60 * 1000; +const networkCache = new Map(); + +async function cached(key: string, read: () => Promise): Promise { + const hit = networkCache.get(key); + if (hit && Date.now() - hit.at < NETWORK_TTL_MS) return hit.value as T; + const value = await read(); + networkCache.set(key, { at: Date.now(), value }); + return value; +} + +function initials(name: string): string { + const parts = name + .trim() + .split(/[\s._-]+/) + .filter(Boolean); + const letters = parts.length > 1 ? parts[0][0] + parts[1][0] : name.trim().slice(0, 2); + return letters.toUpperCase(); +} + +/** The bags with what is in them, and the items still to pack, those in a bag first. */ +export async function packingDetail( + tripId: number, + items: PackingItem[], + limit = 8 +): Promise { + if (items.length === 0) return null; + let bags: { + id: number; + name: string; + color: string; + weight_limit_grams?: number | null; + total_weight_grams?: number; + }[] = []; + try { + const res = await cached(`bags:${tripId}`, () => packingApi.listBags(tripId) as Promise<{ bags?: typeof bags }>); + bags = res.bags ?? []; + } catch { + // Offline or no bags: the widget shows the items without them. + bags = []; + } + const byBag = new Map(bags.map((b) => [b.id, b])); + const summaries = bags.map((b) => { + const inBag = items.filter((i) => i.bag_id === b.id); + const grams = b.total_weight_grams ?? inBag.reduce((sum, i) => sum + (i.weight_grams ?? 0) * (i.quantity ?? 1), 0); + return { + name: b.name, + // Empty when the bag has no usable colour: the widget then uses its own blue. + color: HEX.test(b.color) ? b.color : '', + grams, + ...(b.weight_limit_grams ? { limit: b.weight_limit_grams } : {}), + packed: inBag.filter((i) => i.checked).length, + total: inBag.length, + }; + }); + const missing = items + .filter((i) => !i.checked) + .sort((a, b) => Number(b.bag_id != null) - Number(a.bag_id != null) || a.sort_order - b.sort_order) + .slice(0, limit) + .map((i) => { + const bag = i.bag_id != null ? byBag.get(i.bag_id) : undefined; + return { name: i.name, category: i.category ?? null, color: bag && HEX.test(bag.color) ? bag.color : null }; + }); + return { bags: summaries.filter((b) => b.total > 0), missing }; +} + +interface AtlasStats { + countries?: { code: string; lastVisit?: string | null; firstVisit?: string | null }[]; + stats?: { totalCountries?: number; totalTrips?: number; totalDays?: number }; +} + +const ATLAS_TTL_MS = 60 * 60 * 1000; +let atlasCache: { at: number; language: string; value: WidgetAtlas | null } | null = null; + +/** The countries of the Atlas, the latest ones named, and how they spread over the continents. */ +export async function atlasSummary(language: string): Promise { + if (atlasCache && atlasCache.language === language && Date.now() - atlasCache.at < ATLAS_TTL_MS) + return atlasCache.value; + const value = await readAtlas(language); + atlasCache = { at: Date.now(), language, value }; + return value; +} + +async function readAtlas(language: string): Promise { + let data: AtlasStats; + try { + data = (await apiClient.get('/addons/atlas/stats', { timeout: 10_000 })).data as AtlasStats; + } catch { + // The addon is off or the server unreachable: no atlas widget data this time. + return null; + } + const countries = (data.countries ?? []).filter((c) => /^[A-Z]{2}$/.test(c.code)); + let names: Intl.DisplayNames | null = null; + try { + names = new Intl.DisplayNames([language], { type: 'region' }); + } catch { + names = null; + } + const recent = [...countries] + .sort((a, b) => (b.lastVisit ?? b.firstVisit ?? '').localeCompare(a.lastVisit ?? a.firstVisit ?? '')) + .slice(0, 4) + .map((c) => ({ code: c.code, name: names?.of(c.code) ?? c.code })); + const perContinent = new Map(); + for (const c of countries) { + const continent = CONTINENT_MAP[c.code]; + if (continent) perContinent.set(continent, (perContinent.get(continent) ?? 0) + 1); + } + return { + count: data.stats?.totalCountries ?? countries.length, + codes: countries.map((c) => c.code), + recent, + continents: [...perContinent].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count), + ...(data.stats?.totalTrips ? { trips: data.stats.totalTrips } : {}), + ...(data.stats?.totalDays ? { days: data.stats.totalDays } : {}), + }; +} + +interface Message { + user_id: number; + username: string; + text: string; + created_at: string | null; + deleted: number | null; +} + +interface Poll { + question: string; + is_closed: boolean; + options: { text: unknown; label: unknown; voters: { user_id: number }[] }[]; +} + +/** Who travels along, the latest messages in the trip chat, and the open poll. */ +export async function collabSummary( + tripId: number, + path: string, + members: string[], + me: number | null +): Promise { + let messages: Message[] = []; + let polls: Poll[] = []; + try { + const [m, p] = await Promise.all([ + cached(`messages:${tripId}`, () => collabApi.getMessages(tripId) as Promise<{ messages?: Message[] }>), + cached(`polls:${tripId}`, () => collabApi.getPolls(tripId) as Promise<{ polls?: Poll[] }>), + ]); + messages = m.messages ?? []; + polls = p.polls ?? []; + } catch { + // Offline or the collab addon is off: the widget shows the members only. + if (members.length < 2) return null; + } + const latest = messages + .filter((m) => !m.deleted && m.text.trim()) + .sort((a, b) => (a.created_at ?? '').localeCompare(b.created_at ?? '')) + .slice(-3) + .map((m) => ({ + author: m.username, + initials: initials(m.username), + text: m.text.trim().slice(0, 140), + at: m.created_at, + mine: me != null && m.user_id === me, + })); + const open = polls.find((p) => !p.is_closed); + const label = (o: Poll['options'][number]) => String(o.label ?? o.text ?? ''); + const poll = open + ? { + question: open.question, + options: open.options.slice(0, 4).map((o) => ({ label: label(o), votes: o.voters.length })), + voters: new Set(open.options.flatMap((o) => o.voters.map((v) => v.user_id))).size, + } + : undefined; + if (members.length < 2 && latest.length === 0 && !poll) return null; + return { + members: members.slice(0, 6).map((name) => ({ name, initials: initials(name) })), + messages: latest, + ...(poll ? { poll } : {}), + path, + }; +} diff --git a/client/src/native/widgets.test.ts b/client/src/native/widgets.test.ts new file mode 100644 index 000000000..f220ae68a --- /dev/null +++ b/client/src/native/widgets.test.ts @@ -0,0 +1,407 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Day, Trip } from '../types'; + +vi.mock('./platform', () => ({ isNativeIos: vi.fn(() => true), isNativeApp: vi.fn(() => true) })); +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn(() => true) })); +vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() })); +vi.mock('./trekShell', () => ({ + TrekShell: { + setWidgetSnapshot: vi.fn(async () => {}), + syncTripDay: vi.fn(async () => ({ running: true })), + endTripDay: vi.fn(async () => {}), + }, +})); + +import { TrekShell } from './trekShell'; +import { + buildSnapshot, + liveDayDue, + pickTrip, + publishWidgets, + todayOf, + tripDayState, + widgetTripChoices, + withBookings, +} from './widgets'; + +const trip = (id: number, start: string | null, end: string | null, archived = 0) => + ({ id, title: `Trip ${id}`, start_date: start, end_date: end, is_archived: archived }) as unknown as Trip; + +const day = (id: number, n: number, date: string, places: { name: string; time?: string }[]) => + ({ + id, + trip_id: 1, + day_number: n, + date, + assignments: places.map((p, i) => ({ + id: id * 10 + i, + order_index: i, + place: { name: p.name, place_time: p.time ?? null }, + })), + }) as unknown as Day; + +const labels = { + nextTrip: 'Next', + today: 'Today', + noTrip: 'None', + inDays: 'in {n} days', + tomorrow: 'Tomorrow', + nothingPlanned: '-', +}; + +describe('pickTrip', () => { + it('prefers the running trip, then the next upcoming one', () => { + const trips = [ + trip(1, '2026-12-01', '2026-12-05'), + trip(2, '2026-11-20', '2026-11-25'), + trip(3, '2026-11-01', '2026-11-10'), + ]; + expect(pickTrip(trips, '2026-11-06')?.id).toBe(3); + expect(pickTrip(trips, '2026-11-12')?.id).toBe(2); + }); + + it('of several running trips takes the dashboard hero: the one that started first', () => { + const trips = [ + trip(1, '2026-11-02', '2026-11-06'), + trip(2, '2026-10-20', '2026-11-18'), + trip(3, '2026-11-04', '2026-11-12'), + ]; + expect(pickTrip(trips, '2026-11-06')?.id).toBe(2); + }); + + it('skips undated, archived and finished trips', () => { + expect( + pickTrip( + [trip(1, null, null), trip(2, '2026-12-01', '2026-12-02', 1), trip(3, '2026-01-01', '2026-01-02')], + '2026-11-06' + ) + ).toBeNull(); + }); +}); + +describe('todayOf and tripDayState', () => { + const days = [ + day(2, 2, '2026-11-07', []), + day(1, 1, '2026-11-06', [{ name: 'Museum', time: '09:00' }, { name: 'Walk' }, { name: 'Dinner', time: '19:30' }]), + ]; + + it('finds today in day order and keeps the plan order', () => { + const today = todayOf( + trip(1, '2026-11-06', '2026-11-07'), + days, + '2026-11-06', + (n, m) => `${n}/${m}`, + (t) => `T${t}` + ); + expect(today?.dayLabel).toBe('1/2'); + expect(today?.stops.map((s) => s.name)).toEqual(['Museum', 'Walk', 'Dinner']); + expect(today?.stops[0]).toMatchObject({ time: 'T09:00', minutes: 540 }); + }); + + it('is null on a day outside the trip', () => { + expect( + todayOf( + trip(1, '2026-11-06', '2026-11-07'), + days, + '2026-11-09', + () => '', + (t) => t + ) + ).toBeNull(); + }); + + it('names the next timed stop and counts the ones behind', () => { + const today = todayOf( + trip(1, '2026-11-06', '2026-11-07'), + days, + '2026-11-06', + () => 'D', + (t) => t + ); + if (!today) throw new Error('the trip runs today'); + expect(tripDayState(today, 8 * 60, 'done')).toMatchObject({ nextName: 'Museum', done: 0, total: 2 }); + expect(tripDayState(today, 12 * 60, 'done')).toMatchObject({ nextName: 'Dinner', nextTime: '19:30', done: 1 }); + expect(tripDayState(today, 22 * 60, 'done')).toMatchObject({ nextName: 'done', done: 2, nextTime: undefined }); + }); + + it('gives the Android Live Update the next stop in minutes and one colour per timed stop', () => { + const state = tripDayState( + { + tripTitle: 'T', + path: '/trips/1', + dayLabel: 'D', + stops: [ + { name: 'Museum', time: '10:00', minutes: 600, color: '#D6273B' }, + { name: 'Walk', time: null, minutes: null }, + { name: 'Dinner', time: '19:30', minutes: 1170, color: null }, + ], + }, + 12 * 60, + 'done' + ); + expect(state).toMatchObject({ + nextName: 'Dinner', + nextMinutes: 1170, + colors: ['#D6273B', null], + done: 1, + total: 2, + }); + expect( + tripDayState({ tripTitle: 'T', path: '/', dayLabel: 'D', stops: [] }, 0, 'done').nextMinutes + ).toBeUndefined(); + }); +}); + +describe('liveDayDue', () => { + const evening = { + tripTitle: 'T', + path: '/trips/1', + dayLabel: 'D', + stops: [ + { name: 'Walk', time: null, minutes: null }, + { name: 'Uber to the airport', time: '18:00', minutes: 18 * 60 }, + { name: 'Flight', time: '21:00', minutes: 21 * 60 }, + ], + }; + + it('keeps the lock screen free until three hours before the first timed stop', () => { + expect(liveDayDue(evening, 6 * 60 + 32)).toBe(false); + expect(liveDayDue(evening, 14 * 60 + 59)).toBe(false); + expect(liveDayDue(evening, 15 * 60)).toBe(true); + }); + + it('stays on through the day once it has started, until the day is done', () => { + expect(liveDayDue(evening, 19 * 60)).toBe(true); + expect(liveDayDue(evening, 23 * 60 + 30)).toBe(true); + }); + + it('starts from the earliest timed stop, wherever it stands in the list', () => { + const early = { ...evening, stops: [...evening.stops, { name: 'Breakfast', time: '08:00', minutes: 8 * 60 }] }; + expect(liveDayDue(early, 5 * 60)).toBe(true); + expect(liveDayDue(early, 4 * 60 + 59)).toBe(false); + }); + + it('has nothing to show on a day without times', () => { + expect(liveDayDue({ ...evening, stops: [{ name: 'Walk', time: null, minutes: null }] }, 12 * 60)).toBe(false); + }); +}); + +describe('publishWidgets', () => { + it('writes the snapshot without the internal minutes and ends the activity on a day without times', async () => { + const snapshot = buildSnapshot( + trip(1, '2026-11-06', '2026-11-07'), + { tripTitle: 'Trip 1', path: '/trips/1', dayLabel: 'D', stops: [{ name: 'Walk', time: null, minutes: null }] }, + labels + ); + expect(snapshot.today?.stops[0]).toEqual({ name: 'Walk', time: null }); + await publishWidgets(snapshot, { + tripTitle: 'Trip 1', + path: '/trips/1', + dayLabel: 'D', + nextName: 'x', + nextTime: undefined, + done: 0, + total: 0, + }); + expect(JSON.parse(vi.mocked(TrekShell.setWidgetSnapshot).mock.calls[0][0].json).trip.path).toBe('/trips/1'); + expect(TrekShell.endTripDay).toHaveBeenCalled(); + expect(TrekShell.syncTripDay).not.toHaveBeenCalled(); + }); +}); + +describe('the richer snapshot', () => { + it('puts the timed bookings of the day between the stops and gives the day its place in the trip', () => { + const days = [ + day(1, 1, '2026-11-06', [{ name: 'Museum', time: '09:00' }, { name: 'Walk' }, { name: 'Dinner', time: '19:30' }]), + day(2, 2, '2026-11-07', []), + ]; + const plain = todayOf( + trip(1, '2026-11-06', '2026-11-07'), + days, + '2026-11-06', + () => 'D', + (t) => t + ); + if (!plain) throw new Error('the trip runs today'); + const today = withBookings( + plain, + [ + { id: 1, trip_id: 1, title: 'Train', type: 'train', status: 'confirmed', reservation_time: '2026-11-06T12:15' }, + { + id: 2, + trip_id: 1, + title: 'Tomorrow', + type: 'flight', + status: 'confirmed', + reservation_time: '2026-11-07T08:00', + }, + { id: 3, trip_id: 1, title: 'Gone', type: 'event', status: 'cancelled', reservation_time: '2026-11-06T10:00' }, + ] as never, + '2026-11-06', + (t) => t + ); + expect(today.stops.map((s) => s.name)).toEqual(['Museum', 'Walk', 'Train', 'Dinner']); + expect(today.stops[2]).toMatchObject({ time: '12:15', minutes: 735, symbol: 'tram.fill' }); + expect(today).toMatchObject({ index: 1, total: 2 }); + expect(withBookings(plain, [], '2026-11-06', (t) => t)).toBe(plain); + }); + + it('makes a stop of every leg of a flight with a stopover, and keeps a flight in the air ahead until it lands', () => { + const plain = todayOf( + trip(1, '2026-11-09', '2026-11-10'), + [day(5, 1, '2026-11-09', []), day(6, 2, '2026-11-10', [])], + '2026-11-09', + () => 'D', + (t) => t + ); + if (!plain) throw new Error('the trip runs today'); + const legs = [ + { from: 'SNA', to: 'ATL', dep_day_id: 5, dep_time: '14:00', arr_day_id: 5, arr_time: '21:11' }, + { from: 'ATL', to: 'ORF', dep_day_id: 5, dep_time: '22:40', arr_day_id: 6, arr_time: '00:31' }, + ]; + const today = withBookings( + plain, + [ + { id: 1, trip_id: 1, title: 'Car', type: 'car', status: 'confirmed', reservation_time: '2026-11-09T13:00' }, + { + id: 2, + trip_id: 1, + title: 'SNA → ATL → ORF', + type: 'flight', + status: 'confirmed', + reservation_time: '2026-11-09T14:00', + metadata: JSON.stringify({ legs }), + }, + ] as never, + '2026-11-09', + (t) => t + ); + expect(today.stops.map((s) => s.name)).toEqual(['Car', 'SNA → ATL', 'ATL → ORF']); + // In the air on the first leg, between the legs, and on the second leg past midnight. + expect(tripDayState(today, 16 * 60 + 22, 'done')).toMatchObject({ nextName: 'SNA → ATL', done: 1, total: 3 }); + expect(tripDayState(today, 21 * 60 + 30, 'done')).toMatchObject({ nextName: 'ATL → ORF', done: 2 }); + expect(tripDayState(today, 23 * 60 + 30, 'done')).toMatchObject({ nextName: 'ATL → ORF', done: 2 }); + }); + + it('lands a leg without an arrival day on the day it leaves', () => { + const plain = todayOf( + trip(1, '2026-11-09', '2026-11-09'), + [day(5, 1, '2026-11-09', [])], + '2026-11-09', + () => 'D', + (t) => t + ); + if (!plain) throw new Error('the trip runs today'); + const legs = [ + { from: 'SNA', to: 'ATL', dep_day_id: 5, dep_time: '08:00', arr_time: '10:00' }, + { from: 'ATL', to: 'ORF', dep_day_id: 5, dep_time: '12:00', arr_time: '14:00' }, + ]; + const today = withBookings( + plain, + [ + { id: 2, trip_id: 1, title: 'Hop', type: 'flight', status: 'confirmed', metadata: JSON.stringify({ legs }) }, + ] as never, + '2026-11-09', + (t) => t + ); + expect(tripDayState(today, 15 * 60, 'done')).toMatchObject({ nextName: 'done', done: 2 }); + }); + + it('counts a booking with an end time as under way until it ends', () => { + const plain = todayOf( + trip(1, '2026-11-09', '2026-11-09'), + [day(5, 1, '2026-11-09', [])], + '2026-11-09', + () => 'D', + (t) => t + ); + if (!plain) throw new Error('the trip runs today'); + const today = withBookings( + plain, + [ + { + id: 1, + trip_id: 1, + title: 'Tour', + type: 'tour', + status: 'confirmed', + reservation_time: '2026-11-09T10:00', + reservation_end_time: '2026-11-09T13:00', + }, + ] as never, + '2026-11-09', + (t) => t + ); + expect(tripDayState(today, 11 * 60, 'done')).toMatchObject({ nextName: 'Tour', done: 0 }); + expect(tripDayState(today, 13 * 60 + 1, 'done')).toMatchObject({ nextName: 'done', done: 1 }); + }); + + it('carries the extras and leaves out what is empty', () => { + const snapshot = buildSnapshot( + { ...trip(1, '2026-11-06', '2026-11-07'), day_count: 2 } as Trip, + { + tripTitle: 'Trip 1', + path: '/trips/1', + dayLabel: 'D', + index: 1, + total: 2, + stops: [{ name: 'Tea', time: '10:00', minutes: 600, color: '#2FA37A', symbol: 'leaf.fill' }], + }, + labels, + { + place: 'Kyoto, Japan', + cover: null, + placeCount: 12, + memberCount: 0, + weather: { temp: 18, main: 'Clear', label: 'Sunny' }, + bookings: [], + todos: { open: 1, total: 2, items: [], path: '/trips/1?tab=listen' }, + packing: null, + } + ); + expect(snapshot.trip).toEqual({ + title: 'Trip 1', + start: '2026-11-06', + end: '2026-11-07', + path: '/trips/1', + place: 'Kyoto, Japan', + dayCount: 2, + placeCount: 12, + }); + expect(snapshot.today).toEqual({ + dayLabel: 'D', + index: 1, + total: 2, + stops: [{ name: 'Tea', time: '10:00', minutes: 600, color: '#2FA37A', symbol: 'leaf.fill' }], + }); + expect(snapshot.weather).toEqual({ temp: 18, main: 'Clear', label: 'Sunny' }); + expect(snapshot.bookings).toEqual([]); + expect(snapshot.todos?.open).toBe(1); + expect(snapshot).not.toHaveProperty('packing'); + }); +}); + +describe('widgets set to a trip', () => { + it('offers the trips running or ahead, in the dashboard order, at most six', () => { + const trips = [ + trip(1, '2026-01-01', '2026-01-05'), + trip(2, '2026-12-01', '2026-12-05'), + trip(3, '2026-11-04', '2026-11-12'), + trip(4, '2026-11-20', '2026-11-22', 1), + trip(5, null, null), + ...[6, 7, 8, 9, 10, 11].map((id) => trip(id, `2027-0${id - 5}-01`, `2027-0${id - 5}-03`)), + ]; + expect(widgetTripChoices(trips, '2026-11-06').map((t) => t.id)).toEqual([3, 2, 6, 7, 8, 9]); + }); + + it('writes each trip under its own key and the list to pick from', async () => { + vi.mocked(TrekShell.setWidgetSnapshot).mockClear(); + const snapshot = buildSnapshot(trip(2, '2026-12-01', '2026-12-05'), null, labels); + await publishWidgets(snapshot, null, [ + { id: 2, title: 'Trip 2', start: '2026-12-01', end: '2026-12-05', snapshot }, + ]); + const calls = vi.mocked(TrekShell.setWidgetSnapshot).mock.calls.map(([options]) => options); + expect(calls.map((c) => c.key)).toEqual([undefined, 'trip.2', 'trips']); + expect(JSON.parse(calls[2].json)).toEqual([{ id: 2, title: 'Trip 2', start: '2026-12-01', end: '2026-12-05' }]); + }); +}); diff --git a/client/src/native/widgets.ts b/client/src/native/widgets.ts new file mode 100644 index 000000000..62adf997e --- /dev/null +++ b/client/src/native/widgets.ts @@ -0,0 +1,466 @@ +import type { Day, Reservation, Trip } from '../types'; +import { getFlightLegs, getTrainLegs, usesStationRoute } from '../utils/flightLegs'; +import { splitReservationDateTime } from '../utils/formatters'; +import { heroTrip, sortTripsByRelevance } from '../utils/heroTrip'; +import { hasNativeFeature } from './capabilities'; +import { isNativeApp } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell } from './trekShell'; +import { stopLook, type WidgetBooking, type WidgetPacking, type WidgetTodos } from './widgetExtras'; +import type { WidgetFlight } from './widgetFlight'; +import type { WidgetAtlas, WidgetCollab, WidgetPackingDetail } from './widgetOnline'; + +/** + * What the home-screen widgets and the travel-day Live Activity show, built from + * the trips this device keeps offline (db/offlineDb) and handed to the app + * (TrekShell.setWidgetSnapshot, syncTripDay). The texts go along translated, so + * the widgets speak the app's language without localising anything themselves. + * Everything past trip, today and the first six labels is optional on the Swift + * side (client/ios/App/TREKWidgets/WidgetSnapshot.swift), so an older app + * binary ignores it and a newer one copes without it. + */ +export interface WidgetLabels { + nextTrip: string; + today: string; + noTrip: string; + /** Contains "{n}". */ + inDays: string; + tomorrow: string; + nothingPlanned: string; + days?: string; + bookings?: string; + noBookings?: string; + todos?: string; + noTodos?: string; + packing?: string; + confirmed?: string; + pending?: string; + todayShort?: string; + tomorrowShort?: string; + now?: string; + places?: string; + travellers?: string; + allDone?: string; + missing?: string; + countries?: string; + world?: string; + group?: string; + poll?: string; + votes?: string; + noMessages?: string; + departure?: string; + /** The flight widget: its title and the words around the moment. */ + flight?: string; + /** Contains "{time}", where the widget puts its own running countdown. */ + flightDeparts?: string; + flightInAir?: string; + /** Contains "{time}". */ + flightLands?: string; + flightLanded?: string; + flightOnTime?: string; + /** Contains "{m}". */ + flightLate?: string; + /** Contains "{m}". */ + flightEarly?: string; + flightEstimated?: string; + /** Past the departure time with the aircraft not yet in the air. */ + flightReady?: string; + noFlight?: string; + /** Android, which has no running countdown text: "{d} d {h} h", "{h} h {m} min", "{m} min". */ + durDaysHours?: string; + durHoursMinutes?: string; + durMinutes?: string; +} + +interface WidgetStop { + time: string | null; + name: string; + /** Minutes after midnight, for picking the next stop and the widget's now line. */ + minutes: number | null; + color?: string | null; + symbol?: string | null; + /** Minutes after midnight it ends, past midnight as 1440: a flight in the air is not done yet. */ + endMinutes?: number | null; +} + +interface SnapshotStop { + time: string | null; + name: string; + minutes?: number; + color?: string; + symbol?: string; +} + +export interface WidgetSnapshot { + trip: { + title: string; + start: string; + end: string; + path: string; + place?: string; + /** A small JPEG of the cover, base64. */ + cover?: string; + dayCount?: number; + placeCount?: number; + memberCount?: number; + } | null; + today: { dayLabel: string; stops: SnapshotStop[]; index?: number; total?: number } | null; + weather?: WidgetWeather; + bookings?: WidgetBooking[]; + todos?: WidgetTodos; + packing?: WidgetPacking & Partial; + atlas?: WidgetAtlas; + collab?: WidgetCollab; + flight?: WidgetFlight; + labels: WidgetLabels; +} + +export interface WidgetWeather { + temp: number; + high?: number; + low?: number; + /** The provider's main condition ("Clear", "Rain", ...), which the widget turns into a symbol. */ + main: string; + label: string; + place?: string; + /** Chance of rain in percent. */ + rain?: number; +} + +/** What goes along with the trip beyond its day; each part optional. */ +interface SnapshotExtras { + place?: string | null; + cover?: string | null; + placeCount?: number; + memberCount?: number; + weather?: WidgetWeather | null; + bookings?: WidgetBooking[]; + todos?: WidgetTodos; + packing?: (WidgetPacking & Partial) | null; + atlas?: WidgetAtlas | null; + collab?: WidgetCollab | null; + flight?: WidgetFlight; +} + +export interface TripDay { + tripTitle: string; + path: string; + dayLabel: string; + stops: WidgetStop[]; + /** The day's id, which the legs of a multi-leg booking name. */ + dayId?: number; + /** 1-based position of the day in the trip, and the trip's day count. */ + index?: number; + total?: number; +} + +/** iOS (WidgetKit) and Android (Glance) read the same snapshot. */ +export function widgetsActive(): boolean { + return isNativeApp() && hasNativeFeature('widgets'); +} + +export function minutesOf(time: string | null | undefined): number | null { + const m = /^(\d{1,2}):(\d{2})/.exec(time ?? ''); + return m ? Number(m[1]) * 60 + Number(m[2]) : null; +} + +/** + * The trip the dashboard's hero features (utils/heroTrip.ts): the running one, + * else the next to start, so the widgets show the trip the app opens on. + * Archived trips are not candidates, as on the dashboard. + */ +export function pickTrip(trips: Trip[], today: string): Trip | null { + const active = trips.filter((t) => !t.is_archived); + return heroTrip(sortTripsByRelevance(active, today), today); +} + +/** + * The trips a widget can be set to in Edit Widget: the ones running or coming + * up, in the dashboard's order (so the hero's trip comes first), at most `limit`, + * each of which gets a snapshot of its own. + */ +export function widgetTripChoices(trips: Trip[], today: string, limit = 6): Trip[] { + const ahead = trips.filter((t) => !t.is_archived && t.start_date && (t.end_date ?? t.start_date) >= today); + return sortTripsByRelevance(ahead, today).slice(0, limit); +} + +/** The symbols of the booking kinds a day's timeline shows next to its stops. */ +export const RESERVATION_SYMBOLS: Record = { + flight: 'airplane', + train: 'tram.fill', + bus: 'bus.fill', + car: 'car.fill', + cruise: 'ferry.fill', + ferry: 'ferry.fill', + hotel: 'bed.double.fill', + restaurant: 'fork.knife', + event: 'ticket.fill', + tour: 'figure.hiking', +}; + +/** Puts each timed booking before the first stop that comes later; untimed stops keep their place. */ +export function mergeByTime(stops: T[], booked: T[]): T[] { + const out = [...stops]; + for (const b of [...booked].sort((x, y) => (x.minutes ?? 0) - (y.minutes ?? 0))) { + const at = out.findIndex((s) => s.minutes != null && s.minutes > (b.minutes ?? 0)); + if (at < 0) out.push(b); + else out.splice(at, 0, b); + } + return out; +} + +/** Today's day of the trip with its stops in plan order, if the trip runs today. */ +export function todayOf( + trip: Trip, + days: Day[], + today: string, + dayLabel: (index: number, total: number) => string, + formatTime: (time: string) => string +): TripDay | null { + const ordered = days.filter((d) => d.trip_id === trip.id).sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0)); + const index = ordered.findIndex((d) => (d.date ?? '').slice(0, 10) === today); + if (index < 0) return null; + const day = ordered[index]; + const stops = [...(day.assignments ?? [])] + .sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0)) + .flatMap((a): WidgetStop[] => + a.place?.name + ? [ + { + name: a.place.name, + time: a.place.place_time ? formatTime(a.place.place_time.slice(0, 5)) : null, + minutes: minutesOf(a.place.place_time), + ...stopLook(a.place.category), + }, + ] + : [] + ); + return { + tripTitle: trip.title, + path: `/trips/${trip.id}`, + dayLabel: dayLabel(index + 1, ordered.length), + stops, + dayId: day.id, + index: index + 1, + total: ordered.length, + }; +} + +/** The day with its timed bookings (a flight, the table tonight) joined to the stops in time order. */ +export function withBookings( + day: TripDay, + reservations: Reservation[], + today: string, + formatTime: (time: string) => string +): TripDay { + const booked = reservations.flatMap((r): WidgetStop[] => { + if (r.status === 'cancelled') return []; + const symbol = RESERVATION_SYMBOLS[r.type] ?? 'bookmark.fill'; + // A booking with stopovers is a stop per leg, as the planner shows it: one + // stop at the first departure counted the day done while legs were ahead. + const legs = r.type === 'flight' ? getFlightLegs(r) : usesStationRoute(r.type) ? getTrainLegs(r) : []; + if (legs.length > 1 && day.dayId != null && legs.every((l) => l.dep_day_id != null)) { + return legs.flatMap((leg): WidgetStop[] => { + if (leg.dep_day_id !== day.dayId || !leg.dep_time) return []; + return [ + { + name: leg.from && leg.to ? `${leg.from} → ${leg.to}` : r.title, + time: formatTime(leg.dep_time), + minutes: minutesOf(leg.dep_time), + // A leg without an arrival day lands on the day it leaves, as the planner reads it. + endMinutes: (leg.arr_day_id ?? leg.dep_day_id) === day.dayId ? minutesOf(leg.arr_time) : 24 * 60, + color: null, + symbol, + }, + ]; + }); + } + const { date, time } = splitReservationDateTime(r.reservation_time); + if (!time || date !== today) return []; + const end = splitReservationDateTime(r.reservation_end_time); + return [ + { + name: r.title, + time: formatTime(time), + minutes: minutesOf(time), + endMinutes: !end.time ? null : end.date && end.date !== today ? 24 * 60 : minutesOf(end.time), + color: null, + symbol, + }, + ]; + }); + return booked.length ? { ...day, stops: mergeByTime(day.stops, booked) } : day; +} + +/** A stop as the widget gets it: the empty fields left out rather than sent as null. */ +function snapshotStop({ time, name, minutes, color, symbol }: WidgetStop): SnapshotStop { + return { + time, + name, + ...(minutes != null ? { minutes } : {}), + ...(color ? { color } : {}), + ...(symbol ? { symbol } : {}), + }; +} + +export function buildSnapshot( + trip: Trip | null, + day: TripDay | null, + labels: WidgetLabels, + extras: SnapshotExtras = {} +): WidgetSnapshot { + const snapshot: WidgetSnapshot = { + trip: trip + ? { + title: trip.title, + start: trip.start_date ?? '', + end: trip.end_date ?? '', + path: `/trips/${trip.id}`, + ...(extras.place ? { place: extras.place } : {}), + ...(extras.cover ? { cover: extras.cover } : {}), + ...(trip.day_count ? { dayCount: trip.day_count } : {}), + ...(extras.placeCount ? { placeCount: extras.placeCount } : {}), + ...(extras.memberCount ? { memberCount: extras.memberCount } : {}), + } + : null, + today: day + ? { + dayLabel: day.dayLabel, + stops: day.stops.map(snapshotStop), + ...(day.index ? { index: day.index, total: day.total } : {}), + } + : null, + labels, + }; + if (extras.weather) snapshot.weather = extras.weather; + if (extras.bookings) snapshot.bookings = extras.bookings; + if (extras.todos) snapshot.todos = extras.todos; + if (extras.packing) snapshot.packing = extras.packing; + if (extras.atlas) snapshot.atlas = extras.atlas; + if (extras.collab) snapshot.collab = extras.collab; + if (extras.flight) snapshot.flight = extras.flight; + return snapshot; +} + +/** What the Live Activity (iOS) and the Live Update (Android) show of the travel day. */ +interface TripDayState { + tripTitle: string; + path: string; + dayLabel: string; + nextName: string; + nextTime?: string; + /** Android: minutes after midnight of the next stop, for the countdown. */ + nextMinutes?: number; + /** Android: the colour of each timed stop, for the progress segments. */ + colors?: (string | null)[]; + done: number; + total: number; + /** iOS: the day's flight while it is near or in the air, drawn as a boarding pass. */ + flight?: LiveFlight; +} + +/** The flight a Live Activity follows: times in epoch seconds, the clocks formatted. */ +interface LiveFlight { + number: string; + from: string; + to: string; + dep: number; + arr: number; + depTime: string; + arrTime: string; + delay?: number; + /** In the air when the app last looked: the countdown then runs to touchdown. */ + airborne?: boolean; +} + +/** From three hours before take-off until an hour after touchdown the activity is about the flight. */ +export function liveFlightOf(flight: WidgetFlight | undefined, nowSeconds: number): LiveFlight | undefined { + if (!flight || flight.landed) return undefined; + const dep = flight.depActual ?? flight.depExpected ?? flight.dep; + const arr = flight.arrExpected ?? flight.arr; + if (nowSeconds < dep - 3 * 3600 || nowSeconds > arr + 3600) return undefined; + return { + number: flight.number, + from: flight.from, + to: flight.to, + dep, + arr, + depTime: flight.depTime, + arrTime: flight.arrTimeExpected ?? flight.arrTime, + ...(flight.delay != null ? { delay: flight.delay } : {}), + ...(flight.airborne ? { airborne: true } : {}), + }; +} + +/** + * The Live Activity's state: the first stop still ahead or still under way (a + * flight in the air until it lands), else the last. + */ +export function tripDayState(day: TripDay, nowMinutes: number, allDone: string): TripDayState { + const timed = day.stops.filter((s) => s.minutes != null); + const nextIndex = day.stops.findIndex( + (s) => s.minutes != null && (s.minutes >= nowMinutes || (s.endMinutes != null && s.endMinutes > nowMinutes)) + ); + const done = nextIndex < 0 ? timed.length : day.stops.slice(0, nextIndex).filter((s) => s.minutes != null).length; + const next = nextIndex >= 0 ? day.stops[nextIndex] : null; + return { + tripTitle: day.tripTitle, + path: day.path, + dayLabel: day.dayLabel, + nextName: next?.name ?? allDone, + nextTime: next?.time ?? undefined, + // Android's Live Update counts down to the next stop and colours a segment per stop. + nextMinutes: next?.minutes ?? undefined, + colors: day.stops.filter((s) => s.minutes != null).map((s) => s.color ?? null), + done, + total: timed.length, + }; +} + +/** How long before the day's first timed stop its Live Activity appears. */ +const LIVE_LEAD_MINUTES = 3 * 60; + +/** + * Whether the travel day's Live Activity belongs on the lock screen now: from + * three hours before the first stop with a time, then until the day is done. A + * day whose first stop is an evening flight does not hold the lock screen from + * the morning on. + */ +export function liveDayDue(day: TripDay, nowMinutes: number): boolean { + const first = day.stops.reduce( + (min, s) => (s.minutes != null && (min === null || s.minutes < min) ? s.minutes : min), + null + ); + return first !== null && nowMinutes >= first - LIVE_LEAD_MINUTES; +} + +/** A trip a widget can be set to in Edit Widget, and its snapshot. */ +export interface TripWidgetSnapshot { + id: number; + title: string; + start: string; + end: string; + snapshot: WidgetSnapshot; +} + +export async function publishWidgets( + snapshot: WidgetSnapshot, + liveDay: TripDayState | null, + trips: TripWidgetSnapshot[] = [] +): Promise { + if (!widgetsActive()) return; + await TrekShell.setWidgetSnapshot({ json: JSON.stringify(snapshot) }).catch(reportNativeFailure); + // An app binary without widgetTrips would take every one of these for the dashboard's snapshot. + if (hasNativeFeature('widgetTrips')) { + for (const trip of trips) { + await TrekShell.setWidgetSnapshot({ json: JSON.stringify(trip.snapshot), key: `trip.${trip.id}` }).catch( + reportNativeFailure + ); + } + const index = trips.map(({ id, title, start, end }) => ({ id, title, start, end })); + await TrekShell.setWidgetSnapshot({ json: JSON.stringify(index), key: 'trips' }).catch(reportNativeFailure); + } + if (!hasNativeFeature('liveActivity')) return; + if (liveDay && liveDay.total > 0) await TrekShell.syncTripDay(liveDay).catch(reportNativeFailure); + else await TrekShell.endTripDay().catch(reportNativeFailure); +} diff --git a/client/src/native/windowFold.test.ts b/client/src/native/windowFold.test.ts new file mode 100644 index 000000000..63ce9c790 --- /dev/null +++ b/client/src/native/windowFold.test.ts @@ -0,0 +1,85 @@ +// FE-NATIVE-FOLD-001 onwards: the fold an Android foldable reports, as two-pane screens use it. +import { act, renderHook, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { NativeWindowLayout } from './trekShell'; +import { _resetWindowFold, foldOf, useWindowFold } from './windowFold'; + +const shell = vi.hoisted(() => ({ + features: [] as string[], + layout: null as unknown, + listener: null as null | ((layout: unknown) => void), +})); + +vi.mock('./capabilities', () => ({ + hasNativeFeature: (feature: string) => shell.features.includes(feature), + useNativeCapabilities: () => ({ + caps: { shellApi: 3, platform: 'android', appVersion: '', build: '', features: shell.features }, + updateRequired: false, + }), +})); +vi.mock('./trekShell', () => ({ + TrekShell: { + getWindowLayout: vi.fn(() => Promise.resolve(shell.layout)), + addListener: vi.fn((_event: string, fn: (layout: unknown) => void) => { + shell.listener = fn; + return Promise.resolve({ remove: () => Promise.resolve() }); + }), + }, +})); + +function layout(over: Partial = {}): NativeWindowLayout { + return { + width: 841, + height: 701, + widthClass: 'expanded', + heightClass: 'medium', + posture: 'halfOpened', + orientation: 'vertical', + separating: true, + hinge: { left: 420, top: 0, right: 421, bottom: 701 }, + ...over, + }; +} + +beforeEach(() => { + _resetWindowFold(); + shell.features = []; + shell.layout = null; + shell.listener = null; +}); + +afterEach(() => _resetWindowFold()); + +describe('foldOf', () => { + it('FE-NATIVE-FOLD-001: a book posture splits the window at its hinge', () => { + expect(foldOf(layout())).toEqual({ start: 420, end: 421 }); + }); + + it('FE-NATIVE-FOLD-002: a seamless flat fold, a horizontal one or none at all splits nothing', () => { + expect(foldOf(layout({ posture: 'flat', separating: false }))).toBeNull(); + expect(foldOf(layout({ orientation: 'horizontal' }))).toBeNull(); + expect(foldOf(layout({ posture: 'none', hinge: undefined }))).toBeNull(); + expect(foldOf(null)).toBeNull(); + // A hinge outside the window is not one to lay panes against. + expect(foldOf(layout({ hinge: { left: 0, top: 0, right: 0, bottom: 701 } }))).toBeNull(); + }); +}); + +describe('useWindowFold', () => { + it('FE-NATIVE-FOLD-003: without the shell feature there is no fold to follow', () => { + const { result } = renderHook(() => useWindowFold()); + expect(result.current).toBeNull(); + expect(shell.listener).toBeNull(); + }); + + it('FE-NATIVE-FOLD-004: follows the layout the Android shell reports, as the device folds and unfolds', async () => { + shell.features = ['windowLayout']; + shell.layout = layout(); + const { result } = renderHook(() => useWindowFold()); + await waitFor(() => expect(result.current).toEqual({ start: 420, end: 421 })); + + act(() => shell.listener?.(layout({ posture: 'flat', separating: false }))); + expect(result.current).toBeNull(); + }); +}); diff --git a/client/src/native/windowFold.ts b/client/src/native/windowFold.ts new file mode 100644 index 000000000..14e1090d3 --- /dev/null +++ b/client/src/native/windowFold.ts @@ -0,0 +1,72 @@ +import { useEffect, useSyncExternalStore } from 'react'; + +import { hasNativeFeature, useNativeCapabilities } from './capabilities'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell, type NativeWindowLayout } from './trekShell'; + +/** A fold down the window, in CSS pixels from its left edge: where it begins and ends. */ +export interface WindowFold { + start: number; + end: number; +} + +/** + * The fold a two-pane screen should respect: a vertical one that separates the + * window into two sides, as a foldable half open like a book has, or a device + * whose two screens meet there. A flat fold that does not separate (a Galaxy + * Fold opened all the way) is one seamless screen, and a horizontal one runs + * across both panes rather than between them. + */ +export function foldOf(layout: NativeWindowLayout | null): WindowFold | null { + if (!layout?.hinge || layout.posture === 'none') return null; + if (layout.orientation !== 'vertical' || !layout.separating) return null; + const { left, right } = layout.hinge; + if (!(left > 0 && right >= left && right < layout.width)) return null; + return { start: left, end: right }; +} + +let layout: NativeWindowLayout | null = null; +let listening = false; +const listeners = new Set<() => void>(); + +function publish(next: NativeWindowLayout): void { + layout = next; + for (const listener of listeners) listener(); +} + +/** Starts following the window layout the Android shell reports (feature windowLayout), once. */ +function follow(): void { + if (listening || !hasNativeFeature('windowLayout')) return; + listening = true; + TrekShell.getWindowLayout().then(publish, reportNativeFailure); + TrekShell.addListener('windowLayout', publish).catch(reportNativeFailure); +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +const current = () => layout; + +/** + * The fold of the window, while the app's shell reports one (Android, feature + * windowLayout); null in a browser, on iOS and on a device without one. Two-pane + * screens end their leading pane at it, so no row runs across the hinge. + */ +export function useWindowFold(): WindowFold | null { + const { caps } = useNativeCapabilities(); + const supported = caps.features.includes('windowLayout'); + useEffect(() => { + if (supported) follow(); + }, [supported]); + const reported = useSyncExternalStore(subscribe, current, current); + return supported ? foldOf(reported) : null; +} + +/** Test helper: forget the layout and the subscription. */ +export function _resetWindowFold(): void { + layout = null; + listening = false; + listeners.clear(); +} diff --git a/client/src/pages/AdminPage.test.tsx b/client/src/pages/AdminPage.test.tsx index dc04fa8ff..76386d99a 100644 --- a/client/src/pages/AdminPage.test.tsx +++ b/client/src/pages/AdminPage.test.tsx @@ -169,7 +169,8 @@ describe('AdminPage', () => { // Other tabs expect(screen.getByRole('button', { name: /personalization/i })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /addons/i })).toBeInTheDocument(); - expect(screen.getByRole('button', { name: /settings/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /^security$/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /^services$/i })).toBeInTheDocument(); }); }); @@ -359,7 +360,7 @@ describe('AdminPage', () => { await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - expect(screen.queryByRole('button', { name: /mcp access/i })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /^mcp$/i })).not.toBeInTheDocument(); }); it('shows MCP Tokens tab button when MCP addon is enabled', async () => { @@ -375,7 +376,7 @@ describe('AdminPage', () => { render(); await waitFor(() => { - expect(screen.getByRole('button', { name: /mcp access/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /^mcp$/i })).toBeInTheDocument(); }); }); }); @@ -395,7 +396,7 @@ describe('AdminPage', () => { await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^security$/i })); const heading = await screen.findByRole('heading', { name: /authentication methods/i }); const card = heading.closest('section'); @@ -512,12 +513,12 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^security$/i })); - const mfaHeading = await screen.findByRole('heading', { name: /require two-factor/i }); - const mfaCard = mfaHeading.closest('section'); - const mfaToggle = within(mfaCard!).getByRole('button'); - fireEvent.click(mfaToggle); + // The 2FA rule is a row of the sign-in card: its label left, its switch right. + const mfaLabel = await screen.findByText('Require 2FA', { selector: 'label' }); + const mfaRow = mfaLabel.closest('.flex-wrap'); + fireEvent.click(within(mfaRow!).getByRole('button')); await waitFor(() => { expect(capturedBody).toEqual(expect.objectContaining({ require_mfa: true })); @@ -551,7 +552,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^services$/i })); await screen.findByText('Transit Provider'); await waitFor(() => expect(transitTrigger()).toHaveTextContent('Transitous')); @@ -577,7 +578,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^services$/i })); await screen.findByText('Transit Provider'); // A real change first, so the counter is proven to move at all. @@ -606,7 +607,7 @@ describe('AdminPage', () => { seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() }); render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^services$/i })); await screen.findByText('Transit Provider'); await waitFor(() => expect(transitTrigger()).toHaveTextContent('Google')); } @@ -634,7 +635,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^security$/i })); const rotateBtn = await screen.findByRole('button', { name: /^rotate$/i }); fireEvent.click(rotateBtn); @@ -805,9 +806,9 @@ describe('AdminPage', () => { await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); fireEvent.click(screen.getByRole('button', { name: /^notifications$/i })); - // AdminNotificationsPanel heading for admin notifications + // The admin matrix sits in the admin alerts card, under its targets await waitFor(() => { - expect(screen.getByRole('heading', { name: /^notifications$/i })).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: /^admin alerts$/i })).toBeInTheDocument(); }); }); }); @@ -826,9 +827,9 @@ describe('AdminPage', () => { seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() }); render(); - await waitFor(() => expect(screen.getByRole('button', { name: /mcp access/i })).toBeInTheDocument()); + await waitFor(() => expect(screen.getByRole('button', { name: /^mcp$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /mcp access/i })); + fireEvent.click(screen.getByRole('button', { name: /^mcp$/i })); expect(screen.getByTestId('mcp-tokens-panel')).toBeInTheDocument(); }); @@ -881,7 +882,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^services$/i })); // Maps is the first 'Enter key...' input (Unsplash is the second). const keyInput = (await screen.findAllByPlaceholderText('Enter key...'))[0]; @@ -912,7 +913,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^services$/i })); // Find the file types input by placeholder const fileTypesInput = await screen.findByPlaceholderText(/jpg,png,pdf/i); @@ -942,7 +943,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^security$/i })); // Wait for OIDC section to appear const oidcHeading = await screen.findByRole('heading', { name: /single sign-on/i }); @@ -1089,7 +1090,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^security$/i })); const rotateBtn = await screen.findByRole('button', { name: /^rotate$/i }); fireEvent.click(rotateBtn); @@ -1143,7 +1144,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^services$/i })); // Wait for the API Keys section to appear const apiKeysHeading = await screen.findByRole('heading', { name: /^api keys$/i }); @@ -1175,7 +1176,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^services$/i })); const apiKeysHeading = await screen.findByRole('heading', { name: /^api keys$/i }); const apiKeysCard = apiKeysHeading.closest('section'); @@ -1209,7 +1210,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^services$/i })); const apiKeysHeading = await screen.findByRole('heading', { name: /^api keys$/i }); const apiKeysCard = apiKeysHeading.closest('section'); @@ -1241,7 +1242,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^services$/i })); // Wait for the API Keys section const apiKeysHeading = await screen.findByRole('heading', { name: /^api keys$/i }); @@ -1334,7 +1335,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^security$/i })); const rotateBtn = await screen.findByRole('button', { name: /^rotate$/i }); fireEvent.click(rotateBtn); @@ -1453,13 +1454,9 @@ describe('AdminPage', () => { // Wait for notifications tab to load await screen.findByPlaceholderText('mail.example.com'); - // Find the webhook panel heading ('Webhook') — exact match to avoid 'Admin Webhook' - const webhookHeading = screen.getByRole('heading', { name: /^webhook$/i }); - // Each channel is a settings card, found as the section around its heading. - const webhookCard = webhookHeading.closest('section'); - // Find the toggle button in webhook card - const webhookToggle = within(webhookCard!).getByRole('button'); - fireEvent.click(webhookToggle); + // Each channel is a row of the channels card, its switch named after it; + // the exact name keeps it apart from the Admin Webhook target. + fireEvent.click(screen.getByRole('button', { name: /^webhook$/i })); await waitFor(() => { expect(appSettingsCalled).toBe(true); @@ -1536,18 +1533,15 @@ describe('AdminPage', () => { await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); fireEvent.click(screen.getByRole('button', { name: /^notifications$/i })); - // Wait for the AdminNotificationsPanel matrix to appear - // The panel heading is t('admin.tabs.notifications') = 'Notifications' - // The channel column header is t('settings.notificationPreferences.email') = 'Email' (CSS uppercases it) - // Find the AdminNotificationsPanel by its h2 heading role='heading' - const matrixHeading = await screen.findByRole('heading', { name: /^notifications$/i }); + // Wait for the AdminNotificationsPanel matrix to appear. It sits bare in the + // admin alerts card (t('admin.notifications.adminAlerts') = 'Admin alerts'), + // whose h2 heading finds it. + const matrixHeading = await screen.findByRole('heading', { name: /^admin alerts$/i }); const matrixCard = matrixHeading.closest('section'); - // The matrix toggle button is inside the card (not a checkbox — it's a button toggle) - const matrixToggle = matrixCard?.querySelector('button'); - if (matrixToggle) { - fireEvent.click(matrixToggle); - } + // The matrix switch is named after its event and channel; the card's first + // buttons belong to the webhook and ntfy targets above the matrix. + fireEvent.click(within(matrixCard!).getByRole('button', { name: /, email$/i })); await waitFor(() => { expect(prefUpdateCalled).toBe(true); @@ -1561,7 +1555,7 @@ describe('AdminPage', () => { render(); await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument()); - fireEvent.click(screen.getByRole('button', { name: /settings/i })); + fireEvent.click(screen.getByRole('button', { name: /^security$/i })); // Wait for the OIDC section — heading is 'Single Sign-On (OIDC)' const oidcHeading = await screen.findByRole('heading', { name: /single sign-on/i }); @@ -1792,7 +1786,7 @@ describe('AdminPage', () => { fireEvent.click(screen.getByRole('button', { name: /^plugins$/i })); expect(screen.getByTestId('plugins-panel')).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: /user defaults/i })); + fireEvent.click(screen.getByRole('button', { name: /^defaults$/i })); expect(screen.getByTestId('default-user-settings')).toBeInTheDocument(); }); }); diff --git a/client/src/pages/AdminPage.tsx b/client/src/pages/AdminPage.tsx index f0e8125c9..a3a195052 100644 --- a/client/src/pages/AdminPage.tsx +++ b/client/src/pages/AdminPage.tsx @@ -16,7 +16,7 @@ import AuditLogPanel from '../components/Admin/AuditLogPanel' import AdminMcpTokensPanel from '../components/Admin/AdminMcpTokensPanel' import AdminPluginsPanel from '../components/Admin/AdminPluginsPanel' import AdminStoragePanel from '../components/Admin/storage/AdminStoragePanel' -import { Users, Map, Briefcase, Shield, FileText, RotateCcw, Save, SlidersHorizontal, UserCog, Puzzle, Blocks, Settings as SettingsIcon, Bell, Database, ScrollText, KeyRound, GitBranch, Bug, HardDrive } from 'lucide-react' +import { Users, Map, Briefcase, Shield, FileText, RotateCcw, Save, SlidersHorizontal, UserCog, Puzzle, Blocks, ShieldCheck, Compass, Bell, Database, ScrollText, KeyRound, GitBranch, Bug, HardDrive } from 'lucide-react' import PageSidebar, { type PageSidebarTab } from '../components/Layout/PageSidebar' import { useAdmin } from './admin/useAdmin' import AdminUpdateBanner from './admin/AdminUpdateBanner' @@ -51,28 +51,32 @@ function AdminPageDesktop(): React.ReactElement { const gUsers = t('admin.group.users') const gConfig = t('admin.group.config') - const gIntegration = t('admin.group.integration') const gMaintenance = t('admin.group.maintenance') - const GROUP_LABELS = { users: gUsers, config: gConfig, integration: gIntegration, maintenance: gMaintenance } + // The integration group was folded into config; a managed tab that still + // names it lands there too instead of under a missing heading. + const GROUP_LABELS = { users: gUsers, config: gConfig, integration: gConfig, maintenance: gMaintenance } const TABS: PageSidebarTab[] = [ { id: 'users', label: t('admin.tabs.users'), icon: Users, group: gUsers }, { id: 'defaults', label: t('admin.tabs.defaults'), icon: UserCog, group: gUsers }, - { id: 'config', label: t('admin.tabs.config'), icon: SlidersHorizontal, group: gConfig }, - { id: 'settings', label: t('admin.tabs.settings'), icon: SettingsIcon, group: gConfig }, + // By what an admin comes for, not by how it is built: who may sign in, what + // the install talks to, which features it offers and what they show. + { id: 'security', label: t('admin.tabs.security'), icon: ShieldCheck, group: gConfig }, + { id: 'services', label: t('admin.tabs.services'), icon: Compass, group: gConfig }, { id: 'addons', label: t('admin.tabs.addons'), icon: Puzzle, group: gConfig }, + { id: 'config', label: t('admin.tabs.config'), icon: SlidersHorizontal, group: gConfig }, + { id: 'notifications', label: t('admin.tabs.notifications'), icon: Bell, group: gConfig }, + ...(mcpEnabled ? [{ id: 'mcp-tokens', label: t('admin.tabs.mcpTokens'), icon: KeyRound, group: gConfig }] : []), // Plugins run third-party code that can send data anywhere; a hosted instance // offers none, so there is nothing to manage here (TREK_PLUGINS_ENABLED is off). ...(managed ? [] : [{ id: 'plugins', label: t('admin.tabs.plugins'), icon: Blocks, group: gConfig }]), // Storage backends and their credentials are hoster-level configuration — // the server refuses the whole surface in managed mode (MANAGED_FORBIDDEN). - ...(managed ? [] : [{ id: 'storage', label: t('admin.tabs.storage'), icon: HardDrive, group: gConfig }]), - { id: 'notifications', label: t('admin.tabs.notifications'), icon: Bell, group: gIntegration }, - ...(mcpEnabled ? [{ id: 'mcp-tokens', label: t('admin.tabs.mcpTokens'), icon: KeyRound, group: gIntegration }] : []), - // Releases and update cadence belong to whoever operates the install. - ...(managed ? [] : [{ id: 'github', label: t('admin.tabs.github'), icon: GitBranch, group: gIntegration }]), + ...(managed ? [] : [{ id: 'storage', label: t('admin.tabs.storage'), icon: HardDrive, group: gMaintenance }]), // Backups run off-volume on a managed install; the tab would offer a // schedule that competes with the real one. ...(managed ? [] : [{ id: 'backup', label: t('admin.tabs.backup'), icon: Database, group: gMaintenance }]), + // Releases and update cadence belong to whoever operates the install. + ...(managed ? [] : [{ id: 'github', label: t('admin.tabs.github'), icon: GitBranch, group: gMaintenance }]), { id: 'audit', label: t('admin.tabs.audit'), icon: ScrollText, group: gMaintenance }, ...(devMode ? [{ id: 'dev-notifications', label: 'Dev: Notifications', icon: Bug, group: gMaintenance }] : []), // Empty in this repository — see client/src/managed. Appended per group @@ -128,7 +132,6 @@ function AdminPageDesktop(): React.ReactElement { )} {c.canDelete && ( - )} - - {c.canDelete && ( - )} } {p.places.length} {String(p.onLabelFilter != null)} {p.onManageLabels && } @@ -192,6 +194,10 @@ function makeHook(overrides: Hook = {}): Hook { heroHeight: 240, listColRef: () => {}, listColRect: { left: 10, width: 400 }, + mapColRef: () => {}, + mapColRect: { left: 500, width: 900 }, + mapLocked: false, + toggleMapLocked: vi.fn(), categories: [], collections: [list], ownedLists: [list, { id: 4, name: 'Other', is_owner: true }], @@ -214,7 +220,7 @@ function makeHook(overrides: Hook = {}): Hook { incomingInvites: [], orderedInvites: [], routeInvite: null, - counts: { all: 1, idea: 0, want: 1, visited: 0 }, + counts: { all: 1, idea: 0, want: 1, visited: 0, revisit: 0 }, view: 'list', statusFilter: 'all', categoryFilter: 'all', @@ -556,11 +562,18 @@ describe('CollectionsPage — child wiring', () => { expect(hook.setView).toHaveBeenCalledWith('map') }) - it('FE-PAGE-COLLPAGE-028: from the map view a marker click drops back into the split', () => { + it('FE-PAGE-COLLPAGE-028: on the full map a marker click shows the place and the map stays', () => { const hook = renderPage({ view: 'map' }) fireEvent.click(screen.getByText('map-select')) expect(hook.setSelectedPlaceId).toHaveBeenCalledWith(10) - expect(hook.setView).toHaveBeenCalledWith('list') + expect(hook.setView).not.toHaveBeenCalled() + }) + + it('FE-PAGE-COLLPAGE-028b: the map carries the trip map\'s padlock, remembered by the page', () => { + const hook = renderPage({ mapLocked: true }) + expect(screen.getByTestId('map-locked')).toHaveTextContent('true') + fireEvent.click(screen.getByText('map-lock')) + expect(hook.toggleMapLocked).toHaveBeenCalledTimes(1) }) it('FE-PAGE-COLLPAGE-029: the map view toggle returns to the list without clearing the selection', () => { @@ -637,9 +650,17 @@ describe('CollectionsPage — detail sheet and modals', () => { expect(screen.getByTestId('detail-anchored')).toHaveTextContent('sheet') }) - it('FE-PAGE-COLLPAGE-034: the full-map view hides the detail sheet', () => { + it('FE-PAGE-COLLPAGE-034: on a narrow full map the detail opens as a sheet over the map', () => { renderPage({ ...withPlace, view: 'map', isWide: false }) - expect(screen.queryByTestId('detail')).toBeNull() + expect(screen.getByTestId('detail-anchored')).toHaveTextContent('sheet') + }) + + it('FE-PAGE-COLLPAGE-034b: on a wide full map the detail docks on the map\'s edge, once the map is measured', () => { + renderPage({ ...withPlace, view: 'map' }) + expect(screen.getByTestId('detail-anchored')).toHaveTextContent('docked') + cleanup() + renderPage({ ...withPlace, view: 'map', mapColRect: null }) + expect(screen.getByTestId('detail-anchored')).toHaveTextContent('sheet') }) it('FE-PAGE-COLLPAGE-035: the add-place modal is bound to the active list', () => { diff --git a/client/src/pages/DashboardPage.desktop.test.tsx b/client/src/pages/DashboardPage.desktop.test.tsx index c0e0fe149..0b2b691f8 100644 --- a/client/src/pages/DashboardPage.desktop.test.tsx +++ b/client/src/pages/DashboardPage.desktop.test.tsx @@ -67,6 +67,8 @@ beforeEach(() => { vi.setSystemTime(new Date('2026-07-05T12:00:00Z')); installMatchMedia(); resetAllStores(); + // The currency tool waits for the saved pair (#3009); the page renders with settings in place. + useSettingsStore.setState({ isLoaded: true }); seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() }); usePluginStore.setState({ plugins: [], loaded: true }); onlyTrips([TRIP]); @@ -203,7 +205,10 @@ describe('DashboardPage (desktop)', () => { // Only the unconfirmed one is marked. const pending = container.querySelectorAll('.upc-pending'); expect(pending).toHaveLength(1); - expect(pending[0]).toHaveTextContent('Pending'); + // A letter on the type icon's corner, the word as its name and tooltip. + expect(pending[0]).toHaveTextContent(/^P$/); + expect(pending[0]).toHaveAttribute('aria-label', 'Pending'); + expect(pending[0].closest('.upc-type')).not.toBeNull(); }); it('FE-PAGE-DESKDASH-009: the currency tool converts and swaps the pair', async () => { diff --git a/client/src/pages/DashboardPage.tsx b/client/src/pages/DashboardPage.tsx index a7dc00e0d..245fed2d2 100644 --- a/client/src/pages/DashboardPage.tsx +++ b/client/src/pages/DashboardPage.tsx @@ -544,7 +544,7 @@ function AtlasStats({ stats }: { stats: TravelStats | null }): React.ReactElemen
    {t('dashboard.atlas.tripsTotal')}
    {statsPending ? : stats.totalTrips ?? 0}
    -
    {statsPending ? : t('dashboard.atlas.placesMapped', { count: stats.totalPlaces ?? 0 })}
    +
    {statsPending ? {t('dashboard.atlas.placesMapped', { count: 0 })} : t('dashboard.atlas.placesMapped', { count: stats.totalPlaces ?? 0 })}
    @@ -572,7 +572,7 @@ function AtlasStats({ stats }: { stats: TravelStats | null }): React.ReactElemen {statsPending ? : distanceText} {' '}{distanceLabel}
    -
    {statsPending ? : t('dashboard.atlas.aroundEquator', { count: equatorTimes })}
    +
    {statsPending ? {t('dashboard.atlas.aroundEquator', { count: '0.00' })} : t('dashboard.atlas.aroundEquator', { count: equatorTimes })}
    @@ -662,7 +662,7 @@ function TripCard({ trip, locale, badges, matchedPlaces, onOpen, onEdit, onCopy, // ── Currency tool (self-contained, mirrors the design's fx widget) ─────────── function CurrencyTool(): React.ReactElement { const { t } = useTranslation() - const { from, to, setFrom, setTo, amount, setAmount, currencies, rate, converted, swap, fetchRates: fetchRate } = useCurrencyConverter() + const { from, to, setFrom, setTo, amount, setAmount, currencies, rate, converted, swap, fetchRates: fetchRate, pairPending, ratePending } = useCurrencyConverter() const ccyOptions = currencies.map(c => ({ value: c, label: c })) return ( @@ -671,7 +671,8 @@ function CurrencyTool(): React.ReactElement {
    {t('dashboard.currency')}
    -
    + {/* Held invisible until the saved pair is known, so the defaults never flash first (#3009). */} +
    {t('dashboard.fx.from')}
    setAmount(e.target.value)} inputMode="decimal" /> @@ -685,7 +686,9 @@ function CurrencyTool(): React.ReactElement {
    - {rate != null ? `1 ${from} = ${rate.toFixed(4)} ${to}` : t('dashboard.fx.unavailable')} + {pairPending || ratePending + ? {`1 ${from} = 0.0000 ${to}`} + : {rate != null ? `1 ${from} = ${rate.toFixed(4)} ${to}` : t('dashboard.fx.unavailable')}}
    ) @@ -758,6 +761,7 @@ function UpcomingTool({ items, locale, onOpen }: { const timeStr = parsed.time ? formatTime(parsed.time, locale, timeFormat) : null const typeClass = RES_TYPE_CLASS[r.type] || 'other' const moment = MOMENT_LABEL[r.type] + const where = moment ? t(moment) : (r.location || r.place_name || r.trip_title) return (
    onOpen(r.trip_id)} role="button" data-no-press tabIndex={0} @@ -766,14 +770,20 @@ function UpcomingTool({ items, locale, onOpen }: {
    {r.title} - {r.status === 'pending' && {t('reservations.pending')}}
    - {timeStr && <> {timeStr} · } - {moment ? t(moment) : (r.location || r.place_name || r.trip_title)} + {timeStr && {timeStr}} + {where && {where}}
    -
    {RES_ICON[r.type] || }
    +
    + {RES_ICON[r.type] || } + {r.status === 'pending' && ( + + {t('reservations.pending').charAt(0).toUpperCase()} + + )} +
    ) })} diff --git a/client/src/pages/JourneyDetailPage.tsx b/client/src/pages/JourneyDetailPage.tsx index 59724c202..7519f22d0 100644 --- a/client/src/pages/JourneyDetailPage.tsx +++ b/client/src/pages/JourneyDetailPage.tsx @@ -72,7 +72,7 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe recordings, canTakeOverRecording, recordingNeedsConnection, dayImport, recordingPrep, feedEdge, scrollFeedTo, loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto, - addPickedProviderPhotos, addEntryProviderPhotos, + addPickedProviderPhotos, addEntryProviderPhotos, writeAboutPlace, } = useJourneyDetail({ journeyId, embedded }) // Inside a trip the trip draws the bar and owns the height; the journal fills // the box it is given and starts at its top. @@ -191,6 +191,7 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe tracks={tracks} layers={mapLayers} entryTitleOf={entryTitleOf} + onWriteAboutPlace={writeAboutPlace} photos={mapPhotos} onPhotoClick={openMapPhotos} dark={document.documentElement.classList.contains('dark')} @@ -721,6 +722,7 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe ref={mapRef} layers={mapLayers} onOpenEntry={handleMarkerClick} + onWriteAboutPlace={writeAboutPlace} entryTitleOf={entryTitleOf} checkins={[]} entries={sidebarMapItems as any} diff --git a/client/src/pages/JourneyPublicPage.tsx b/client/src/pages/JourneyPublicPage.tsx index d3e8cf367..c2c63e998 100644 --- a/client/src/pages/JourneyPublicPage.tsx +++ b/client/src/pages/JourneyPublicPage.tsx @@ -20,6 +20,7 @@ import { ThumbsUp, } from 'lucide-react'; import { DAY_COLORS } from '../components/Journey/dayColors'; +import JourneyDayJump from '../components/Journey/JourneyDayJump'; import JournalBody from '../components/Journey/JournalBody'; import JourneyLayeredMap from '../components/Journey/JourneyLayeredMap'; import MobileEntryView from '../components/Journey/MobileEntryView'; @@ -120,6 +121,7 @@ export default function JourneyPublicPage() { showLangPicker, setShowLangPicker, mapRef, + feedRef, activeEntryId, setActiveEntryId, viewingEntry, @@ -227,7 +229,7 @@ export default function JourneyPublicPage() { const dayIdx = sortedDates.indexOf(date); const dayColor = DAY_COLORS[dayIdx % DAY_COLORS.length]; return ( -
    +
    {/* Day header */}
    {/* Left: feed */} -
    +
    {view === 'timeline' && perms.share_timeline && renderTimeline()} {view === 'gallery' && perms.share_gallery && renderGallery()} + {/* Every day and its entries one click away, as in the journal itself (#2998). */} + {view === 'timeline' && perms.share_timeline && sortedDates.length > 1 && ( +
    +
    + ({ + date, + color: DAY_COLORS[i % DAY_COLORS.length], + entries: (groupedEntries.get(date) ?? []).map(e => ({ id: e.id, title: e.title || e.location_name || t('journey.detail.newEntry') })), + }))} + /> +
    +
    + )}
    {/* Right: sticky map — matches auth page aside proportions */} diff --git a/client/src/pages/LoginPage.tsx b/client/src/pages/LoginPage.tsx index 8b3cbfe67..0c6e12669 100644 --- a/client/src/pages/LoginPage.tsx +++ b/client/src/pages/LoginPage.tsx @@ -4,7 +4,6 @@ import { EyeOff, Fingerprint, Globe, - KeyRound, Loader2, Lock, Mail, @@ -17,7 +16,9 @@ import ToggleSwitch from '../components/Settings/ToggleSwitch'; import { SUPPORTED_LANGUAGES, useTranslation } from '../i18n'; import { IDP_LOGIN_URL, useLogin } from './login/useLogin'; import LoginWorld from './login/LoginWorld'; -import { clearSignedOut } from '../utils/signedOut' +import NativeServerLink from './login/NativeServerLink'; +import MfaCodeStep from './login/MfaCodeStep'; +import { LANGUAGE_CORNER_CLASS } from './login/languageCorner'; import PasswordChecklist from '../components/shared/PasswordChecklist'; /** Fixed so the sky does not reshuffle on every render. */ @@ -85,9 +86,7 @@ export default function LoginPage(): React.ReactElement { configWait, idpSlow, idpName, - handleDemoLogin, - handleSubmit, - handlePasskeyLogin, + handleDemoLogin, handleSubmit, handlePasskeyLogin, handleSsoClick, } = useLogin(); const oidcButtonShown = !!(appConfig?.oidc_configured && appConfig?.oidc_login && !oidcOnly); @@ -230,8 +229,7 @@ export default function LoginPage(): React.ReactElement { return (
    - {/* Language dropdown */} -
    +
    )} - -
    - - ) => - setMfaCode(e.target.value.toUpperCase().slice(0, 24)) - } - placeholder="000000 or XXXX-XXXX" - required - autoFocus - style={inputBase} - onFocus={(e: React.FocusEvent) => (e.target.style.borderColor = '#111827')} - onBlur={(e: React.FocusEvent) => (e.target.style.borderColor = '#e5e7eb')} - /> -
    -

    - {t('login.mfaHint')} -

    - -
    + { + setMfaStep(false); + setMfaToken(''); + setMfaCode(''); + setError(''); + }} + /> )} {/* Username (register only) */} @@ -1140,7 +1085,7 @@ export default function LoginPage(): React.ReactElement {
    )} +
    diff --git a/client/src/pages/NativeHandoffPage.test.tsx b/client/src/pages/NativeHandoffPage.test.tsx new file mode 100644 index 000000000..bfeb70855 --- /dev/null +++ b/client/src/pages/NativeHandoffPage.test.tsx @@ -0,0 +1,68 @@ +// FE-NATIVE-HANDOFF-PAGE-001 to FE-NATIVE-HANDOFF-PAGE-005 +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '../../tests/helpers/render'; +import NativeHandoffPage from './NativeHandoffPage'; +import { useNativeHandoff } from './nativeHandoff/useNativeHandoff'; + +vi.mock('./nativeHandoff/useNativeHandoff', () => ({ useNativeHandoff: vi.fn() })); + +const base = { + valid: true, + passkeyStep: false, + continueWithPasskey: vi.fn(), + otherSignIn: vi.fn(), + ready: true, + userName: 'maria', + status: 'idle' as const, + openApp: vi.fn(), + switchAccount: vi.fn(), +}; + +beforeEach(() => { + vi.mocked(useNativeHandoff).mockReturnValue({ ...base }); +}); + +describe('NativeHandoffPage', () => { + it('FE-NATIVE-HANDOFF-PAGE-001: asks before handing the session to the app', () => { + render(); + expect( + screen.getByText('You are signed in as maria. Open the TREK app to finish signing in there.') + ).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Open the TREK app' })); + expect(base.openApp).toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'Use a different account' })); + expect(base.switchAccount).toHaveBeenCalled(); + }); + + it('FE-NATIVE-HANDOFF-PAGE-002: shows the failure and keeps the button while sending disabled', () => { + vi.mocked(useNativeHandoff).mockReturnValue({ ...base, status: 'failed' }); + const { rerender } = render(); + expect(screen.getByRole('alert')).toHaveTextContent('Signing in did not work. Please try again.'); + + vi.mocked(useNativeHandoff).mockReturnValue({ ...base, status: 'sending' }); + rerender(); + expect(screen.getByRole('button', { name: 'Open the TREK app' })).toBeDisabled(); + }); + + it('FE-NATIVE-HANDOFF-PAGE-003: spins while the session is being checked', () => { + vi.mocked(useNativeHandoff).mockReturnValue({ ...base, ready: false }); + render(); + expect(screen.queryByRole('button')).not.toBeInTheDocument(); + }); + + it('FE-NATIVE-HANDOFF-PAGE-004: says so when the link is broken', () => { + vi.mocked(useNativeHandoff).mockReturnValue({ ...base, valid: false, ready: false }); + render(); + expect(screen.getByText('Signing in did not work. Please try again.')).toBeInTheDocument(); + }); + + it('FE-NATIVE-HANDOFF-PAGE-005: asks for the passkey itself when the app started a passkey sign-in', () => { + vi.mocked(useNativeHandoff).mockReturnValue({ ...base, passkeyStep: true, ready: false }); + render(); + const buttons = screen.getAllByRole('button'); + fireEvent.click(buttons[0]); + expect(base.continueWithPasskey).toHaveBeenCalled(); + fireEvent.click(buttons[1]); + expect(base.otherSignIn).toHaveBeenCalled(); + }); +}); diff --git a/client/src/pages/NativeHandoffPage.tsx b/client/src/pages/NativeHandoffPage.tsx new file mode 100644 index 000000000..fb20cb6f2 --- /dev/null +++ b/client/src/pages/NativeHandoffPage.tsx @@ -0,0 +1,81 @@ +import { Fingerprint, Smartphone } from 'lucide-react'; +import { useTranslation } from '../i18n'; +import { useNativeHandoff } from './nativeHandoff/useNativeHandoff'; + +const PRIMARY = 'w-full rounded-lg bg-accent py-3 font-semibold text-accent-text disabled:opacity-60'; +const SECONDARY = 'py-1 text-caption text-content-muted'; + +export default function NativeHandoffPage() { + const { t } = useTranslation(); + const { valid, passkeyStep, continueWithPasskey, otherSignIn, ready, userName, status, openApp, switchAccount } = + useNativeHandoff(); + + const failed = status === 'failed' && ( +

    + {t(passkeyStep ? 'login.passkey.failed' : 'native.login.failed')} +

    + ); + + return ( +
    +
    + {passkeyStep ? ( + + ) : ( + + )} + {!valid ? ( +

    {t('native.login.failed')}

    + ) : passkeyStep ? ( + <> +

    {t('login.passkey.signIn')}

    + {failed} + + + + ) : !ready ? ( +
    + ) : ( + <> +

    {t('native.handoff.title')}

    +

    {t('native.handoff.hint', { name: userName })}

    + {failed} + + + + )} +
    +
    + ); +} diff --git a/client/src/pages/PluginPage.tsx b/client/src/pages/PluginPage.tsx index fa68c5aaa..bb45e1f6d 100644 --- a/client/src/pages/PluginPage.tsx +++ b/client/src/pages/PluginPage.tsx @@ -28,7 +28,8 @@ export default function PluginPage(): React.ReactElement { return ( -
    + {/* The phone shell sets --plugin-page-h and its own insets (mobile.css). */} +
    diff --git a/client/src/pages/TripPlannerPage.test.tsx b/client/src/pages/TripPlannerPage.test.tsx index ef467f905..abd3cd129 100644 --- a/client/src/pages/TripPlannerPage.test.tsx +++ b/client/src/pages/TripPlannerPage.test.tsx @@ -301,7 +301,7 @@ describe('TripPlannerPage', () => { }); describe('FE-PAGE-PLANNER-002: Loading state shown while loadTrip in progress', () => { - it('shows loading animation when isLoading is true', () => { + it('shows loading animation when isLoading is true', async () => { seedStore(useTripStore, { trip: null, isLoading: true, @@ -315,8 +315,9 @@ describe('TripPlannerPage', () => { renderPlannerPage(99); - // Loading state: shows the trip-open loading splash - expect(screen.getByTestId('trip-loading-splash')).toBeInTheDocument(); + // A quick open shows nothing but the page's ground; a slow one gets the splash. + expect(screen.queryByTestId('trip-loading-splash')).not.toBeInTheDocument(); + expect(await screen.findByTestId('trip-loading-splash', {}, { timeout: 2000 })).toBeInTheDocument(); }); }); diff --git a/client/src/pages/TripPlannerPage.tsx b/client/src/pages/TripPlannerPage.tsx index 5190042d6..ffb838de3 100644 --- a/client/src/pages/TripPlannerPage.tsx +++ b/client/src/pages/TripPlannerPage.tsx @@ -63,7 +63,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null { // selection, CRUD handlers with undo, map filters, splash) lives in the hook. const pageState = useTripPlannerPage() const { - tripId, navigate, toast, t, language, placesPhotosEnabled, + tripId, navigate, t, language, placesPhotosEnabled, trip, days, places, assignments, packingItems, todoItems, categories, reservations, budgetItems, files, selectedDayId, isLoading, tripActions, can, canUploadFiles, pushUndo, undo, canUndo, lastActionLabel, handleUndo, @@ -76,7 +76,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null { TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange, leftWidth, rightWidth, leftHidden, rightHidden, toggleLeft, toggleRight, - startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizeMin, resizeMax, + startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing, resizeMin, resizeMaxLeft, resizeMaxRight, selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment, showDayDetail, setShowDayDetail, dayDetailCollapsed, setDayDetailCollapsed, stayPickerDayId, setStayPickerDayId, @@ -123,7 +123,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null { selectedPlace, dayOrderMap, dayPlaces, toursEnabled, toursMode, setToursMode, tours, toursLoading, tourDataReady, tourPlaceIds, invalidateTourPlaceIds, selectedTour, - mapTileUrl, fontStyle, splashDone, assistantMap, + mapTileUrl, fontStyle, slowOpen, saveTrip, assistantMap, } = pageState.planner const { poi, @@ -183,13 +183,13 @@ function TripPlannerPageDesktop(): React.ReactElement | null { // the day-header tram button and the modal's mode switch — is off without one. const tripHasDates = Boolean(trip?.start_date && trip?.end_date) - if (isLoading || !splashDone) { + if (isLoading) { return ( -
    - + {slowOpen && }
    ) } @@ -280,7 +280,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null { dawarichEnabled={dawarichEnabled} dawarichTrail={dawarichTrail} dawarichHiddenDates={dawarichHiddenDates} dawarichTrailShown={dawarichTrailShown} toggleDawarichTrail={toggleDawarichTrail} mobileSidebarOpen={mobileSidebarOpen} showPlaceForm={showPlaceForm} showMembersModal={showMembersModal} showReservationModal={showReservationModal} poi={poi} tourMap={tourMap} leftPanelPx={leftPanelPx} rightPanelPx={rightPanelPx} mapInsetLeft={mapInsetLeft} mapInsetRight={mapInsetRight} - glMap={glMap} setGlMap={setGlMap} poiPillEnabled={poiPillEnabled} mapPois={mapPois} distanceUnit={distanceUnit} + glMap={glMap} setGlMap={setGlMap} poiPillEnabled={poiPillEnabled} mapPois={mapPois} distanceUnit={distanceUnit} inspectorHeight={pageState.inspectorCard.height} />
    @@ -294,7 +294,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null { boxShadow: leftHidden ? 'none' : 'var(--sidebar-shadow)', borderRadius: 16, overflow: 'hidden', display: 'flex', flexDirection: 'column', - transition: 'width 0.25s ease', + transition: resizing ? 'none' : 'width 0.25s ease', opacity: leftHidden ? 0 : 1, }}> {enabledAddons.roadtrip && ( @@ -402,7 +402,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null { /> )} {!leftHidden && ( - + )}
    @@ -418,11 +418,11 @@ function TripPlannerPageDesktop(): React.ReactElement | null { boxShadow: rightHidden ? 'none' : 'var(--sidebar-shadow)', borderRadius: 16, overflow: 'hidden', display: 'flex', flexDirection: 'column', - transition: 'width 0.25s ease', + transition: resizing ? 'none' : 'width 0.25s ease', opacity: rightHidden ? 0 : 1, }}> {!rightHidden && ( - + )}
    {roadtripActive ? ( @@ -547,7 +547,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null { onDelete={() => handleDeletePlace(selectedPlace.id)} leftWidth={isMobile ? 0 : leftPanelPx} rightWidth={isMobile ? 0 : rightPanelPx} - clearMapPill + clearMapPill collapsible cardRef={pageState.inspectorCard.measure} /> )} @@ -633,9 +633,9 @@ function TripPlannerPageDesktop(): React.ReactElement | null { background: 'var(--sidebar-bg)', backdropFilter: 'blur(24px) saturate(180%)', WebkitBackdropFilter: 'blur(24px) saturate(180%)', boxShadow: leftHidden ? 'none' : 'var(--sidebar-shadow)', borderRadius: 16, overflow: 'hidden', display: 'flex', flexDirection: 'column', - transition: 'width 0.25s ease', opacity: leftHidden ? 0 : 1, + transition: resizing ? 'none' : 'width 0.25s ease', opacity: leftHidden ? 0 : 1, }}> - {!leftHidden && } + {!leftHidden && }
    @@ -654,7 +654,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null { style={{ width: rightHidden ? 0 : rightWidth, opacity: rightHidden ? 0 : 1, - transition: 'width 0.25s ease, opacity 0.25s ease', + transition: resizing ? 'opacity 0.25s ease' : 'width 0.25s ease, opacity 0.25s ease', background: 'var(--sidebar-bg)', backdropFilter: 'blur(24px) saturate(180%)', WebkitBackdropFilter: 'blur(24px) saturate(180%)', @@ -662,7 +662,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null { }} > {!rightHidden && ( - + )} {!rightHidden && ( @@ -826,11 +826,11 @@ function TripPlannerPageDesktop(): React.ReactElement | null { setShowTripForm(false)} - onSave={async (data) => { await tripActions.updateTrip(tripId, data); loadAccommodations(); toast.success(t('trip.toast.tripUpdated')) }} + onSave={saveTrip} trip={trip} onCoverUpdate={applyTripCoverUpdate} /> - setShowMembersModal(false)} tripId={tripId} tripTitle={trip?.title} onMembersChanged={refreshMembers} /> + setShowMembersModal(false)} tripId={tripId} tripTitle={trip?.title} onMembersChanged={refreshMembers} editTrip={trip && can('trip_edit', trip) ? { trip, onSave: saveTrip, onCoverUpdate: applyTripCoverUpdate } : undefined} /> { if (importReviewActive) { advanceImportReview() } else { setShowReservationModal(false); setEditingReservation(null); setBookingForAssignmentId(null) } }} onSave={async (data, steps) => { const r = await handleSaveReservation(data, steps); if (importReviewActive && r) advanceImportReview(); return r }} reservation={editingReservation} prefill={reservationPrefill} days={days} places={places} assignments={assignments} selectedDayId={selectedDayId} files={files} onFileUpload={canUploadFiles ? (fd) => tripActions.addFile(tripId, fd) : undefined} onFileDelete={(id) => tripActions.deleteFile(tripId, id)} accommodations={tripAccommodations} defaultAssignmentId={bookingForAssignmentId} onOpenExpense={openBookingExpense} tripMembers={tripMembers} /> {showTransportModal && ( diff --git a/client/src/pages/TripPlannerPage.wiring.fixture.ts b/client/src/pages/TripPlannerPage.wiring.fixture.ts index ca43e059b..798e66049 100644 --- a/client/src/pages/TripPlannerPage.wiring.fixture.ts +++ b/client/src/pages/TripPlannerPage.wiring.fixture.ts @@ -174,8 +174,10 @@ function layoutState(): HookState { startResizeRight: vi.fn(), nudgeLeft: vi.fn(), nudgeRight: vi.fn(), + resizing: false, resizeMin: 200, - resizeMax: 520, + resizeMaxLeft: 520, + resizeMaxRight: 520, selectedPlaceId: null, selectedAssignmentId: null, setSelectedPlaceId: vi.fn(), @@ -327,6 +329,7 @@ function mapState(): HookState { selectedTour: null, mapTileUrl: 'https://tiles/{z}/{x}/{y}.png', fontStyle: { fontFamily: 'var(--font-system)' }, - splashDone: true, + slowOpen: false, + saveTrip: vi.fn(), }; } diff --git a/client/src/pages/TripPlannerPage.wiring.test.tsx b/client/src/pages/TripPlannerPage.wiring.test.tsx index a07238bca..ad37e2afd 100644 --- a/client/src/pages/TripPlannerPage.wiring.test.tsx +++ b/client/src/pages/TripPlannerPage.wiring.test.tsx @@ -1,4 +1,4 @@ -// FE-PAGE-TPW-001 to FE-PAGE-TPW-074 +// FE-PAGE-TPW-001 to FE-PAGE-TPW-075 // // The planner page is a wiring container: everything stateful lives in // useTripPlanner (covered in src/pages/tripPlanner/useTripPlanner.test.tsx). @@ -260,7 +260,7 @@ describe('TripPlannerPage — shell', () => { { leftHidden: true, rightHidden: false, visibleSide: 'right', leftInset: 0, rightInset: 300 }, ])('UI-R2: the 768-1023px panel state shows only its selected rail ($visibleSide)', ({ leftHidden, rightHidden, visibleSide, leftInset, rightInset }) => { const { container } = renderToursPage({ narrowPanels: true, - leftHidden, rightHidden, leftWidth: 300, rightWidth: 300, resizeMax: 300 }) + leftHidden, rightHidden, leftWidth: 300, rightWidth: 300, resizeMaxLeft: 300, resizeMaxRight: 300 }) const handles = container.querySelectorAll('div[role="separator"]') expect(handles).toHaveLength(1) expect(handles[0]).toHaveAttribute('data-resize', visibleSide) @@ -638,21 +638,25 @@ describe('TripPlannerPage — shell', () => { expect(plannerActions.viewGpxTour).toHaveBeenCalledOnce() }) - it('FE-PAGE-TPW-002: the splash holds the page until the trip finished loading', () => { - renderPage({ isLoading: true, splashDone: false }) + it('FE-PAGE-TPW-002: a slow open shows the splash until the trip finished loading', () => { + renderPage({ isLoading: true, slowOpen: true }) expect(screen.getByRole('status')).toHaveTextContent('Kyoto') expect(screen.queryByTestId('map-view')).not.toBeInTheDocument() }) - it('FE-PAGE-TPW-003: the splash also covers the gap between load and splashDone', () => { - renderPage({ isLoading: false, splashDone: false }) + it('FE-PAGE-TPW-003: a quick open shows no splash, only the empty page while it loads, and the trip at once', () => { + const view = renderPage({ isLoading: true, slowOpen: false }) + expect(screen.queryByTestId('splash')).not.toBeInTheDocument() + expect(screen.queryByTestId('map-view')).not.toBeInTheDocument() + view.unmount() - expect(screen.getByTestId('splash')).toBeInTheDocument() + renderPage({ isLoading: false, slowOpen: false }) + expect(screen.queryByTestId('splash')).not.toBeInTheDocument() }) it('FE-PAGE-TPW-004: a trip that never arrived renders nothing at all', () => { - const { container } = renderPage({ trip: null, isLoading: false, splashDone: true }) + const { container } = renderPage({ trip: null, isLoading: false, slowOpen: false }) expect(container).toBeEmptyDOMElement() }) @@ -1454,6 +1458,7 @@ describe('TripPlannerPage — lists tab', () => { renderPage({ activeTab: 'listen', packingItems: [buildPackingItem({ checked: 0 })] }) await screen.findByTestId('packing-list-panel') + openListsMenu() fireEvent.click(screen.getByRole('button', { name: /Save as template/i })) expect(props('packingPanel').saveTemplateSignal).toBe(1) }) @@ -1462,6 +1467,7 @@ describe('TripPlannerPage — lists tab', () => { renderPage({ activeTab: 'listen', packingItems: [buildPackingItem({ checked: 0 })] }) await screen.findByTestId('packing-list-panel') + openListsMenu() expect(screen.queryByRole('button', { name: /Save as template/i })).not.toBeInTheDocument() fireEvent.click(screen.getByRole('button', { name: /Import/i })) expect(props('packingPanel').openImportSignal).toBe(1) @@ -1476,7 +1482,7 @@ describe('TripPlannerPage — lists tab', () => { expect(props('applyTemplate').visibility).toBe('personal') }) - it('FE-PAGE-TPW-044b: export and import sit in the header as icons, export following the open view (#875, #1420)', async () => { + it('FE-PAGE-TPW-044b: export and import sit in the Lists menu, export following the open view (#875, #1420)', async () => { renderPage({ activeTab: 'listen', packingItems: [buildPackingItem({ checked: 0 })] }) await screen.findByTestId('packing-list-panel') @@ -1486,12 +1492,18 @@ describe('TripPlannerPage — lists tab', () => { act(() => { props('packingPanel').onViewChange('personal') }) expect(props('exportMenu').view).toBe('personal') - const importButton = screen.getByRole('button', { name: 'Import' }) - expect(importButton).toHaveAttribute('title', 'Import') - expect(importButton).toHaveTextContent('') + expect(props('exportMenu').variant).toBe('menu') + openListsMenu() + expect(screen.getByRole('button', { name: 'Import' })).toBeInTheDocument() }) }) +/** The Lists bar's "..." beside Add list, which holds templates, import and export. */ +function openListsMenu() { + const trigger = screen.getAllByRole('button', { name: 'Show more' }).find(b => b.getAttribute('aria-haspopup') === 'menu') + if (trigger) fireEvent.click(trigger) +} + describe('TripPlannerPage — modals', () => { it('FE-PAGE-TPW-045: closing the place form clears every editing slot', () => { renderPage() @@ -1518,13 +1530,10 @@ describe('TripPlannerPage — modals', () => { expect((props('placeForm').dayAssignments as unknown as unknown[]).length).toBe(1) }) - it('FE-PAGE-TPW-047: saving the trip form reloads the accommodations and confirms', async () => { + it('FE-PAGE-TPW-047: the trip form saves through the hook, the same save the trip settings use', () => { renderPage() - await act(async () => { await props('tripForm').onSave({ title: 'Kyoto 2' }) }) - const tripActions = hookState.tripActions as Record> - expect(tripActions.updateTrip).toHaveBeenCalledWith(42, { title: 'Kyoto 2' }) - expect(hookState.loadAccommodations).toHaveBeenCalled() + expect(props('tripForm').onSave).toBe(hookState.saveTrip) act(() => { props('tripForm').onClose() }) expect(hookState.setShowTripForm).toHaveBeenCalledWith(false) @@ -1552,6 +1561,14 @@ describe('TripPlannerPage — modals', () => { expect(hookState.setShowMembersModal).toHaveBeenCalledWith(false) }) + it('FE-PAGE-TPW-075: the trip settings hold the trip form only for someone who may edit the trip (#2811)', () => { + renderPage() + expect(props('membersModal').editTrip).toBeTruthy() + + renderPage({ can: vi.fn((action: string) => action !== 'trip_edit') }) + expect(props('membersModal').editTrip).toBeUndefined() + }) + it('FE-PAGE-TPW-050: closing the booking modal outside a review resets the editor', async () => { renderPage() diff --git a/client/src/pages/admin/AdminNotificationDefaultsPanel.tsx b/client/src/pages/admin/AdminNotificationDefaultsPanel.tsx index 274318106..55599dff3 100644 --- a/client/src/pages/admin/AdminNotificationDefaultsPanel.tsx +++ b/client/src/pages/admin/AdminNotificationDefaultsPanel.tsx @@ -1,4 +1,4 @@ -import { Check, Lock, Minus, UsersRound } from 'lucide-react' +import { UsersRound } from 'lucide-react' import type { NotificationDefault } from '@trek/shared' import { useTranslation } from '../../i18n' import { Tooltip } from '../../components/shared/Tooltip' @@ -6,19 +6,13 @@ import { SettingsCard } from '../../components/Settings/settingsKit' import { fs } from '../../components/shared/DialogShell' import { EVENT_LABEL_KEYS, channelLabel } from '../../components/Settings/notificationLabels' import { useNotificationDefaults } from './useNotificationDefaults' +import { DEFAULT_ICON as ICON, DEFAULT_LABEL_KEYS as LABEL_KEYS, NEXT_DEFAULT as NEXT, defaultChannels, defaultOf } from './notificationDefaultsModel' -const NEXT: Record = { on: 'off', off: 'blocked', blocked: 'on' } -const ICON = { on: Check, off: Minus, blocked: Lock } as const const TONE: Record = { on: 'bg-accent text-accent-text border-transparent', off: 'bg-surface-card text-content-muted border-edge', blocked: 'bg-danger-soft text-danger border-transparent', } -const LABEL_KEYS: Record = { - on: 'admin.notificationDefaults.on', - off: 'admin.notificationDefaults.off', - blocked: 'admin.notificationDefaults.blocked', -} /** * What every user's notification cells start as (#1536). One cell per event and @@ -30,7 +24,7 @@ export default function AdminNotificationDefaultsPanel() { const { matrix, saving, cycle } = useNotificationDefaults() if (!matrix) return null - const channels = matrix.channels.filter(ch => matrix.event_types.some(evt => matrix.implemented_combos[evt]?.includes(ch.id))) + const channels = defaultChannels(matrix) const columns = `minmax(0, 1fr) ${channels.map(() => '76px').join(' ')}` return ( @@ -63,7 +57,7 @@ export default function AdminNotificationDefaultsPanel() { {t(EVENT_LABEL_KEYS[eventType]) || eventType} {channels.map(ch => { if (!implemented.includes(ch.id)) return — - const state = matrix.defaults[eventType]?.[ch.id] ?? 'on' + const state = defaultOf(matrix, eventType, ch.id) const Icon = ICON[state] const label = `${t(EVENT_LABEL_KEYS[eventType]) || eventType}, ${channelLabel(ch, t)}: ${t(LABEL_KEYS[state])}` return ( diff --git a/client/src/pages/admin/AdminNotificationsPanel.tsx b/client/src/pages/admin/AdminNotificationsPanel.tsx index d29cd0208..fe6c8588f 100644 --- a/client/src/pages/admin/AdminNotificationsPanel.tsx +++ b/client/src/pages/admin/AdminNotificationsPanel.tsx @@ -11,10 +11,15 @@ const EYEBROW = 'text-center font-geist font-bold uppercase tracking-[.08em] tex // Per-event × per-channel admin notification preference matrix. // Loads its own data and auto-saves each toggle. -export default function AdminNotificationsPanel({ t, toast }: { t: (k: string) => string; toast: ReturnType }) { +export default function AdminNotificationsPanel({ t, toast, bare = false }: { + t: (k: string) => string + toast: ReturnType + /** Inside the admin notifications card, which carries the title: the matrix alone. */ + bare?: boolean +}) { const { matrix, saving, visibleChannels, toggle } = useAdminNotificationMatrix(t, toast) - const card = (children: React.ReactNode) => ( + const card = (children: React.ReactNode) => bare ? <>{children} : ( {children} diff --git a/client/src/pages/admin/AdminNotificationsTab.test.tsx b/client/src/pages/admin/AdminNotificationsTab.test.tsx index 474207edf..8fdabd433 100644 --- a/client/src/pages/admin/AdminNotificationsTab.test.tsx +++ b/client/src/pages/admin/AdminNotificationsTab.test.tsx @@ -42,6 +42,28 @@ function card(heading: string | RegExp): HTMLElement { return screen.getByRole('heading', { name: heading }).closest('section')!; } +/** The labels of the channels card's switch rows, top to bottom: its first block of rows, not the SMTP section under it. */ +function channelRows(): string[] { + const rows = card('Channels').querySelector('.divide-y'); + if (!rows) throw new Error('the channels card has no rows'); + return Array.from(rows.querySelectorAll('label'), l => l.textContent ?? ''); +} + +/** A channel's row in the channels card (label and hint left, switch right). */ +function channelRow(label: string): HTMLElement { + const row = within(card('Channels')) + .getAllByText(label) + .find(node => node.tagName === 'LABEL') + ?.closest('.flex-wrap'); + if (!row) throw new Error(`no channel row for ${label}`); + return row; +} + +/** A channel's switch: each row's switch carries the channel's name. */ +function channelSwitch(label: string): HTMLElement { + return within(channelRow(label)).getByRole('button', { name: label }); +} + const EMAIL_ON: SmtpValues = { notification_channels: 'email', smtp_host: 'mail.example.com' }; /** @@ -68,11 +90,9 @@ describe('AdminNotificationsTab', () => { it('FE-ADMNOT-001: renders every channel panel plus the preference matrix', () => { renderTab(); + // Every channel is a row of the channels card; the SMTP relay is a section of it. + expect(channelRows()).toEqual(['Email (SMTP)', 'Webhook', 'Ntfy', 'Web Push', 'In-App', 'Trip Reminders']); expect(screen.getByRole('heading', { name: 'Email (SMTP)' })).toBeInTheDocument(); - expect(screen.getByRole('heading', { name: /^webhook$/i })).toBeInTheDocument(); - expect(screen.getByRole('heading', { name: 'Ntfy' })).toBeInTheDocument(); - expect(screen.getByRole('heading', { name: 'In-App' })).toBeInTheDocument(); - expect(screen.getByRole('heading', { name: 'Trip Reminders' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Admin Webhook' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Admin Ntfy' })).toBeInTheDocument(); expect(screen.getByTestId('admin-notifications-panel')).toBeInTheDocument(); @@ -112,7 +132,7 @@ describe('AdminNotificationsTab', () => { ); const admin = renderTab({ smtpValues: { notification_channels: 'webhook' } }); - fireEvent.click(within(card('Email (SMTP)')).getAllByRole('button')[0]); + fireEvent.click(channelSwitch('Email (SMTP)')); await waitFor(() => expect(body).toEqual({ notification_channels: 'email,webhook' })); expect(replaySmtp(admin.setSmtpValues, 0).notification_channels).toBe('email,webhook'); @@ -128,7 +148,7 @@ describe('AdminNotificationsTab', () => { ); renderTab({ smtpValues: { notification_channels: 'email' } }); - fireEvent.click(within(card('Email (SMTP)')).getAllByRole('button')[0]); + fireEvent.click(channelSwitch('Email (SMTP)')); await waitFor(() => expect(body).toEqual({ notification_channels: 'none' })); }); @@ -143,7 +163,7 @@ describe('AdminNotificationsTab', () => { ); renderTab({ smtpValues: { notification_channels: 'email, plugin-gotify' } }); - fireEvent.click(within(card('Ntfy')).getAllByRole('button')[0]); + fireEvent.click(channelSwitch('Ntfy')); await waitFor(() => expect(body).toEqual({ notification_channels: 'email,ntfy,plugin-gotify' })); }); @@ -152,7 +172,7 @@ describe('AdminNotificationsTab', () => { server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 }))); const admin = renderTab({ smtpValues: { notification_channels: 'email' } }); - fireEvent.click(within(card(/^webhook$/i)).getAllByRole('button')[0]); + fireEvent.click(channelSwitch('Webhook')); await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error')); expect(replaySmtp(admin.setSmtpValues, 0).notification_channels).toBe('email,webhook'); @@ -269,7 +289,7 @@ describe('AdminNotificationsTab', () => { ); const admin = renderTab({ smtpValues: { notify_trip_reminder: 'false' } }); - fireEvent.click(within(card('Trip Reminders')).getByRole('button')); + fireEvent.click(channelSwitch('Trip Reminders')); await waitFor(() => expect(body).toEqual({ notify_trip_reminder: 'true' })); expect(admin.toast.success).toHaveBeenCalledWith('Trip reminders enabled'); @@ -280,7 +300,7 @@ describe('AdminNotificationsTab', () => { server.use(http.get('/api/auth/app-config', () => HttpResponse.json({}))); const admin = renderTab({ smtpValues: {} }); - fireEvent.click(within(card('Trip Reminders')).getByRole('button')); + fireEvent.click(channelSwitch('Trip Reminders')); await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('Trip reminders disabled')); expect(replaySmtp(admin.setSmtpValues, 0).notify_trip_reminder).toBe('false'); @@ -290,7 +310,7 @@ describe('AdminNotificationsTab', () => { server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 }))); const admin = renderTab({ smtpValues: {} }); - fireEvent.click(within(card('Trip Reminders')).getByRole('button')); + fireEvent.click(channelSwitch('Trip Reminders')); await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error')); expect(replaySmtp(admin.setSmtpValues, 1).notify_trip_reminder).toBe('true'); @@ -565,21 +585,20 @@ describe('AdminNotificationsTab', () => { // single stack there instead of leaving half a grid row empty. renderTab({ managed: true }); - expect(screen.getByRole('heading', { name: /^webhook$/i })).toBeInTheDocument(); - expect(screen.getByRole('heading', { name: 'Trip Reminders' })).toBeInTheDocument(); + expect(channelRows()).toEqual(['Webhook', 'Ntfy', 'Web Push', 'In-App', 'Trip Reminders']); expect(screen.queryByRole('heading', { name: 'Email (SMTP)' })).not.toBeInTheDocument(); expect(screen.queryByRole('heading', { name: 'Admin Webhook' })).not.toBeInTheDocument(); expect(screen.queryByRole('heading', { name: 'Admin Ntfy' })).not.toBeInTheDocument(); }); - it('FE-ADMNOT-044: Web Push has its own card after Ntfy, before In-App', () => { + it('FE-ADMNOT-044: Web Push has its own row after Ntfy, before In-App', () => { renderTab({ smtpValues: { notification_channels: 'email' } }); - const headings = screen.getAllByRole('heading').map(h => h.textContent); - expect(headings.indexOf('Web Push')).toBe(headings.indexOf('Ntfy') + 1); - expect(headings.indexOf('In-App')).toBe(headings.indexOf('Web Push') + 1); - expect(within(card('Web Push')).getByText(/receive notifications on their phones/)).toBeInTheDocument(); - expect(within(card('Web Push')).getByRole('button', { name: 'Web Push' })).toHaveAttribute('aria-pressed', 'false'); + const rows = channelRows(); + expect(rows.indexOf('Web Push')).toBe(rows.indexOf('Ntfy') + 1); + expect(rows.indexOf('In-App')).toBe(rows.indexOf('Web Push') + 1); + expect(within(channelRow('Web Push')).getByText(/receive notifications on their phones/)).toBeInTheDocument(); + expect(channelSwitch('Web Push')).toHaveAttribute('aria-pressed', 'false'); }); it('FE-ADMNOT-045: switching Web Push on adds push to the list and keeps the rest', async () => { @@ -592,7 +611,7 @@ describe('AdminNotificationsTab', () => { ); const admin = renderTab({ smtpValues: { notification_channels: 'email,plugin-gotify' } }); - fireEvent.click(within(card('Web Push')).getByRole('button', { name: 'Web Push' })); + fireEvent.click(channelSwitch('Web Push')); await waitFor(() => expect(body).toEqual({ notification_channels: 'email,push,plugin-gotify' })); expect(replaySmtp(admin.setSmtpValues, 0).notification_channels).toBe('email,push,plugin-gotify'); @@ -608,7 +627,7 @@ describe('AdminNotificationsTab', () => { ); renderTab({ smtpValues: { notification_channels: 'email,push' } }); - const toggle = within(card('Web Push')).getByRole('button', { name: 'Web Push' }); + const toggle = channelSwitch('Web Push'); expect(toggle).toHaveAttribute('aria-pressed', 'true'); fireEvent.click(toggle); diff --git a/client/src/pages/admin/AdminNotificationsTab.tsx b/client/src/pages/admin/AdminNotificationsTab.tsx index 08bdce19e..1d114b5b7 100644 --- a/client/src/pages/admin/AdminNotificationsTab.tsx +++ b/client/src/pages/admin/AdminNotificationsTab.tsx @@ -1,6 +1,5 @@ import React, { useId } from 'react' -import { Bell, BellRing, CalendarClock, Mail, Save, Send, Smartphone, Webhook } from 'lucide-react' -import type { LucideIcon } from 'lucide-react' +import { Bell, BellRing, Mail, Save, Send, Webhook } from 'lucide-react' import type { TranslationFn } from '../../types' import type { useAdmin } from './useAdmin' import AdminNotificationsPanel from './AdminNotificationsPanel' @@ -9,7 +8,7 @@ import { SWITCH_ONLY_CHANNELS, useNotificationChannels } from '../../components/ import { MASK, useAdminNotificationSettings } from '../../components/Admin/useAdminNotificationSettings' import ToggleSwitch from '../../components/Settings/ToggleSwitch' import { - SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsCard, + SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsCard, SettingsColumns, } from '../../components/Settings/settingsKit' import { EditorField, GRID_2, INPUT } from '../../components/shared/dialogParts' import { fs } from '../../components/shared/DialogShell' @@ -19,9 +18,6 @@ interface AdminNotificationsTabProps { t: TranslationFn } -/** The glyph on each switch-only channel's card; anything else is the push channel. */ -const CHANNEL_ICONS: Record = { webhook: Webhook, ntfy: BellRing } - /** The save and test buttons under a card's fields, on a hairline of their own. */ function CardActions({ children }: { children: React.ReactNode }): React.ReactElement { return
    {children}
    @@ -78,115 +74,102 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa ) - const tripRemindersCard = ( - - } - /> - ) - return (<> - {/* Two columns from xl up, the same shape as the Settings tab. Most of these - cards are a title with a switch on the far right, so on a wide screen the - middle stayed empty while the page still scrolled past the three tall ones. - Two explicit columns rather than a grid over the flat list: a plain grid - pairs cards row by row and leaves a hole under the shorter one, and the SMTP - card is taller than all the toggle rows together. Grouped by audience, not by - height — the channels a user can receive on the left, everything the operator - sends or receives themselves on the right. The channel switches stay - together because they all write the same notification_channels list. - On a managed install the two admin-target cards are gone and the right column - is the matrix alone — still a column, so the grid keeps working. Each card - brings its own bottom margin, so the columns only need the gap between them. */} -
    -
    - {/* The relay is the operator's: their host, their credential, their sending - reputation. An instance that could point it elsewhere would send under a - domain it does not own. */} - {!managed && ( - channels.toggle('email')} />} - > - {/* Greyed and out of reach while the channel is off, never hidden. */} -
    - {smtpLoaded && (<> -
    - {smtpField(SMTP_FIELDS[0])} - {smtpField(SMTP_FIELDS[1])} -
    -
    - {smtpField(SMTP_FIELDS[2])} - {smtpField(SMTP_FIELDS[3])} -
    - {smtpField(SMTP_FIELDS[4])} - )} - - { - const newVal = smtpValues.smtp_skip_tls_verify === 'true' ? 'false' : 'true' - setSmtpValues(prev => ({ ...prev, smtp_skip_tls_verify: newVal })) - }} - /> - } + {/* Every channel users can receive on is one switch in one card, the SMTP + relay's fields a section under them; the operator's own targets and the + admin-only matrix on the right. */} + + + {/* The relay is the operator's on a managed install: their host, their + credential, their sending reputation. */} + {!managed && ( + channels.toggle('email')} />} + /> + )} + {SWITCH_ONLY_CHANNELS.map(ch => ( + channels.toggle(ch.id)} />} + /> + ))} + } + /> + - -
    - - - - -
    - )} + } + /> + - {/* Webhook, Ntfy and Web Push: a title, a hint and the switch each. Nothing - to set below them, so the card is its head band alone. */} - {SWITCH_ONLY_CHANNELS.map(ch => ( - channels.toggle(ch.id)} />} - /> - ))} - - {/* In-App Panel */} - } - /> - - {!managed && tripRemindersCard} -
    - -
    + {/* The SMTP relay, a section of this card: greyed and out of reach while + the email channel is off, never hidden. */} + {!managed && ( + +
    + {smtpLoaded && (<> +
    + {smtpField(SMTP_FIELDS[0])} + {smtpField(SMTP_FIELDS[1])} +
    +
    + {smtpField(SMTP_FIELDS[2])} + {smtpField(SMTP_FIELDS[3])} +
    + {smtpField(SMTP_FIELDS[4])} + )} + + { + const newVal = smtpValues.smtp_skip_tls_verify === 'true' ? 'false' : 'true' + setSmtpValues(prev => ({ ...prev, smtp_skip_tls_verify: newVal })) + }} + /> + } + /> + +
    + + + + +
    + )} + + } + end={ + // What the operator receives about running the instance: one card, the + // two targets as its blocks, then which event goes out over which channel. + {/* Admin alerts are about running the instance (version notices, and what else lands there later). On a managed install those go to whoever runs it. */} {!managed && (<> @@ -258,7 +241,6 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa @@ -286,12 +268,10 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa {/* The matrix decides which of those channels each admin-only event goes out over, so it belongs under the targets it routes to rather than across the full width below both columns. */} - - {/* Without the admin alert cards the right column is short, so the - reminder switch moves over on a managed install. */} - {managed && tripRemindersCard} -
    -
    + +
    + } + /> {/* What users' own notifications start as, across the full width: one row per user event, one column per channel users can pick (#1536). */} diff --git a/client/src/pages/admin/AdminSettingsTab.test.tsx b/client/src/pages/admin/AdminSettingsTab.test.tsx index 89d7a4097..746024a01 100644 --- a/client/src/pages/admin/AdminSettingsTab.test.tsx +++ b/client/src/pages/admin/AdminSettingsTab.test.tsx @@ -1,4 +1,4 @@ -// FE-ADMSET-001 to FE-ADMSET-043 +// FE-ADMSET-001 to FE-ADMSET-044 import { http, HttpResponse } from 'msw'; import React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -13,9 +13,20 @@ import AdminSettingsTab from './AdminSettingsTab'; type Spy = ReturnType; type Spies = Record & { toast: Record }; +/** The three tabs the settings are split into (security, services, features), on one page. */ +function AllParts({ admin, t }: { admin: AdminHook; t: ReturnType['t'] }) { + return ( + <> + + + + + ); +} + function Harness({ admin }: { admin: AdminHook }) { const { t } = useTranslation(); - return ; + return ; } function renderTab(overrides: Record = {}) { @@ -71,7 +82,7 @@ function OidcHarness() { const { t } = useTranslation(); const [oidcConfig, setOidcConfig] = React.useState(EMPTY_OIDC); const admin = buildAdminHook({ oidcConfig, setOidcConfig }); - return ; + return ; } beforeEach(() => { @@ -88,7 +99,8 @@ describe('AdminSettingsTab', () => { expect(screen.getByRole('heading', { name: 'Authentication Methods' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Passkey login' })).toBeInTheDocument(); - expect(screen.getByRole('heading', { name: /require two-factor/i })).toBeInTheDocument(); + // Requiring two-factor is a switch of the sign-in card now, not a card of its own. + expect(screen.getByText(/require 2fa/i)).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Allowed File Types' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'API Keys' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: /single sign-on/i })).toBeInTheDocument(); @@ -143,6 +155,7 @@ describe('AdminSettingsTab', () => { expect(screen.queryByText('SSO Login')).not.toBeInTheDocument(); expect(screen.queryByText('SSO Auto-Provisioning')).not.toBeInTheDocument(); + expect(screen.queryByText('Go straight to SSO')).not.toBeInTheDocument(); }); it('FE-ADMSET-008: SSO login toggle sends the inverted value', () => { @@ -167,6 +180,14 @@ describe('AdminSettingsTab', () => { expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith('oidc_registration', true, admin.setOidcRegistration); }); + it('FE-ADMSET-044: the SSO auto redirect toggle sends the inverted value (#2925)', () => { + const admin = renderTab({ oidcConfigured: true, oidcAutoRedirect: true }); + + fireEvent.click(toggleFor('Go straight to SSO')); + + expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith('oidc_auto_redirect', false, admin.setOidcAutoRedirect); + }); + it('FE-ADMSET-011: passkey toggle sends the inverted value', () => { const admin = renderTab({ passkeyLogin: false }); @@ -215,7 +236,7 @@ describe('AdminSettingsTab', () => { it('FE-ADMSET-016: require-MFA toggle flips the current value', () => { const admin = renderTab({ requireMfa: false }); - fireEvent.click(within(card(/require two-factor/i)).getByRole('button')); + fireEvent.click(toggleFor('Require 2FA')); expect(admin.handleToggleRequireMfa).toHaveBeenCalledWith(true); }); @@ -331,13 +352,11 @@ describe('AdminSettingsTab', () => { expect(screen.queryByRole('button', { name: 'Automatic' })).not.toBeInTheDocument(); }); - it('FE-ADMSET-022f: a managed install moves file types to the right column', () => { - // With place search and the keys gone the right column would stand empty. + it('FE-ADMSET-022f: a managed install keeps the file types card on the services tab', () => { + // Place search and the keys are the operator's there; the file types stay the admin's. renderTab({ managed: true }); - const right = screen.getByRole('heading', { name: 'Allowed File Types' }).closest('.min-w-0'); - expect(right).not.toBeNull(); - expect(within(right as HTMLElement).queryByRole('heading', { name: /two-factor/i })).not.toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'Allowed File Types' })).toBeInTheDocument(); }); it('FE-ADMSET-023: the maps Test button is disabled without a key', () => { @@ -475,7 +494,8 @@ describe('AdminSettingsTab', () => { // A key alone does not put Google behind the search; the server ignores the // switch under another provider, and the row must not promise otherwise. renderTab({ placesGoogleOnly: true, hasMapsKey: true, placesProvider: 'openstreetmap' }); - const hint = toggleFor('Search with Google only').closest('.flex-wrap')!.querySelector('p')!; + // The hint sits behind the row's info mark, in the page for a screen reader. + const hint = toggleFor('Search with Google only').closest('.flex-wrap')!.querySelector('.sr-only')!; expect(hint.textContent).not.toMatch(/Every search and every suggestion goes to Google Places/); expect(hint.textContent).not.toMatch(/Needs a Google Maps API key/); expect(hint.textContent).toMatch(/provider/i); diff --git a/client/src/pages/admin/AdminSettingsTab.tsx b/client/src/pages/admin/AdminSettingsTab.tsx index 2e3c2c2fa..302e34781 100644 --- a/client/src/pages/admin/AdminSettingsTab.tsx +++ b/client/src/pages/admin/AdminSettingsTab.tsx @@ -1,21 +1,20 @@ import React from 'react' -import { adminApi } from '../../api/client' -import { getApiErrorMessage } from '../../types' import { AlertTriangle, CheckCircle, Compass, Eye, EyeOff, FileType, Fingerprint, KeyRound, Loader2, LockKeyhole, LogIn, - RefreshCw, Save, ShieldCheck, XCircle, + Plane, RefreshCw, Save, XCircle, } from 'lucide-react' import ToggleSwitch from '../../components/Settings/ToggleSwitch' import CustomSelect from '../../components/shared/CustomSelect' import { fs } from '../../components/shared/DialogShell' import { EditorField, GRID_2, INPUT } from '../../components/shared/dialogParts' import { - SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsCard, SettingsHint, StatusPill, + SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsCard, SettingsColumns, SettingsHint, StatusPill, } from '../../components/Settings/settingsKit' import GoogleOptions from './GoogleOptions' import GoogleDailyLimitRow from '../../components/Admin/GoogleDailyLimitRow' import ProviderBlock from './ProviderBlock' import TrekApiCard from './TrekApiCard' +import MailIngestAdminCard from '../../components/Admin/mailIngest/MailIngestAdminCard' import PlaceContribPanel from '../../components/Admin/PlaceContribPanel' import { useAdminSettingsActions } from '../../components/Admin/useAdminSettingsActions' import { placesGoogleOnlyHint } from '../../utils/placeSource' @@ -25,6 +24,12 @@ import type { useAdmin } from './useAdmin' interface AdminSettingsTabProps { admin: ReturnType t: TranslationFn + /** + * Which tab this renders: sign-in and its safety (security), what the + * install talks to outside (services), or the setup of the features the + * addons tab switches on (features). + */ + part: 'security' | 'services' | 'features' } /** @@ -101,7 +106,7 @@ function KeyField({ shown, value, onChange, inputProps, label, onToggle }: { function SaveBar({ onClick, saving, label }: { onClick: () => void; saving: boolean; label: string }) { return (
    - @@ -109,19 +114,19 @@ function SaveBar({ onClick, saving, label }: { onClick: () => void; saving: bool ) } -// "Settings" admin tab: auth methods, require-MFA, allowed file types, API keys, -// OIDC config and the danger zone. Pure layout around the useAdmin hook. -export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): React.ReactElement { +// The admin's security, services and feature setup tabs, cut from what was one +// "Settings" tab. Pure layout around the useAdmin hook. +export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabProps): React.ReactElement { const { - toast, placesPhotosEnabled, placesAutocompleteEnabled, placesDetailsEnabled, placesEnrichEnabled, placesGoogleOnly, handleTogglePlacesGoogleOnly, - transitProvider, setTransitProviderState, - transitGoogleKeySource, setTransitGoogleKeySource, + transitProvider, + transitGoogleKeySource, placeShadowEnabled, oidcConfig, setOidcConfig, savingOidc, passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration, - oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration, + oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration, oidcAutoRedirect, setOidcAutoRedirect, + flightLive, setFlightLive, flightLiveLocked, envOverrideOidcOnly, oidcConfigured, requireMfa, passkeyLogin, setPasskeyLogin, passkeyConfigured, webauthnRpId, setWebauthnRpId, webauthnOrigins, setWebauthnOrigins, savingWebauthn, handleSaveWebauthn, @@ -135,14 +140,12 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R } = admin const { saveOidc, saveFileTypes, togglePlacesPhotos, togglePlacesAutocomplete, togglePlacesDetails, togglePlacesEnrich, - togglePlaceShadow, + togglePlaceShadow, changeTransitProvider, } = useAdminSettingsActions(admin, t) const passwordLoginLocked = !passwordLogin && !oidcLogin const oidcLoginLocked = !passwordLogin && oidcLogin - // On a managed install the right column loses place search, routing and the - // keys to the operator, so file types move over and the columns stay even. const fileTypesCard = (
    @@ -164,18 +167,9 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R ) - return ( -
    - {/* Two columns from xl up. Nearly every card here is "label left, - switch right", so on a wide screen the middle stayed empty while the - page scrolled for ages. Two explicit columns rather than a grid over - the flat list: a plain grid pairs cards row by row and leaves a hole - under whichever of the pair is shorter, and these differ by hundreds - of pixels. Grouped by subject, not by height — access and identity - left, integrations and data right. The cards carry their own bottom - margin, so only the column gap is set here. */} -
    -
    + // Each card is built once; the parts below pick theirs. + const authCard = ( + <> {/* Authentication Methods */} {envOverrideOidcOnly && {t('admin.envOverrideHint')}} @@ -235,12 +229,21 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R } /> )} - - - - {/* Passkey (WebAuthn) login */} - - + {/* Whether an instance without password login skips its own login page (#2925) */} + {oidcConfigured && ( + void handleToggleAuthSetting('oidc_auto_redirect', !oidcAutoRedirect, setOidcAutoRedirect)} + /> + } + /> + )} + {/* Passkeys and the 2FA rule are ways in too, so they sit with the others. */} } /> + handleToggleRequireMfa(!requireMfa)} + /> + } + /> - {passkeyLogin && !passkeyConfigured && {t('admin.passkey.notConfigured')}} - + + + ) + // Where passkeys bind: an expert setting, a row of the setup list. The switch + // to offer passkeys at all is in the sign-in card. + const passkeyCard = ( + <> {/* The domain passkeys bind to and the origins that may present them follow from the address the instance is served on, which the operator owns. Getting either wrong invalidates every enrolled passkey, and on a shared parent domain a wrong RP ID reaches past this instance - entirely — so they are pinned per container, not offered here. The - switch above stays: whether to offer passkeys at all is a house rule. */} - {!managed && (<> + entirely — so they are pinned per container, not offered here. */} + {!managed && ( + {webauthnRpId} : undefined} + > - )} - - - {/* Require 2FA for all users */} - - - handleToggleRequireMfa(!requireMfa)} - /> - } - /> - - - + + )} + + ) + const oidcCard = ( + <> {/* An issuer the instance names can assert any address as verified, and the discovery calls leave from inside the operator’s network. Sign-on is theirs to wire, so the fields are not offered. */} {!managed && ( /* OIDC / SSO Configuration */ - + }>{t('settings.configured')} + : }>{t('settings.notSetUp')} + } + >
    )} - - {!managed && fileTypesCard} -
    - -
    - {managed && fileTypesCard} - {/* Inside the place search card elsewhere; that card is the operator's here, - sharing place details is still the admin's decision. */} - {managed && } - + + ) + const flightCard = ( + <> + {/* Live flight status: open ADS-B data, no key, on by default; the admin may keep it off. */} + + + void handleToggleAuthSetting('flight_live_enabled', !flightLive, setFlightLive)} + /> + } + /> + + + + ) + const mailCard = ( + <> + {/* Booking mail import: how forwarded booking mails reach this install. On a managed + install the operator runs the TREK Cloud relay, so the card is not shown there. */} + {!managed && } + + ) + const servicesCard = ( + <> {/* Place search and routing: TREK's own services first, then which provider answers search and transit, and the search log. Apart from the keys, so a keyless install reads its whole setup in one card. Everything here saves as it is changed. */} {/* On a managed install place search and routing are the operator's: the services, their allowance and the providers behind them come with the - instance. Share place details stays the admin's call and has a tab of - its own there (AdminPage). */} + instance, so the whole card is left out. Share place details stays the + admin's call and is rendered on its own just above (PlaceContribPanel). */} {!managed && ( - - {!managed && (<> + {/* Transit Backend (#1699) — Transitous has no GTFS for much of Asia, so an install can point transit search at Google instead, on the same key. Falls back to Transitous when no key resolves. A block of @@ -409,24 +449,7 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R the body, which is what lets it escape the card's overflow-hidden. */} { - // A native select stayed silent when the option already selected was - // picked again; this one reports every pick, and a no-op PUT is still - // a write on an audited settings route. - if (value === transitProvider) return - const next = value === 'google' ? 'google' : 'transitous' - const previous = transitProvider - setTransitProviderState(next) - try { - const saved = await adminApi.updateTransitProvider(next) - setTransitGoogleKeySource(saved.googleKeySource) - } catch (err: unknown) { - // The select springs back on its own; without a word that reads - // as a broken control, not as a save that failed. - setTransitProviderState(previous) - toast.error(getApiErrorMessage(err, t('common.error'))) - } - }} + onChange={value => void changeTransitProvider(String(value))} options={[ { value: 'transitous', label: t('admin.transitProvider.transitous') }, { value: 'google', label: t('admin.transitProvider.google') }, @@ -448,10 +471,9 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R {t('admin.transitProvider.personalKeyWarning')} )} - )} - {/* Which keyed provider answers place search. Outside the managed guard - on purpose: the operator owns the credentials, but what their users - search against is still the admin's call (see server managed.ts). */} + {/* Which keyed provider answers place search. Never shown on a managed + install: places_provider is operator-locked there (MANAGED_LOCKED_SETTING_KEYS + in server managed.ts), so a pick would be dropped on save. */} {t('admin.placesProvider.subtitle')}
    @@ -502,11 +524,14 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R )} - + + ) + const apiKeysCard = ( + <> {/* API Keys: only the keyed providers, Google, Unsplash and Amap. They are - the operator's on a managed install, so the card is not shown there; - which provider answers search stays the admin's call in the card above - (server managed.ts). The per-place Google switches sit under the key + the operator's on a managed install, so the card is not shown there + (server managed.ts), and neither is the provider pick in the card + above. The per-place Google switches sit under the key because they are set once and then never touched. */} {!managed && ( @@ -533,7 +558,6 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R onClick={() => handleValidateKey('maps')} disabled={!mapsKeyTestable || validating.maps} className={`${SETTINGS_BUTTON} flex-none whitespace-nowrap`} - style={fs(13, 'body')} > {validating.maps ? ( @@ -658,9 +682,10 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R )} -
    -
    - + + ) + const dangerCard = ( + <> {/* Full width, and last. A destructive action should not sit beside a harmless toggle where a mis-aimed click can reach it. */} {/* Rotating the secret signs every user out and fixes nothing an instance admin @@ -676,7 +701,6 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
    + + ) + + // What used to be one "Settings" tab, split by what an admin comes for: + // who may sign in and how (security), what the install talks to outside + // (services), and how the features in the addons tab are set up there. + if (part === 'features') { + return ( + <> + {flightCard} + {mailCard} + + ) + } + if (part === 'services') { + // Place search and the services on the left, the keys and file types on the right. + return ( + + {/* Inside the place search card elsewhere; that card is the operator's here, + sharing place details is still the admin's decision. */} + {managed && } + {servicesCard} + } + end={<> + {apiKeysCard} + {fileTypesCard} + } + /> + ) + } + // Who may sign in and what it takes (the passkey domain, single sign-on), + // with the one destructive action in its own card. + return ( + // Split by length, not by kind: single sign-on is the one long form, so the + // right column holds it and the short danger zone under it. + + {authCard} + {passkeyCard} + + } + end={ + <> + {oidcCard} + {dangerCard} + + } + /> ) } diff --git a/client/src/pages/admin/AdminUserModals.tsx b/client/src/pages/admin/AdminUserModals.tsx index 87a52b278..990962ed2 100644 --- a/client/src/pages/admin/AdminUserModals.tsx +++ b/client/src/pages/admin/AdminUserModals.tsx @@ -8,6 +8,7 @@ import { Fingerprint, RefreshCw, ShieldOff, + Unlink, UserCog, UserPlus, } from 'lucide-react'; @@ -114,8 +115,9 @@ export default function AdminUserModals({ admin, t }: AdminUserModalsProps): Rea rotatingJwt, handleCreateUser, handleSaveUser, + oidcConfigured, } = admin; - const { rotateJwt, resetPasskeys, resetMfa } = useAdminUserActions(admin, t); + const { rotateJwt, resetPasskeys, resetMfa, unlinkSso } = useAdminUserActions(admin, t); const [showCreatePw, setShowCreatePw] = React.useState(false); const [showEditPw, setShowEditPw] = React.useState(false); // The user whose passkeys wait for the admin's answer in the confirm dialog. @@ -295,7 +297,6 @@ export default function AdminUserModals({ admin, t }: AdminUserModalsProps): Rea if (editingUser) setPasskeyResetUser(editingUser); }} className={`${SETTINGS_BUTTON_DANGER} flex-none`} - style={fs(12.5, 'body')} > {t('admin.passkey.reset')} @@ -311,13 +312,19 @@ export default function AdminUserModals({ admin, t }: AdminUserModalsProps): Rea type="button" onClick={() => setMfaResetUser(editingUser)} className={`${SETTINGS_BUTTON_DANGER} flex-none`} - style={fs(12.5, 'body')} > {t('admin.mfa.reset')}
    )} + )} @@ -350,7 +357,6 @@ export default function AdminUserModals({ admin, t }: AdminUserModalsProps): Rea target="_blank" rel="noopener noreferrer" className={SETTINGS_BUTTON} - style={fs(13, 'body')} > {t('admin.update.button')} @@ -480,6 +486,56 @@ docker run -d --name trek \\ confirmLabel={t('admin.mfa.reset')} danger /> + + + ); +} + +/** + * Removing a user's SSO link (#3065): its section in the edit dialog and the + * question before it. Offered only while SSO is set up, and never for the + * admin's own account. + */ +function SsoUnlinkSection({ + user, + me, + ssoSetUp, + onUnlink, + t, +}: { + user: { id: number; username: string } | null; + me: { id: number } | null | undefined; + ssoSetUp: boolean; + onUnlink: (user: { id: number }) => Promise; + t: TranslationFn; +}): React.ReactElement | null { + const [asking, setAsking] = React.useState(false); + if (!ssoSetUp || !user || user.id === me?.id) return null; + return ( + <> + +
    +

    + {t('admin.sso.unlinkHint')} +

    + +
    +
    + setAsking(false)} + onConfirm={() => void onUnlink(user)} + title={t('admin.sso.unlink')} + message={t('admin.sso.unlinkConfirm', { name: user.username })} + confirmLabel={t('admin.sso.unlink')} + danger + /> ); } diff --git a/client/src/pages/admin/AdminUsersTab.tsx b/client/src/pages/admin/AdminUsersTab.tsx index 69ee768f1..ea05276fb 100644 --- a/client/src/pages/admin/AdminUsersTab.tsx +++ b/client/src/pages/admin/AdminUsersTab.tsx @@ -58,7 +58,7 @@ export default function AdminUsersTab({ admin, t, locale }: AdminUsersTabProps): title={t('admin.tabs.users')} hint={<>{users.length} {t('admin.stats.users', { count: users.length })}} action={ - @@ -146,7 +146,7 @@ export default function AdminUsersTab({ admin, t, locale }: AdminUsersTabProps): title={t('admin.invite.title')} hint={t('admin.invite.subtitle')} action={ - diff --git a/client/src/pages/admin/FoldSummary.test.tsx b/client/src/pages/admin/FoldSummary.test.tsx deleted file mode 100644 index 319f9be12..000000000 --- a/client/src/pages/admin/FoldSummary.test.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { fireEvent, render, screen } from '../../../tests/helpers/render'; -import FoldSummary from './FoldSummary'; - -describe('FoldSummary', () => { - it('heads the fold with a turning chevron and its own label', () => { - const { container } = render( -
    - - More - -

    inside

    -
    - ); - const summary = container.querySelector('summary') as HTMLElement; - expect(summary).toContainElement(screen.getByText('More')); - const chevron = summary.querySelector('svg') as SVGElement; - expect(chevron).toHaveAttribute('aria-hidden', 'true'); - expect(chevron.getAttribute('class')).toContain('group-open:rotate-90'); - expect(summary.firstElementChild).toBe(chevron); - }); - - it('opens and closes the fold it heads', () => { - const { container } = render( -
    - More -

    inside

    -
    - ); - const details = container.querySelector('details') as HTMLDetailsElement; - expect(details.open).toBe(false); - fireEvent.click(container.querySelector('summary') as HTMLElement); - expect(details.open).toBe(true); - }); -}); diff --git a/client/src/pages/admin/FoldSummary.tsx b/client/src/pages/admin/FoldSummary.tsx deleted file mode 100644 index 6a8c10f76..000000000 --- a/client/src/pages/admin/FoldSummary.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { ChevronRight } from 'lucide-react'; -import React from 'react'; - -/** - * The clickable head of a native
    fold on the admin settings page: a - * chevron that turns when the fold opens, then whatever the fold calls itself. - * The surrounding
    needs the `group` class for the chevron to turn. - */ -export default function FoldSummary({ children }: { children: React.ReactNode }): React.ReactElement { - return ( - - - ); -} diff --git a/client/src/pages/admin/GoogleOptions.tsx b/client/src/pages/admin/GoogleOptions.tsx index 359227d46..d25300944 100644 --- a/client/src/pages/admin/GoogleOptions.tsx +++ b/client/src/pages/admin/GoogleOptions.tsx @@ -1,7 +1,5 @@ import React from 'react' -import { fs } from '../../components/shared/DialogShell' -import { StatusPill } from '../../components/Settings/settingsKit' -import FoldSummary from './FoldSummary' +import { SettingsBlock, StatusPill } from '../../components/Settings/settingsKit' interface GoogleOptionsProps { /** "Google options" — the heading of the fold. */ @@ -19,19 +17,14 @@ interface GoogleOptionsProps { * an admin opens this card at all. The switches are the opposite — set once, * then never touched, and there are five of them. * - * A native
    rather than a state hook: keyboard operable and announced - * to screen readers without writing any of that, and it survives a re-render - * without state. Drawn as a box of rows (settingsKit's SettingRows), the - * summary being its first row. + * Shown open: the settings pages fold nothing away. */ export default function GoogleOptions({ title, summary, children }: GoogleOptionsProps): React.ReactElement { return ( -
    - - {title} - {summary} - -
    {children}
    -
    + // A block of the card: its title and the count of switches on as the block's + // head, its rows inside. + {summary}} flush> + {children} + ) } diff --git a/client/src/pages/admin/ProviderBlock.tsx b/client/src/pages/admin/ProviderBlock.tsx index 60cac2598..3c7e1d9f9 100644 --- a/client/src/pages/admin/ProviderBlock.tsx +++ b/client/src/pages/admin/ProviderBlock.tsx @@ -1,6 +1,5 @@ import React from 'react' -import { fs } from '../../components/shared/DialogShell' -import { StatusPill } from '../../components/Settings/settingsKit' +import { SettingsBlock, StatusPill } from '../../components/Settings/settingsKit' interface ProviderBlockProps { title: string @@ -17,21 +16,16 @@ interface ProviderBlockProps { } /** - * One provider inside the API card, in the same shape as the TREK block above - * it, so the page reads as a list of comparable options rather than one - * highlighted thing and some loose fields underneath. A white box on the - * card's grey body, its name in a head row, like a bag in the packing sidebar. + * One provider inside the API card: its name in a head row, a pill beside it, + * its fields below, as one rounded block of the card (SettingsBlock), so the + * card reads as a list of comparable options. */ export default function ProviderBlock({ title, badge, tone = 'muted', children, }: ProviderBlockProps): React.ReactElement { return ( -
    -
    -

    {title}

    - {badge && {badge}} -
    -
    {children}
    -
    + {badge} : undefined}> + {children} + ) } diff --git a/client/src/pages/admin/TrekApiCard.tsx b/client/src/pages/admin/TrekApiCard.tsx index 16068576c..70c825208 100644 --- a/client/src/pages/admin/TrekApiCard.tsx +++ b/client/src/pages/admin/TrekApiCard.tsx @@ -1,19 +1,11 @@ import React from 'react' -import { Library, MapPin, Route, Search, X } from 'lucide-react' import TrekMark from '../../components/shared/TrekMark' import { fs } from '../../components/shared/DialogShell' import { StatusPill } from '../../components/Settings/settingsKit' -import FoldSummary from './FoldSummary' import ServiceIdentityPanel from '../../components/Admin/ServiceIdentityPanel' import PlaceContribPanel from '../../components/Admin/PlaceContribPanel' import type { TranslationFn } from '../../types' -import { - TREK_API_SOURCES as SOURCES, - trekApiAddressFeatures, - trekApiFacts, - trekApiFields, - trekApiRoutingFeatures, -} from '../../components/Admin/trekApiModel' +import { TREK_API_SOURCES as SOURCES, trekApiFacts } from '../../components/Admin/trekApiModel' interface TrekApiCardProps { t: TranslationFn @@ -35,30 +27,13 @@ interface TrekApiCardProps { * three places on the server rather than promised here, and the allowance below * the facts is what the service itself reports for this installation. */ -const CHIP = 'rounded-full border px-2.5 py-[3px] font-medium' - -/** One of the lists under "more": an icon and a name, chips, a note. */ -function FactGroup({ icon, title, note, children }: { icon: React.ReactNode; title: string; note: string; children: React.ReactNode }) { - return ( -
    -

    - {icon} - {title} -

    -
      {children}
    -

    {note}

    -
    - ) -} - export default function TrekApiCard({ t, managed = false }: TrekApiCardProps): React.ReactElement { - const fields = trekApiFields(t) const facts = trekApiFacts(t) return ( -
    -
    +
    {/* The recommendation, moved here from the Google field. It is the whole point of the block: a key should be the exception, not the default. A pill beside the mark rather than a banner, so it does not shout @@ -72,13 +47,12 @@ export default function TrekApiCard({ t, managed = false }: TrekApiCardProps): R {t('admin.trekApi.tagline')}

    -
      + {/* What it offers as compact badges that wrap, not a list of rows. */} +
        {facts.map(({ Icon, text }) => ( -
      • - - - {text} +
      • +
      • ))}
      @@ -87,72 +61,11 @@ export default function TrekApiCard({ t, managed = false }: TrekApiCardProps): R
    -
    - - {t('admin.trekApi.more')} - -
    - {/* The fields as chips rather than a paragraph. A list of what you - get is something you scan, not something you read, and a sentence - forces the reader to parse commas to answer "is the phone number - in there". One list per service, under the service's own name. */} - - - {/* Named as plainly as what IS included. An admin who switches the - source expecting ratings and a photograph of every restaurant - should find that out here and not three weeks later. */} - - - - - - - {/* Attribution, and not in the small print: the licences require the - sources to be named, and naming them is also the answer to "where - does this actually come from". */} - -
    -
    -
    + {/* The sources, named because their licences ask for it, in one line under + the card instead of a list of every field the service answers. */} +

    + {t('admin.trekApi.sourcesLabel')}: {SOURCES.join(', ')} +

    + ) } diff --git a/client/src/pages/admin/notificationDefaultsModel.ts b/client/src/pages/admin/notificationDefaultsModel.ts new file mode 100644 index 000000000..6b3894e29 --- /dev/null +++ b/client/src/pages/admin/notificationDefaultsModel.ts @@ -0,0 +1,33 @@ +import type { NotificationDefault } from '@trek/shared'; +import { Check, Lock, Minus } from 'lucide-react'; +import type { NotificationDefaultsMatrix } from './useNotificationDefaults'; + +/** + * The notification defaults grid (#1536) as both views draw it, the desktop + * AdminNotificationDefaultsPanel and the phone MAdminNotificationDefaults: each + * cell cycles On → Off → Blocked, Off a default a user may still turn on, + * Blocked off for everyone. + */ +export const NEXT_DEFAULT: Record = { + on: 'off', + off: 'blocked', + blocked: 'on', +}; +export const DEFAULT_ICON = { on: Check, off: Minus, blocked: Lock } as const; +export const DEFAULT_LABEL_KEYS: Record = { + on: 'admin.notificationDefaults.on', + off: 'admin.notificationDefaults.off', + blocked: 'admin.notificationDefaults.blocked', +}; + +/** The channels at least one event can be sent on; a channel nothing uses gets no column. */ +export function defaultChannels(matrix: NotificationDefaultsMatrix): NotificationDefaultsMatrix['channels'] { + return matrix.channels.filter((ch) => + matrix.event_types.some((evt) => matrix.implemented_combos[evt]?.includes(ch.id)) + ); +} + +/** A cell's current default; a cell the server does not list starts on. */ +export function defaultOf(matrix: NotificationDefaultsMatrix, eventType: string, channel: string): NotificationDefault { + return matrix.defaults[eventType]?.[channel] ?? 'on'; +} diff --git a/client/src/pages/admin/useAdmin.test.tsx b/client/src/pages/admin/useAdmin.test.tsx index a939e9c28..24b196622 100644 --- a/client/src/pages/admin/useAdmin.test.tsx +++ b/client/src/pages/admin/useAdmin.test.tsx @@ -100,6 +100,7 @@ describe('useAdmin', () => { password_registration: false, oidc_login: false, oidc_registration: false, + oidc_auto_redirect: false, env_override_oidc_only: true, oidc_configured: true, require_mfa: 1, @@ -116,6 +117,7 @@ describe('useAdmin', () => { expect(result.current.passwordRegistration).toBe(false); expect(result.current.oidcLogin).toBe(false); expect(result.current.oidcRegistration).toBe(false); + expect(result.current.oidcAutoRedirect).toBe(false); expect(result.current.envOverrideOidcOnly).toBe(true); expect(result.current.oidcConfigured).toBe(true); expect(result.current.requireMfa).toBe(true); @@ -878,6 +880,11 @@ describe('useAdmin', () => { expect(result.current.activeTab).toBe('audit'); }); + it('opens the notifications tab from the admin email manage link', async () => { + const { result } = await mountAdmin('/admin?tab=notifications'); + expect(result.current.activeTab).toBe('notifications'); + }); + /* * A tab id with no panel behind it — a typo, or a link from an install that * has tabs this one does not — used to open the page on an empty content diff --git a/client/src/pages/admin/useAdmin.ts b/client/src/pages/admin/useAdmin.ts index 295e236ae..e73f1293e 100644 --- a/client/src/pages/admin/useAdmin.ts +++ b/client/src/pages/admin/useAdmin.ts @@ -21,10 +21,17 @@ import { passwordErrorKey } from '../../utils/passwordError' * sidebar. Labels and icons stay in AdminPage; this is only the vocabulary. */ const ADMIN_TAB_IDS = [ - 'users', 'defaults', 'config', 'settings', 'addons', 'plugins', 'storage', + 'users', 'defaults', 'config', 'security', 'services', 'addons', 'plugins', 'storage', 'notifications', 'mcp-tokens', 'github', 'backup', 'audit', 'dev-notifications', ] +/** + * Tab ids that were renamed, so a bookmark, a wiki page or a mail that names the + * old one still lands. "Settings" was one tab for sign-in, services and the + * danger zone; it opens on security, where the danger zone went too. + */ +const ADMIN_TAB_ALIASES: Record = { settings: 'security' } + /** * The ones a managed install deliberately does not offer. * @@ -64,7 +71,8 @@ export function useAdmin() { // on every change, so the address bar keeps saying where the reader is. const [searchParams, setSearchParams] = useSearchParams() const [activeTab, setActiveTabState] = useState(() => { - const asked = searchParams.get('tab') + const raw = searchParams.get('tab') + const asked = raw ? (ADMIN_TAB_ALIASES[raw] ?? raw) : null const known = [...ADMIN_TAB_IDS, ...managedAdminTabs.map(tab => tab.id)] return asked && known.includes(asked) ? asked : 'users' }) @@ -145,6 +153,11 @@ export function useAdmin() { const [passwordRegistration, setPasswordRegistration] = useState(true) const [oidcLogin, setOidcLogin] = useState(true) const [oidcRegistration, setOidcRegistration] = useState(true) + const [oidcAutoRedirect, setOidcAutoRedirect] = useState(true) + // Live flight status (flight_live_enabled): on until an admin stores 'false'; the server leaves a never-set key out. + const [flightLive, setFlightLive] = useState(true) + // FLIGHT_LIVE_ENABLED set on the server holds the switch; the form shows its value, locked. + const [flightLiveLocked, setFlightLiveLocked] = useState(false) const [envOverrideOidcOnly, setEnvOverrideOidcOnly] = useState(false) const [oidcConfigured, setOidcConfigured] = useState(false) const [requireMfa, setRequireMfa] = useState(false) @@ -176,6 +189,8 @@ export function useAdmin() { setSmtpValues(r.data || {}) if (r.data?.webauthn_rp_id) setWebauthnRpId(r.data.webauthn_rp_id) if (r.data?.webauthn_origins) setWebauthnOrigins(r.data.webauthn_origins) + setFlightLive(String(r.data?.flight_live_enabled ?? 'true') !== 'false') + setFlightLiveLocked(r.data?.env_override_flight_live_enabled != null) setSmtpLoaded(true) }).catch(() => setSmtpLoaded(true)) }, []) @@ -286,6 +301,7 @@ export function useAdmin() { setPasswordRegistration(config.password_registration ?? config.allow_registration ?? true) setOidcLogin(config.oidc_login ?? true) setOidcRegistration(config.oidc_registration ?? config.allow_registration ?? true) + setOidcAutoRedirect(config.oidc_auto_redirect ?? true) setEnvOverrideOidcOnly(config.env_override_oidc_only ?? false) setOidcConfigured(config.oidc_configured ?? false) if (config.require_mfa !== undefined) setRequireMfa(!!config.require_mfa) @@ -600,7 +616,8 @@ export function useAdmin() { collabFeatures, setCollabFeatures, oidcConfig, setOidcConfig, savingOidc, setSavingOidc, passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration, - oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration, + oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration, oidcAutoRedirect, setOidcAutoRedirect, + flightLive, setFlightLive, flightLiveLocked, envOverrideOidcOnly, setEnvOverrideOidcOnly, oidcConfigured, setOidcConfigured, requireMfa, setRequireMfa, passkeyLogin, setPasskeyLogin, passkeyConfigured, diff --git a/client/src/pages/atlas/atlasChrome.test.ts b/client/src/pages/atlas/atlasChrome.test.ts new file mode 100644 index 000000000..802aa0434 --- /dev/null +++ b/client/src/pages/atlas/atlasChrome.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it, vi } from 'vitest'; +import { chromeFitPadding, chromePan } from './atlasChrome'; + +// FE-ATLAS-CHROME-001 onwards: the atlas camera beside the touch shell's rail and header. + +describe('atlas chrome insets', () => { + it('FE-ATLAS-CHROME-001: nothing covering the map leaves the opening view alone', () => { + expect(chromePan(undefined, -80, false)).toBeNull(); + expect(chromePan({ top: 0, start: 0 }, 40, false)).toBeNull(); + // A tall window: the far north is already below the header. + expect(chromePan({ top: 62, start: 0 }, 83, false)).toBeNull(); + }); + + it('FE-ATLAS-CHROME-005: the north edge is measured only where there is chrome to clear', () => { + const measure = vi.fn(() => -77); + expect(chromePan(undefined, measure, false)).toBeNull(); + expect(measure).not.toHaveBeenCalled(); + expect(chromePan({ top: 62, start: 0 }, measure, false)).toEqual([0, -139]); + expect(measure).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS-CHROME-002: the world moves away from the rail, in either reading direction', () => { + expect(chromePan({ top: 62, start: 100 }, 83, false)).toEqual([-50, 0]); + expect(chromePan({ top: 62, start: 100 }, 83, true)).toEqual([50, 0]); + }); + + it('FE-ATLAS-CHROME-004: on a short window the far north comes down from under the header, just as far as it needs', () => { + expect(chromePan({ top: 62, start: 0 }, -77, false)).toEqual([0, -139]); + }); + + it("FE-ATLAS-CHROME-003: a country is framed clear of the rail's side and the header", () => { + expect(chromeFitPadding({ top: 62, start: 100 }, false)).toEqual({ + paddingTopLeft: [124, 86], + paddingBottomRight: [24, 24], + }); + expect(chromeFitPadding({ top: 62, start: 100 }, true)).toEqual({ + paddingTopLeft: [24, 86], + paddingBottomRight: [124, 24], + }); + expect(chromeFitPadding(undefined, false)).toEqual({ paddingTopLeft: [24, 24], paddingBottomRight: [24, 24] }); + }); +}); diff --git a/client/src/pages/atlas/atlasChrome.ts b/client/src/pages/atlas/atlasChrome.ts new file mode 100644 index 000000000..bd84bffa6 --- /dev/null +++ b/client/src/pages/atlas/atlasChrome.ts @@ -0,0 +1,50 @@ +/** + * How much of the atlas map's edges a screen's own chrome covers, in px: the + * touch shell's rail along the leading edge, its floating header along the top. + * The phone screen measures them (MAtlas), the camera keeps clear of them. + */ +export interface AtlasChromeInsets { + top: number; + start: number; +} + +/** Arabic runs right to left, and the rail stands on the right then. */ +function documentRtl(): boolean { + return typeof document !== 'undefined' && document.documentElement.dir === 'rtl'; +} + +/** The northern edge of the inhabited world, which the opening view keeps below the header. */ +export const NORTH_EDGE_LAT = 75; + +/** + * The pan that fits the opening view to what the chrome leaves free, or null + * when there is nothing to move. Sideways the centre moves into the middle of + * the map beside the rail. Upwards the world moves down only as far as its + * inhabited top (NORTH_EDGE_LAT, at `northEdgeY` in the map's own pixels) needs + * to clear the header: a tall window shows it below the header anyway, a phone + * had the stars of the far north under it. Leaflet pans the camera, so the + * numbers point the other way from the world's move. `northEdgeY` may be a + * measurement, taken only where there is chrome: the desktop atlas has none. + */ +export function chromePan( + insets: AtlasChromeInsets | undefined, + northEdgeY: number | (() => number), + rtl = documentRtl() +): [number, number] | null { + if (!insets) return null; + const x = insets.start ? (rtl ? 1 : -1) * (insets.start / 2) : 0; + const y = Math.min(0, (typeof northEdgeY === 'function' ? northEdgeY() : northEdgeY) - insets.top); + return x || y ? [x, y] : null; +} + +/** The padding a country is framed with, wider on the rail's side and under the header. */ +export function chromeFitPadding( + insets: AtlasChromeInsets | undefined, + rtl = documentRtl() +): { paddingTopLeft: [number, number]; paddingBottomRight: [number, number] } { + const start = insets?.start ?? 0; + return { + paddingTopLeft: [24 + (rtl ? 0 : start), 24 + (insets?.top ?? 0)], + paddingBottomRight: [24 + (rtl ? start : 0), 24], + }; +} diff --git a/client/src/pages/atlas/useAtlas.ts b/client/src/pages/atlas/useAtlas.ts index d5556389d..c4760c3e3 100644 --- a/client/src/pages/atlas/useAtlas.ts +++ b/client/src/pages/atlas/useAtlas.ts @@ -1,6 +1,6 @@ -import React, { useCallback, useEffect, useMemo, useState, useRef } from 'react' +import React, { useCallback, useEffect, useLayoutEffect, useMemo, useState, useRef } from 'react' import { useNavigate } from 'react-router' -import { getIntlLanguage, getLocaleForLanguage, useTranslation } from '../../i18n' +import { getLocaleForLanguage, useTranslation } from '../../i18n' import { useSettingsStore } from '../../store/settingsStore' import { useTileUrl } from '../../hooks/useTileUrl' import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults' @@ -19,20 +19,11 @@ import { usePlaceLanguage } from '../../hooks/usePlaceLanguage' import { useServerPing } from '../../sync/useServerPing' import type { AtlasConfirmAction, VisitedRegionMap } from './useAtlasCountryActions' import { createWishlistPattern, svgWishlistFill } from './atlasWishlistFill' +import { chromeFitPadding, chromePan, NORTH_EDGE_LAT, type AtlasChromeInsets } from './atlasChrome' +import { useCountryNames } from './useCountryNames' const PLANNED_KEY = 'trek_atlas_show_planned' -function useCountryNames(language: string): (code: string) => string { - const [resolver, setResolver] = useState<(code: string) => string>(() => (code: string) => code) - useEffect(() => { - try { - const dn = new Intl.DisplayNames([getIntlLanguage(language)], { type: 'region' }) - setResolver(() => (code: string) => { try { return dn.of(code) || code } catch { return code } }) - } catch { /* */ } - }, [language]) - return resolver -} - /** * Atlas page logic — the whole interactive globe lives here: atlas/bucket-list * loading, the Leaflet map lifecycle (country + sub-national region layers, @@ -41,7 +32,9 @@ function useCountryNames(language: string): (code: string) => string { * the returned state via its presentational SidebarContent helper. * Behaviour is identical to the previous in-component logic. */ -export function useAtlas() { +export function useAtlas(options: { chromeInsets?: () => AtlasChromeInsets } = {}) { + const chromeInsetsRef = useRef(options.chromeInsets) + useLayoutEffect(() => { chromeInsetsRef.current = options.chromeInsets }) const { t, language } = useTranslation() const placeLang = usePlaceLanguage() const { settings } = useSettingsStore() @@ -380,6 +373,9 @@ export function useAtlas() { map.getPane('regionPane')!.style.zIndex = '401' mapInstance.current = map + // The opening view clears the touch shell's rail and header; the desktop atlas has none and opens as before. + const pan = chromePan(chromeInsetsRef.current?.(), () => map.latLngToContainerPoint([NORTH_EDGE_LAT, 0]).y) + if (pan) map.panBy(pan, { animate: false }) // Both renderers live as long as the map does (see the note on the refs); map.remove() // disposes them along with every other layer it holds. countryRendererRef.current = L.canvas({ padding: 0.5, tolerance: 5 }) @@ -954,7 +950,8 @@ export function useAtlas() { const layer = country_layer_by_a2_ref.current[country_code] try { if (layer?.getBounds && mapInstance.current) { - mapInstance.current.fitBounds(layer.getBounds(), { padding: [24, 24], animate: true, maxZoom: 6 }) + const padding = chromeFitPadding(chromeInsetsRef.current?.()) + mapInstance.current.fitBounds(layer.getBounds(), { ...padding, animate: true, maxZoom: 6 }) } } catch (e ) { console.error('Error fitting bounds', e) diff --git a/client/src/pages/atlas/useCountryNames.ts b/client/src/pages/atlas/useCountryNames.ts new file mode 100644 index 000000000..e6c3c7488 --- /dev/null +++ b/client/src/pages/atlas/useCountryNames.ts @@ -0,0 +1,22 @@ +import { useEffect, useState } from 'react'; +import { getIntlLanguage } from '../../i18n'; + +/** A country's name in the reader's language, from its ISO code; the code itself where none is known. */ +export function useCountryNames(language: string): (code: string) => string { + const [resolver, setResolver] = useState<(code: string) => string>(() => (code: string) => code); + useEffect(() => { + try { + const dn = new Intl.DisplayNames([getIntlLanguage(language)], { type: 'region' }); + setResolver(() => (code: string) => { + try { + return dn.of(code) || code; + } catch { + return code; + } + }); + } catch { + /* no region names in this runtime: the codes stand */ + } + }, [language]); + return resolver; +} diff --git a/client/src/pages/collections/collectionsModel.test.ts b/client/src/pages/collections/collectionsModel.test.ts index 3d90a6e7a..ee2a5e7d5 100644 --- a/client/src/pages/collections/collectionsModel.test.ts +++ b/client/src/pages/collections/collectionsModel.test.ts @@ -53,6 +53,17 @@ const HOLE = undefined as unknown as CollectionPlace; describe('collectionsModel', () => { // ── filterPlaces ──────────────────────────────────────────────────────────── describe('filterPlaces', () => { + it('FE-COLLECTIONS-MODEL-045: the search finds Óbidos and São Brás typed without accents (#3075)', () => { + const places = [ + cp({ id: 1, name: 'Óbidos', status: 'idea' }), + cp({ id: 2, name: 'São Brás de Alportel', status: 'idea' }), + cp({ id: 3, name: 'Lagos', status: 'idea', address: 'Rua de Évora' }), + ]; + expect(filterPlaces(places, 'all', 'obidos').map(p => p.id)).toEqual([1]); + expect(filterPlaces(places, 'all', 'Sao Bras').map(p => p.id)).toEqual([2]); + expect(filterPlaces(places, 'all', 'evora').map(p => p.id)).toEqual([3]); + }); + it('FE-COLLECTIONS-MODEL-001: status filter keeps only the matching status', () => { const places = [ cp({ id: 1, name: 'A', status: 'idea' }), @@ -230,11 +241,11 @@ describe('collectionsModel', () => { cp({ id: 5, name: 'E', status: 'visited' }), cp({ id: 6, name: 'F', status: 'visited' }), ]; - expect(statusCounts(places)).toEqual({ all: 6, idea: 2, want: 1, visited: 3 }); + expect(statusCounts(places)).toEqual({ all: 6, idea: 2, want: 1, visited: 3, revisit: 0 }); }); it('FE-COLLECTIONS-MODEL-015: empty input yields all zeros', () => { - expect(statusCounts([])).toEqual({ all: 0, idea: 0, want: 0, visited: 0 }); + expect(statusCounts([])).toEqual({ all: 0, idea: 0, want: 0, visited: 0, revisit: 0 }); }); it('FE-COLLECTIONS-MODEL-016: undefined entries are skipped from every count', () => { @@ -244,7 +255,12 @@ describe('collectionsModel', () => { cp({ id: 2, name: 'B', status: 'want' }), ]; expect(() => statusCounts(places)).not.toThrow(); - expect(statusCounts(places)).toEqual({ all: 2, idea: 1, want: 1, visited: 0 }); + expect(statusCounts(places)).toEqual({ all: 2, idea: 1, want: 1, visited: 0, revisit: 0 }); + }); + + it('FE-COLLECTIONS-MODEL-046: a place to revisit counts under its own status (#2567)', () => { + const places = [cp({ id: 1, name: 'A', status: 'revisit' }), cp({ id: 2, name: 'B', status: 'visited' })]; + expect(statusCounts(places)).toEqual({ all: 2, idea: 0, want: 0, visited: 1, revisit: 1 }); }); }); @@ -341,14 +357,15 @@ describe('collectionsModel', () => { // ── status metadata + cycle ───────────────────────────────────────────────── describe('status metadata', () => { - it('FE-COLLECTIONS-MODEL-040: nextStatus cycles idea → want → visited → idea', () => { + it('FE-COLLECTIONS-MODEL-040: nextStatus cycles idea → want → visited → revisit → idea', () => { expect(nextStatus('idea')).toBe('want'); expect(nextStatus('want')).toBe('visited'); - expect(nextStatus('visited')).toBe('idea'); + expect(nextStatus('visited')).toBe('revisit'); + expect(nextStatus('revisit')).toBe('idea'); }); it('FE-COLLECTIONS-MODEL-041: STATUS_ORDER holds every status exactly once', () => { - expect(STATUS_ORDER).toEqual(['idea', 'want', 'visited']); + expect(STATUS_ORDER).toEqual(['idea', 'want', 'visited', 'revisit']); }); it('FE-COLLECTIONS-MODEL-042: every status has a label key, an icon and both colours', () => { diff --git a/client/src/pages/collections/collectionsModel.ts b/client/src/pages/collections/collectionsModel.ts index 454f3881b..df976c1e3 100644 --- a/client/src/pages/collections/collectionsModel.ts +++ b/client/src/pages/collections/collectionsModel.ts @@ -1,5 +1,6 @@ import type { CollectionPlace, CollectionLabel } from '@trek/shared' import type { StatusFilter, CollectionSortMode } from '../../store/collectionStore' +import { textMatchesSearch } from '../../utils/placeSearch' /** * Pure data shaping + presentation metadata for the Collections page. No React @@ -36,7 +37,6 @@ export function filterPlaces( labelFilter: number[] = [], ratingFilter: number | 'all' = 'all', ): CollectionPlace[] { - const q = search.trim().toLowerCase() return places.filter(p => { if (!p) return false if (statusFilter !== 'all' && p.status !== statusFilter) return false @@ -44,18 +44,13 @@ export function filterPlaces( // Minimum-average-stars filter (#1435): unrated places drop out once a floor is set. if (ratingFilter !== 'all' && (p.rating_avg == null || p.rating_avg < ratingFilter)) return false if (labelFilter.length && !labelFilter.some(id => (p.label_ids ?? []).includes(id))) return false - if (!q) return true - return ( - p.name.toLowerCase().includes(q) || - (p.address ?? '').toLowerCase().includes(q) || - (p.notes ?? '').toLowerCase().includes(q) - ) + return textMatchesSearch([p.name, p.address, p.notes], search) }) } /** Count places per status for the filter chips. */ export function statusCounts(places: CollectionPlace[]): Record { - const counts: Record = { all: 0, idea: 0, want: 0, visited: 0 } + const counts: Record = { all: 0, idea: 0, want: 0, visited: 0, revisit: 0 } for (const p of places) { if (!p) continue; counts.all += 1; counts[p.status] += 1 } return counts } @@ -93,6 +88,25 @@ export function mappablePlaces(places: CollectionPlace[]): CollectionPlace[] { return places.filter(p => p && typeof p.lat === 'number' && typeof p.lng === 'number') } +/** + * A saved place with its category where the trip map reads it. The server nests a + * collection place's category (`category.color`), the markers and the hover card + * read the flat fields a trip place carries, so every pin here was the grey default + * (#3073). + */ +export function withMarkerCategory(place: CollectionPlace): CollectionPlace & { + category_name: string | null + category_color: string | null + category_icon: string | null +} { + return { + ...place, + category_name: place.category?.name ?? null, + category_color: place.category?.color ?? null, + category_icon: place.category?.icon ?? null, + } +} + /** * Normalise a user-typed link: prepend https:// when there's no scheme so the * href is absolute (a bare "booking.com" would otherwise resolve relative to the diff --git a/client/src/pages/collections/useCollections.test.tsx b/client/src/pages/collections/useCollections.test.tsx index 2b9d65701..4cc8c5059 100644 --- a/client/src/pages/collections/useCollections.test.tsx +++ b/client/src/pages/collections/useCollections.test.tsx @@ -1,4 +1,4 @@ -// FE-PAGE-COLL-001 to FE-PAGE-COLL-095 +// FE-PAGE-COLL-001 to FE-PAGE-COLL-098 // The Collections page hook. The collection store is replaced by a fixture so // every handler/branch can be driven directly; the categories request goes // through MSW, and the websocket module is already mocked in tests/setup.ts. @@ -35,8 +35,9 @@ vi.mock('../../store/collectionStore', () => ({ vi.mock('../../components/Collections/collectionFile', () => ({ downloadCollectionFile: vi.fn(), downloadCollectionGpx: vi.fn(), + downloadCollectionKml: vi.fn(), })) -import { downloadCollectionFile, downloadCollectionGpx } from '../../components/Collections/collectionFile' +import { downloadCollectionFile, downloadCollectionGpx, downloadCollectionKml } from '../../components/Collections/collectionFile' /** How long useCollections lets a run of collections:* events settle before it reloads. */ const WS_SETTLE_MS = 400 @@ -163,6 +164,7 @@ beforeEach(() => { addToast.mockClear() vi.mocked(downloadCollectionFile).mockClear() vi.mocked(downloadCollectionGpx).mockClear() + vi.mocked(downloadCollectionKml).mockClear() vi.mocked(addListener).mockClear() vi.mocked(removeListener).mockClear() installMatchMedia() @@ -379,7 +381,7 @@ describe('useCollections — derived place lists', () => { it('FE-PAGE-COLL-020: visiblePlaces keeps the saved order by default', async () => { const { result } = await setup() expect(result.current.visiblePlaces.map(p => p.id)).toEqual([2, 1, 3]) - expect(result.current.counts).toEqual({ all: 3, idea: 1, want: 1, visited: 1 }) + expect(result.current.counts).toEqual({ all: 3, idea: 1, want: 1, visited: 1, revisit: 0 }) expect(result.current.mappable.map(p => p.id)).toEqual([1, 3]) }) @@ -1200,6 +1202,52 @@ describe('useCollections — export and import as a file', () => { }) }) +// ── The same list as KML for Google My Maps (#1866) ────────────────────────── + +describe('useCollections: KML (#1866)', () => { + const exportKml = (body: Record) => + server.use(http.get('/api/addons/collections/:id/export/kml', () => HttpResponse.json(body))) + + it('FE-PAGE-COLL-096: downloads the KML under the list name, neither the list file nor a GPX', async () => { + exportKml({ name: 'Lisbon', kml: '', pins: 2, omitted: 0 }) + store.activeId = 11 + const { result } = await setup() + + await act(async () => { await result.current.handleExportList('kml') }) + + expect(downloadCollectionKml).toHaveBeenCalledWith('Lisbon', '') + expect(downloadCollectionFile).not.toHaveBeenCalled() + expect(downloadCollectionGpx).not.toHaveBeenCalled() + expect(addToast).not.toHaveBeenCalled() + expect(result.current.exporting).toBe(false) + }) + + it('FE-PAGE-COLL-097: says how many places had no coordinates and stayed out', async () => { + exportKml({ name: 'Lisbon', kml: '', pins: 2, omitted: 3 }) + store.activeId = 11 + const { result } = await setup() + + await act(async () => { await result.current.handleExportList('kml') }) + + expect(downloadCollectionKml).toHaveBeenCalled() + expect(addToast).toHaveBeenCalledWith('3 places have no coordinates and were left out of the KML file', 'info', undefined) + }) + + it('FE-PAGE-COLL-098: hands over no empty KML when no place has coordinates', async () => { + exportKml({ name: 'Lisbon', kml: '', pins: 0, omitted: 4 }) + store.activeId = 11 + const { result } = await setup() + + await act(async () => { await result.current.handleExportList('kml') }) + + expect(downloadCollectionKml).not.toHaveBeenCalled() + expect(addToast).toHaveBeenCalledWith( + 'None of these places has coordinates, so there is nothing to put in a KML file.', 'warning', undefined, + ) + expect(result.current.exporting).toBe(false) + }) +}) + // ── The same list as GPX (#2301) ───────────────────────────────────────────── describe('useCollections: GPX (#2301)', () => { diff --git a/client/src/pages/collections/useCollections.ts b/client/src/pages/collections/useCollections.ts index a7e3457d2..83dc48f41 100644 --- a/client/src/pages/collections/useCollections.ts +++ b/client/src/pages/collections/useCollections.ts @@ -3,11 +3,12 @@ import { useNavigate, useParams, useSearchParams } from 'react-router' import { useTranslation } from '../../i18n' import { useElementSize } from '../../hooks/useElementSize' import { useElementRect } from '../../hooks/useElementRect' +import { useMapLock } from '../../hooks/useMapLock' import { useSettingsStore } from '../../store/settingsStore' import { useAuthStore } from '../../store/authStore' import { useToast } from '../../components/shared/Toast' import { collectionsApi } from '../../api/collections' -import { downloadCollectionFile, downloadCollectionGpx, type CollectionExportFormat } from '../../components/Collections/collectionFile' +import { downloadCollectionFile, downloadCollectionGpx, downloadCollectionKml, type CollectionExportFormat } from '../../components/Collections/collectionFile' import { getApiErrorMessage } from '../../types' import { canAddToCollection, canRemoveFromCollection, collectionRoleOf } from '../../utils/collectionAccess' import { addListener, removeListener } from '../../api/websocket' @@ -52,6 +53,10 @@ export function useCollections() { const hero = useElementSize() // Measure the split's list column so the place-detail sheet can dock over it. const listCol = useElementRect() + // ...and the map column, so on a full map the sheet docks on the map's own edge. + const mapCol = useElementRect() + // The trip map's padlock (#2010): a locked map stays put when a place is picked. + const [mapLocked, toggleMapLocked] = useMapLock() const store = useCollectionStore() const { @@ -282,8 +287,8 @@ export function useCollections() { * * The file is fetched rather than built from what this page holds: the page * has the places for display, the server decides what may leave the instance. - * A GPX holds only places with coordinates, so the rest are counted and the - * count is said; a list with none at all gets no empty file (#2301). + * A GPX or KML holds only places with coordinates, so the rest are counted and + * the count is said; a list with none at all gets no empty file (#2301, #1866). */ const handleExportList = useCallback(async (format: CollectionExportFormat = 'trek') => { if (typeof activeId !== 'number') return @@ -293,6 +298,16 @@ export function useCollections() { downloadCollectionFile(await collectionsApi.exportFile(activeId)) return } + if (format === 'kml') { + const kml = await collectionsApi.exportKml(activeId) + if (kml.pins === 0) { + toast.warning(t('collections.file.kmlNothing')) + return + } + downloadCollectionKml(kml.name, kml.kml) + if (kml.omitted > 0) toast.info(t('collections.file.kmlOmitted', { count: kml.omitted })) + return + } const result = await collectionsApi.exportGpx(activeId) if (result.waypoints === 0) { toast.warning(t('collections.file.gpxNothing')) @@ -546,7 +561,8 @@ export function useCollections() { return { t, language, dark, navigate, isWide, heroRef: hero.ref, heroHeight: hero.height, - listColRef: listCol.ref, listColRect: listCol.rect, categories, + listColRef: listCol.ref, listColRect: listCol.rect, mapColRef: mapCol.ref, mapColRect: mapCol.rect, categories, + mapLocked, toggleMapLocked, // store data collections, ownedLists, sharedLists, activeCollection, isAllSaved, isOwner, myRole, canEdit, canDelete, diff --git a/client/src/pages/dashboard/dashboardModel.ts b/client/src/pages/dashboard/dashboardModel.ts index 981bcfc68..407504202 100644 --- a/client/src/pages/dashboard/dashboardModel.ts +++ b/client/src/pages/dashboard/dashboardModel.ts @@ -7,6 +7,7 @@ import type { Trip } from '../../types' import { localIsoDate } from '../../utils/localDate' +import { sortTripsByRelevance } from '../../utils/heroTrip' // The dashboard works with the canonical Trip shape returned by the list/get // endpoints (it already carries the computed day_count/place_count/is_owner/ @@ -83,17 +84,5 @@ export function getTripStatus(trip: DashboardTrip): 'ongoing' | 'today' | 'tomor } export function sortTrips(trips: DashboardTrip[]): DashboardTrip[] { - const today = localIsoToday() - const rank = (t: DashboardTrip) => { - if (t.start_date && t.end_date && t.start_date <= today && t.end_date >= today) return 0 - if (t.start_date && t.start_date >= today) return 1 - return 2 - } - return [...trips].sort((a, b) => { - const ra = rank(a), rb = rank(b) - if (ra !== rb) return ra - rb - const ad = a.start_date || '', bd = b.start_date || '' - if (ra <= 1) return ad.localeCompare(bd) - return bd.localeCompare(ad) - }) + return sortTripsByRelevance(trips, localIsoToday()) } diff --git a/client/src/pages/dashboard/useDashboard.ts b/client/src/pages/dashboard/useDashboard.ts index 95e191b08..6afd1f1d5 100644 --- a/client/src/pages/dashboard/useDashboard.ts +++ b/client/src/pages/dashboard/useDashboard.ts @@ -9,6 +9,7 @@ import { useTranslation } from '../../i18n' import { useToast } from '../../components/shared/Toast' import { getApiErrorMessage } from '../../types' import { localIsoToday } from './dashboardModel' +import { heroTrip } from '../../utils/heroTrip' import { useTripSearch } from './useTripSearch' import type { TripCreateRequest } from '@trek/shared' import { @@ -97,7 +98,7 @@ export function useDashboard() { // client) is read back quietly, one read per burst: no loading state and no // toast, since nobody here asked for it. trips:changed goes to the acting user // only; trip:deleted goes to the trip's room, which this page is never in. - useServerPing('trips:changed', true, async () => { + const refreshQuietly = async () => { try { const { trips, archivedTrips } = await tripRepo.list() setTrips(sortTrips(trips)) @@ -106,7 +107,8 @@ export function useDashboard() { } catch { // The list on screen stays; the next visit reads it again. } - }) + } + useServerPing('trips:changed', true, refreshQuietly) // Re-run both the trip fetch and the auth check so a recovered backend clears // the error banner (loadUser resets authCheckFailed on success). #1283 @@ -119,9 +121,7 @@ export function useDashboard() { // A trip the hero features on its own merit: one that is running, else the next // one coming up. Only that one is taken out of the grid below, so the same trip // isn't shown twice. - const featured = trips.find(t => t.start_date && t.end_date && t.start_date <= today && t.end_date >= today) - || trips.find(t => t.start_date && t.start_date >= today) - || null + const featured = heroTrip(trips, today) // With neither, the hero still shows something rather than sitting empty — but // that trip is only borrowed for the header and must stay in the grid, or a user // whose trips are all finished (or undated) sees "No trips yet". #1706 @@ -240,6 +240,8 @@ export function useDashboard() { // data + derived spotlight, heroBundle, stats, upcoming, gridTrips, isLoading, loadError: loadError || authCheckFailed, retryLoad, + // Pull-to-refresh on mobile: the same quiet read, no loading state. + refreshQuietly, // ui state tripFilter, setTripFilter, viewMode, toggleViewMode, showForm, setShowForm, editingTrip, setEditingTrip, diff --git a/client/src/pages/inAppNotifications/useInAppNotifications.ts b/client/src/pages/inAppNotifications/useInAppNotifications.ts index 1be1f68ba..7ece58280 100644 --- a/client/src/pages/inAppNotifications/useInAppNotifications.ts +++ b/client/src/pages/inAppNotifications/useInAppNotifications.ts @@ -43,6 +43,8 @@ export function useInAppNotifications() { return { notifications, unreadCount, total: shownTotal, isLoading, hasMore, unreadOnly, setUnreadOnly, loaderRef, displayed, + // Pull-to-refresh on mobile: the first page again, with the current filter. + refresh: () => fetchNotifications(true, unreadOnly), markAllRead, confirmingDeleteAll, requestDeleteAll: () => setConfirmingDeleteAll(true), diff --git a/client/src/pages/journey/useJourney.ts b/client/src/pages/journey/useJourney.ts index 35b66ea1c..ae4f873ba 100644 --- a/client/src/pages/journey/useJourney.ts +++ b/client/src/pages/journey/useJourney.ts @@ -192,6 +192,8 @@ export function useJourney() { return { navigate, journeys, loading, + // Pull-to-refresh on mobile; the list stays on screen while it reloads. + loadJourneys, showCreate, setShowCreate, newTitle, setNewTitle, newSubtitle, setNewSubtitle, availableTrips, selectedTripIds, setSelectedTripIds, searchOpen, setSearchOpen, searchQuery, setSearchQuery, searchInputRef, diff --git a/client/src/pages/journeyDetail/JourneyDetailPage.helpers.test.ts b/client/src/pages/journeyDetail/JourneyDetailPage.helpers.test.ts index 5382d1a84..6c87f4ece 100644 --- a/client/src/pages/journeyDetail/JourneyDetailPage.helpers.test.ts +++ b/client/src/pages/journeyDetail/JourneyDetailPage.helpers.test.ts @@ -2,8 +2,10 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { PROVIDER_SELECT_ALL_MAX_PAGES } from '@trek/shared'; import { createDraftJourneyEntry, + entryForPlace, distanceBetweenGeoPoints, fetchRemainingProviderPages, + filterPhotosByDayRange, groupPhotosByDate, matchJourneyEntries, posterlessVideo, @@ -185,6 +187,35 @@ describe('createDraftJourneyEntry', () => { }); }); +describe('entryForPlace', () => { + const place = { place_id: 4, name: 'Piazza San Marco', lat: 45.434, lng: 12.3388, days: ['2026-05-14', '2026-05-15'], time: '10:00' }; + + it('a planned place starts a new entry on its first day, at its time and spot, named after it', () => { + const entry = entryForPlace({ id: 7, entries: [] }, place, new Date('2026-06-01T08:00:00')); + expect(entry).toMatchObject({ + id: 0, + journey_id: 7, + entry_date: '2026-05-14', + entry_time: '10:00', + title: 'Piazza San Marco', + location_name: 'Piazza San Marco', + location_lat: 45.434, + location_lng: 12.3388, + }); + }); + + it('writes up the suggestion the trip left for the place, so the entry stays linked to it', () => { + const suggestion = { ...createDraftJourneyEntry(7), id: 31, type: 'skeleton' as const, source_place_id: 4 }; + const other = { ...createDraftJourneyEntry(7), id: 32, type: 'skeleton' as const, source_place_id: 5 }; + expect(entryForPlace({ id: 7, entries: [other, suggestion] }, place)).toBe(suggestion); + }); + + it('a place without a planned time takes the time of now', () => { + const entry = entryForPlace({ id: 7 }, { ...place, time: null }, new Date('2026-06-01T08:05:00')); + expect(entry.entry_time).toBe('08:05'); + }); +}); + describe('matchJourneyEntries', () => { const entries = [ { id: 1, title: 'Mercado da Ribeira', story: 'Ate too much', location_name: 'Lisbon', tags: ['food'] }, @@ -360,3 +391,33 @@ describe('sortByCaptureTimeAsc (#1587)', () => { expect(items.map((i) => i.id)).toEqual(['b', 'a']); }); }); + +describe('filterPhotosByDayRange (#2859)', () => { + const photos = [ + { id: 'before', takenAt: '2026-03-09T12:00:00.000Z' }, + { id: 'first', takenAt: '2026-03-10T08:00:00.000Z' }, + // Taken late on the 12th by the photographer's wall clock, already the 13th in UTC. + { id: 'wallclock', takenAt: '2026-03-13T01:00:00.000Z', localTakenAt: '2026-03-12T21:00:00.000Z' }, + { id: 'after', takenAt: '2026-03-13T09:00:00.000Z' }, + { id: 'undated' }, + ]; + const ids = (list: { id: string }[]) => list.map((p) => p.id); + + it('keeps the days between both ends, both included, by the day the grid files them under', () => { + expect(ids(filterPhotosByDayRange(photos, '2026-03-10', '2026-03-12'))).toEqual(['first', 'wallclock']); + }); + + it('reads an empty end as open', () => { + expect(ids(filterPhotosByDayRange(photos, '2026-03-12', ''))).toEqual(['wallclock', 'after']); + expect(ids(filterPhotosByDayRange(photos, '', '2026-03-09'))).toEqual(['before']); + }); + + it('reads ends given the wrong way round as the range they mean', () => { + expect(ids(filterPhotosByDayRange(photos, '2026-03-12', '2026-03-10'))).toEqual(['first', 'wallclock']); + }); + + it('is no filter at all without a range, and drops undated photos once there is one', () => { + expect(filterPhotosByDayRange(photos, '', '')).toBe(photos); + expect(ids(filterPhotosByDayRange(photos, '2000-01-01', '2100-01-01'))).not.toContain('undated'); + }); +}); diff --git a/client/src/pages/journeyDetail/JourneyDetailPage.helpers.ts b/client/src/pages/journeyDetail/JourneyDetailPage.helpers.ts index 089dbdb6b..fadfdbb89 100644 --- a/client/src/pages/journeyDetail/JourneyDetailPage.helpers.ts +++ b/client/src/pages/journeyDetail/JourneyDetailPage.helpers.ts @@ -48,6 +48,32 @@ export function createDraftJourneyEntry(journeyId: number, now = new Date(), onD }; } +/** + * The entry to write about a planned place picked on the journey map: the + * suggestion the trip left for it, when the journal still has one (writing it + * up keeps its link to the place), else a new entry on the place's first day, + * at its time and spot, named after it. + */ +export function entryForPlace( + journey: { id: number; entries?: JourneyEntry[] }, + place: { place_id: number; name: string; lat: number; lng: number; days: string[]; time?: string | null }, + now = new Date() +): JourneyEntry { + const suggestion = (journey.entries ?? []).find( + (entry) => entry.type === 'skeleton' && entry.source_place_id === place.place_id + ); + if (suggestion) return suggestion; + const draft = createDraftJourneyEntry(journey.id, now, place.days[0]); + return { + ...draft, + entry_time: place.time ?? draft.entry_time, + title: place.name, + location_name: place.name, + location_lat: place.lat, + location_lng: place.lng, + }; +} + export function formatDate(d: string, locale?: string): { weekday: string; month: string; day: number } { const date = new Date(d + 'T00:00:00'); // Pass the app's selected locale so weekday/month follow the UI language @@ -100,6 +126,32 @@ export function photoLocalDay(asset: { takenAt?: string | null; localTakenAt?: s return Number.isNaN(parsed.getTime()) ? taken.slice(0, 10) : localIsoDate(parsed); } +/** + * The photos taken between two calendar days, both ends included. + * + * An album comes back from the provider whole, and a shared one can hold years + * of somebody else's photos, so the picker narrows what it already has rather + * than asking again (#2859). The day is the one the grid files a photo under, + * so a photo never shows under a heading the range excludes. Either end may be + * empty for an open range; with both empty the list comes back untouched, same + * reference. A photo with no readable date has nothing to compare and is left + * out once a range is set. Ends given the wrong way round are read as the + * range they obviously mean. + */ +export function filterPhotosByDayRange( + photos: T[], + from: string, + to: string, +): T[] { + if (!from && !to) return photos; + const [start, end] = from && to && from > to ? [to, from] : [from, to]; + return photos.filter((photo) => { + const day = photoLocalDay(photo); + if (day === '__unknown__') return false; + return (!start || day >= start) && (!end || day <= end); + }); +} + /** * The reader's own UTC offset where a given calendar day starts, in minutes east * of UTC. diff --git a/client/src/pages/journeyDetail/useJourneyDetail.test.tsx b/client/src/pages/journeyDetail/useJourneyDetail.test.tsx index b4e8a2ef0..2f6168d15 100644 --- a/client/src/pages/journeyDetail/useJourneyDetail.test.tsx +++ b/client/src/pages/journeyDetail/useJourneyDetail.test.tsx @@ -162,7 +162,8 @@ describe('useJourneyDetail', () => { setup({ search: '?create=entry' }); await waitFor(() => expect(latest.editingEntry).not.toBeNull()); expect(latest.editingEntry).toMatchObject({ id: 0, journey_id: 7, type: 'entry', visibility: 'private' }); - expect(screen.getByTestId('search')).toHaveTextContent(''); + // The parameter goes in the same effect but reaches the URL a render later. + await waitFor(() => expect(screen.getByTestId('search')).toBeEmptyDOMElement()); }); it('FE-JRN-DETHOOK-004: a viewer never gets the draft editor', async () => { diff --git a/client/src/pages/journeyDetail/useJourneyDetail.ts b/client/src/pages/journeyDetail/useJourneyDetail.ts index 1f85322db..a22cb9679 100644 --- a/client/src/pages/journeyDetail/useJourneyDetail.ts +++ b/client/src/pages/journeyDetail/useJourneyDetail.ts @@ -13,10 +13,10 @@ import { lockBodyScroll } from '../../utils/bodyScrollLock' import { localIsoDate } from '../../utils/localDate' import { journeyOpenAtEntryId } from '../../components/Journey/journeyOpenAt' import type { JourneyEntry } from '../../store/journeyStore' -import { createDraftJourneyEntry, photoUrl } from './JourneyDetailPage.helpers' +import { createDraftJourneyEntry, entryForPlace, photoUrl } from './JourneyDetailPage.helpers' import { useDawarichSuggestions } from '../../hooks/useDawarichSuggestions' import { openStaysByDate } from '../../components/Dawarich/dawarichSuggestionModel' -import type { DawarichSuggestion, DawarichSuggestionTarget } from '@trek/shared' +import type { DawarichSuggestion, DawarichSuggestionTarget, JourneyMapPlace } from '@trek/shared' import { useDawarichJournalTrail } from '../../hooks/useDawarichJournalTrail' import { useJourneyDetailLayers } from './useJourneyDetailLayers' @@ -595,5 +595,8 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto, addPickedProviderPhotos: providerPhotos.addPickedPhotos, addEntryProviderPhotos: providerPhotos.addEntryPhotos, + // A planned place picked on the map that nothing was written about yet: write it up. + writeAboutPlace: + canEditEntries && current ? (place: JourneyMapPlace) => setEditingEntry(entryForPlace(current, place)) : undefined, } } diff --git a/client/src/pages/journeyPublic/useJourneyPublic.ts b/client/src/pages/journeyPublic/useJourneyPublic.ts index 24241a0d9..8bcfc799f 100644 --- a/client/src/pages/journeyPublic/useJourneyPublic.ts +++ b/client/src/pages/journeyPublic/useJourneyPublic.ts @@ -32,6 +32,8 @@ export function useJourneyPublic() { const [showLangPicker, setShowLangPicker] = useState(false) const locale = useSettingsStore(s => s.settings.language) || 'en' const mapRef = useRef(null) + // The desktop feed, for the day picker to scroll (#2998). + const feedRef = useRef(null) const [activeEntryId, setActiveEntryId] = useState(null) const [viewingEntry, setViewingEntry] = useState(null) @@ -170,7 +172,7 @@ export function useJourneyPublic() { return { token, data, loading, error, isMobile, locale, view, setView, lightbox, setLightbox, showLangPicker, setShowLangPicker, - mapRef, activeEntryId, setActiveEntryId, viewingEntry, setViewingEntry, handleMarkerClick, + mapRef, feedRef, activeEntryId, setActiveEntryId, viewingEntry, setViewingEntry, handleMarkerClick, perms, journey, stats, timelineEntries, groupedEntries, sortedDates, displayDates, sidebarMapItems, allPhotos, stopNumberById, mapPhotos, mapLayers, entryTitleOf, diff --git a/client/src/pages/login/MfaCodeStep.tsx b/client/src/pages/login/MfaCodeStep.tsx new file mode 100644 index 000000000..364f21d1d --- /dev/null +++ b/client/src/pages/login/MfaCodeStep.tsx @@ -0,0 +1,99 @@ +import { KeyRound } from 'lucide-react'; +import React from 'react'; +import { useTranslation } from '../../i18n'; + +interface MfaCodeStepProps { + /** The account being signed in, kept in the form for password managers. */ + email: string; + code: string; + onCode: (code: string) => void; + inputStyle: React.CSSProperties; + onBack: () => void; +} + +/** The login's second step: the one-time or backup code, and the way back. */ +export default function MfaCodeStep({ email, code, onCode, inputStyle, onBack }: MfaCodeStepProps) { + const { t } = useTranslation(); + return ( +
    + + {/* The account the code belongs to, for password managers: they match a + one-time code to a saved login through the username in the same form, + and the email field is gone in this step. */} + +
    + + ) => onCode(e.target.value.toUpperCase().slice(0, 24))} + placeholder={t('login.mfaPlaceholder')} + required + autoFocus + style={inputStyle} + onFocus={(e: React.FocusEvent) => (e.target.style.borderColor = '#111827')} + onBlur={(e: React.FocusEvent) => (e.target.style.borderColor = '#e5e7eb')} + /> +
    +

    + {t('login.mfaHint')} +

    + +
    + ); +} diff --git a/client/src/pages/login/NativeServerLink.tsx b/client/src/pages/login/NativeServerLink.tsx new file mode 100644 index 000000000..fa68e15ee --- /dev/null +++ b/client/src/pages/login/NativeServerLink.tsx @@ -0,0 +1,18 @@ +import { useNativeServer } from '../../components/Settings/useNativeServer'; +import { useTranslation } from '../../i18n'; + +/** Inside the iOS/Android app only: the way from the sign-in screen back to the address screen. */ +export default function NativeServerLink() { + const { t } = useTranslation(); + const { host, changeServer } = useNativeServer(); + if (!host) return null; + return ( + + ); +} diff --git a/client/src/pages/login/languageCorner.ts b/client/src/pages/login/languageCorner.ts new file mode 100644 index 000000000..a5ec9b011 --- /dev/null +++ b/client/src/pages/login/languageCorner.ts @@ -0,0 +1,7 @@ +// Where the login page's language menu stands: below the status bar in the app and under a +// notch, and beside an element in the top corner such as an iPhone Duo's status capsule. The +// insets the iOS app measures (--trek-native-*) are a floor under env(), as in the touch shell. +export const LANGUAGE_CORNER_CLASS = + 'absolute z-10 top-[calc(max(env(safe-area-inset-top,0px),var(--trek-native-safe-top,0px))+16px)] ' + + 'end-[calc(16px+max(env(safe-area-inset-right,0px),var(--trek-native-safe-right,0px),var(--trek-native-corner-right,0px)))] ' + + 'rtl:end-[calc(16px+max(env(safe-area-inset-left,0px),var(--trek-native-safe-left,0px),var(--trek-native-corner-left,0px)))]'; diff --git a/client/src/pages/login/useLogin.native.test.tsx b/client/src/pages/login/useLogin.native.test.tsx new file mode 100644 index 000000000..dc5fad5f0 --- /dev/null +++ b/client/src/pages/login/useLogin.native.test.tsx @@ -0,0 +1,154 @@ +// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-008: useLogin inside the iOS/Android app +import { startAuthentication } from '@simplewebauthn/browser'; +import { http, HttpResponse } from 'msw'; +import React from 'react'; +import { MemoryRouter } from 'react-router'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildAppConfig } from '../../../tests/helpers/factories'; +import { server } from '../../../tests/helpers/msw/server'; +import { act, renderHook, waitFor } from '../../../tests/helpers/render'; +import { resetAllStores } from '../../../tests/helpers/store'; +import { TranslationProvider } from '../../i18n/TranslationContext'; +import { BrowserSignInCancelled, resumeBrowserSignIn, signInThroughBrowser } from '../../native/browserSignIn'; +import { useAuthStore } from '../../store/authStore'; +import { markSignedOut, wasSignedOut } from '../../utils/signedOut'; +import { useLogin } from './useLogin'; + +// Stable across renders: useLogin's config effect depends on navigate. +const mockNavigate = vi.fn(); +vi.mock('react-router', async () => { + const actual = await vi.importActual('react-router'); + return { ...actual, useNavigate: () => mockNavigate }; +}); +vi.mock('@simplewebauthn/browser', () => ({ startAuthentication: vi.fn() })); +vi.mock('../../native/platform', () => ({ isNativeApp: () => true })); +vi.mock('../../native/browserSignIn', async () => { + const actual = await vi.importActual('../../native/browserSignIn'); + return { ...actual, signInThroughBrowser: vi.fn(), resumeBrowserSignIn: vi.fn() }; +}); + +const realLocation = window.location; +const loadUser = vi.fn(async () => {}); + +function renderLogin() { + return renderHook(() => useLogin(), { + wrapper: ({ children }: { children: React.ReactNode }) => ( + + {children} + + ), + }); +} + +function clickEvent() { + return { preventDefault: vi.fn() } as unknown as React.MouseEvent; +} + +beforeEach(() => { + resetAllStores(); + vi.mocked(signInThroughBrowser).mockReset(); + vi.mocked(resumeBrowserSignIn).mockReset().mockResolvedValue(false); + vi.mocked(startAuthentication).mockReset(); + loadUser.mockClear(); + useAuthStore.setState({ loadUser }); + Object.defineProperty(window, 'location', { + configurable: true, + writable: true, + value: { ...realLocation, pathname: '/login', href: 'http://localhost/login', search: '' }, + }); +}); + +afterEach(() => { + vi.useRealTimers(); + Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation }); +}); + +describe('useLogin in the native app', () => { + it('FE-LOGIN-NATIVE-001: remembers the login by default in the app', async () => { + const { result } = renderLogin(); + await waitFor(() => expect(result.current.appConfig).not.toBeNull()); + expect(result.current.rememberMe).toBe(true); + }); + + it('FE-LOGIN-NATIVE-002: does not bounce an OIDC-only install to the IdP inside the WebView', async () => { + server.use( + http.get('/api/auth/app-config', () => + HttpResponse.json(buildAppConfig({ password_login: false, oidc_configured: true, oidc_login: true })) + ) + ); + const { result } = renderLogin(); + await waitFor(() => expect(result.current.appConfig).not.toBeNull()); + expect(window.location.href).toBe('http://localhost/login'); + expect(result.current.oidcOnly).toBe(true); + }); + + it('FE-LOGIN-NATIVE-003: routes the SSO link through the system browser and signs in', async () => { + vi.mocked(signInThroughBrowser).mockResolvedValue(); + markSignedOut(); + const { result } = renderLogin(); + const event = clickEvent(); + + await act(async () => { + result.current.handleSsoClick(event); + }); + + expect(event.preventDefault).toHaveBeenCalled(); + expect(wasSignedOut()).toBe(false); + expect(signInThroughBrowser).toHaveBeenCalledWith('oidc'); + await waitFor(() => expect(loadUser).toHaveBeenCalledWith({ silent: true })); + await waitFor(() => expect(result.current.showTakeoff).toBe(true)); + }); + + it('FE-LOGIN-NATIVE-004: sends the passkey button to the browser instead of WebAuthn', async () => { + vi.mocked(signInThroughBrowser).mockResolvedValue(); + const { result } = renderLogin(); + + await act(async () => { + await result.current.handlePasskeyLogin(); + }); + + expect(signInThroughBrowser).toHaveBeenCalledWith('passkey'); + expect(startAuthentication).not.toHaveBeenCalled(); + }); + + it('FE-LOGIN-NATIVE-005: stays quiet when the user closes the browser', async () => { + vi.mocked(signInThroughBrowser).mockRejectedValue(new BrowserSignInCancelled()); + const { result } = renderLogin(); + + await act(async () => { + await result.current.handlePasskeyLogin(); + }); + + expect(result.current.error).toBe(''); + expect(result.current.isLoading).toBe(false); + }); + + it('FE-LOGIN-NATIVE-006: explains a failed hand-off', async () => { + vi.mocked(signInThroughBrowser).mockRejectedValue(new Error('exchange failed')); + const { result } = renderLogin(); + + await act(async () => { + await result.current.handlePasskeyLogin(); + }); + + expect(result.current.error).toBe('Signing in did not work. Please try again.'); + expect(result.current.isLoading).toBe(false); + }); + + it('FE-LOGIN-NATIVE-007: signs in with a browser return that reached an app Android started anew', async () => { + vi.mocked(resumeBrowserSignIn).mockResolvedValue(true); + const { result } = renderLogin(); + + await waitFor(() => expect(loadUser).toHaveBeenCalledWith({ silent: true })); + await waitFor(() => expect(result.current.showTakeoff).toBe(true)); + expect(signInThroughBrowser).not.toHaveBeenCalled(); + }); + + it('FE-LOGIN-NATIVE-008: explains a kept return that could not be redeemed, and stays on the page otherwise', async () => { + vi.mocked(resumeBrowserSignIn).mockRejectedValue(new Error('exchange failed')); + const { result } = renderLogin(); + + await waitFor(() => expect(result.current.error).toBe('Signing in did not work. Please try again.')); + expect(result.current.showTakeoff).toBe(false); + }); +}); diff --git a/client/src/pages/login/useLogin.test.tsx b/client/src/pages/login/useLogin.test.tsx index 0b23b7e49..ca024a54a 100644 --- a/client/src/pages/login/useLogin.test.tsx +++ b/client/src/pages/login/useLogin.test.tsx @@ -417,6 +417,37 @@ describe('useLogin — OIDC callback', () => { const { result } = renderLogin(); await waitFor(() => expect(result.current.error).toBe('some_new_provider_code')); }); + + it('FE-LOGIN-HOOK-213: a failed round trip the app started keeps the way back to the handoff page', async () => { + const handoff = `/native-handoff?challenge=${'a'.repeat(64)}`; + sessionStorage.setItem('oidc_redirect', handoff); + localStorage.removeItem('trek_native_handoff_return'); + setSearch('?oidc_error=invalid_state'); + + const { result } = renderLogin(); + await waitFor(() => expect(result.current.error).toBe('Invalid session. Please try again.')); + expect(sessionStorage.getItem('oidc_redirect')).toBe(handoff); + expect(JSON.parse(localStorage.getItem('trek_native_handoff_return') ?? '{}').path).toBe(handoff); + }); + + it('FE-LOGIN-HOOK-214: the SSO retry after that failure ends on the handoff page, not in the web app', async () => { + const handoff = `/native-handoff?challenge=${'b'.repeat(64)}`; + sessionStorage.setItem('oidc_redirect', handoff); + localStorage.removeItem('trek_native_handoff_return'); + setSearch('?oidc_error=invalid_state'); + + const failed = renderLogin(); + await waitFor(() => expect(failed.result.current.error).toBe('Invalid session. Please try again.')); + failed.unmount(); + + setSearch('?oidc_code=code-retry'); + server.use(http.get('/api/auth/oidc/exchange', () => HttpResponse.json({ success: true }))); + renderLogin(); + + await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith(handoff, { replace: true })); + expect(sessionStorage.getItem('oidc_redirect')).toBeNull(); + expect(localStorage.getItem('trek_native_handoff_return')).toBeNull(); + }); }); describe('useLogin — language detection', () => { @@ -1181,6 +1212,43 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => { expect(window.location.href).toBe('http://localhost/login'); }); + it('FE-LOGIN-HOOK-215: with the auto redirect turned off the page stays, with its SSO button (#2925)', async () => { + server.use( + http.get('/api/auth/app-config', () => HttpResponse.json({ ...oidcOnlyConfig(), oidc_auto_redirect: false })), + ); + const { result } = renderLogin(); + await ready(result); + + expect(result.current.oidcOnly).toBe(true); + expect(result.current.redirectScreen).toBe(false); + expect(result.current.configWait).toBe(false); + expect(window.location.href).toBe('http://localhost/login'); + }); + + it('FE-LOGIN-HOOK-216: a cached config with the auto redirect off announces no redirect while the probe is out', async () => { + const config = { ...oidcOnlyConfig(), oidc_auto_redirect: false }; + localStorage.setItem(CONFIG_CACHE_KEY, JSON.stringify(config)); + const release = heldConfig(config); + const { result } = renderLogin(); + + expect(result.current.redirectScreen).toBe(false); + expect(result.current.configWait).toBe(true); + + release(); + await ready(result); + expect(result.current.redirectScreen).toBe(false); + expect(window.location.href).toBe('http://localhost/login'); + }); + + it('FE-LOGIN-HOOK-217: a server from before the switch, with no field, keeps the redirect', async () => { + const config: Record = { ...oidcOnlyConfig() }; + delete config.oidc_auto_redirect; + server.use(http.get('/api/auth/app-config', () => HttpResponse.json(config))); + renderLogin(); + + await waitFor(() => expect(window.location.href).toBe('/api/auth/oidc/login?remember=1')); + }); + it('FE-LOGIN-HOOK-210: right after a sign-out the cached redirect is not announced', async () => { localStorage.setItem(CONFIG_CACHE_KEY, JSON.stringify(oidcOnlyConfig())); const release = heldConfig(oidcOnlyConfig()); diff --git a/client/src/pages/login/useLogin.ts b/client/src/pages/login/useLogin.ts index 2e0293a6a..0aa7550c9 100644 --- a/client/src/pages/login/useLogin.ts +++ b/client/src/pages/login/useLogin.ts @@ -4,11 +4,21 @@ import { useAuthStore } from '../../store/authStore' import { useSettingsStore, hasStoredLanguage } from '../../store/settingsStore' import { useTranslation, detectBrowserLanguage } from '../../i18n' import { startAuthentication } from '@simplewebauthn/browser' -import { wasSignedOut } from '../../utils/signedOut' +import { clearSignedOut, wasSignedOut } from '../../utils/signedOut' import { authApi, configApi } from '../../api/client' import { getApiErrorMessage } from '../../types' import { START_DESTINATION_ROUTE } from '../../utils/startDestination' import { passwordErrorKey } from '../../utils/passwordError' +import { isNativeApp } from '../../native/platform' +import { + BrowserSignInCancelled, + isHandoffReturn, + rememberHandoffReturn, + resumeBrowserSignIn, + signInThroughBrowser, + takeHandoffReturn, + type BrowserSignInStart, +} from '../../native/browserSignIn' interface AppConfig { has_users: boolean @@ -23,6 +33,8 @@ interface AppConfig { password_registration: boolean oidc_login: boolean oidc_registration: boolean + /** False when the admin wants the login page shown before the IdP; absent on servers from before #2925. */ + oidc_auto_redirect?: boolean passkey_login?: boolean passkey_configured?: boolean env_override_oidc_only: boolean @@ -46,6 +58,14 @@ function readCachedConfig(): AppConfig | null { const isOidcOnly = (config: AppConfig | null): boolean => !!config && !config.password_login && config.oidc_login && config.oidc_configured +/** + * Whether the login page leaves for the IdP by itself: an OIDC-only instance + * does, unless its admin turned that off to show the page and its SSO button + * first (#2925). A config without the field keeps the redirect. + */ +const redirectsToIdp = (config: AppConfig | null): boolean => + isOidcOnly(config) && config?.oidc_auto_redirect !== false + /** * Login data hook — owns the whole auth surface: login/register/demo, the MFA * step-up, the must-change-password step, the OIDC code exchange + error @@ -59,7 +79,10 @@ export function useLogin() { const [username, setUsername] = useState('') const [email, setEmail] = useState('') const [password, setPassword] = useState('') - const [rememberMe, setRememberMe] = useState(false) + // On by default in the app: a session cookie there dies with the app process, + // and nobody expects to sign in again every time the phone unloads an app. + const [rememberMe, setRememberMe] = useState(isNativeApp) + const [nativeApp] = useState(isNativeApp) const [showPassword, setShowPassword] = useState(false) const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState('') @@ -75,7 +98,7 @@ export function useLogin() { const [cachedConfig] = useState(readCachedConfig) const [expectRedirect] = useState(() => { const params = new URLSearchParams(window.location.search) - return isOidcOnly(cachedConfig) && !!cachedConfig?.has_users + return !isNativeApp() && redirectsToIdp(cachedConfig) && !!cachedConfig?.has_users && !params.get('invite') && !params.get('oidc_code') && !params.get('oidc_error') }) const [idpRedirect, setIdpRedirect] = useState(false) @@ -183,7 +206,9 @@ export function useLogin() { if (!config.has_users) setMode('register') // Skip auto-redirect when config is from cache — network is unreliable // and auto-redirecting to the IdP could loop if the proxy changed. - if (allowRedirect && !fromCache && isOidcOnly(config) && config.has_users && !invite && !noRedirect) { + // Not in the app: its WebView cannot host the IdP, and opening the + // system browser uninvited on every launch would be worse than a button. + if (allowRedirect && !fromCache && !nativeApp && redirectsToIdp(config) && config.has_users && !invite && !noRedirect) { setIdpRedirect(true) window.location.href = IDP_LOGIN_URL } @@ -214,7 +239,9 @@ export function useLogin() { // body is never read, so it can go without breaking SSO sign-in. if (ok && data.success === true) { await loadUser() - const savedRedirect = sessionStorage.getItem('oidc_redirect') || START_DESTINATION_ROUTE + // Taken either way, so a handoff left from an abandoned sign-in cannot catch a later one. + const handoffReturn = takeHandoffReturn() + const savedRedirect = sessionStorage.getItem('oidc_redirect') || handoffReturn || START_DESTINATION_ROUTE sessionStorage.removeItem('oidc_redirect') navigate(savedRedirect, { replace: true }) } else { @@ -241,14 +268,21 @@ export function useLogin() { email_link_blocked: t('login.oidc.emailLinkBlocked'), } setError(errorMessages[oidcError] || oidcError) - sessionStorage.removeItem('oidc_redirect') + // A round trip the app's sign-in started keeps its way back. The next SSO + // attempt from this page is a plain web login, and without the handoff page + // to return to it ends in the web app inside the app's browser sheet. The + // handoff page asks for a tap before it passes anything on, so keeping the + // path hands nothing over by itself; the copy is renewed for a slow retry. + const stashed = sessionStorage.getItem('oidc_redirect') + if (isHandoffReturn(stashed)) rememberHandoffReturn(stashed) + else sessionStorage.removeItem('oidc_redirect') window.history.replaceState({}, '', '/login') loadConfig(false) return } loadConfig(true) - }, [navigate, t, noRedirect]) + }, [navigate, t, noRedirect, nativeApp]) // Language detection chain (runs once on mount, only if user has no saved preference): // 1. localStorage → already in store initial state, skip @@ -289,7 +323,47 @@ export function useLogin() { } } + // In the app: a sign-in the system browser finished while Android started the + // app anew. Its return waited natively; redeemed here, it signs the app in. + useEffect(() => { + if (!nativeApp) return + resumeBrowserSignIn() + .then(async (signedIn) => { + if (!signedIn) return + await loadUser({ silent: true }) + setShowTakeoff(true) + void loadSettings() + setTimeout(() => { + void navigate(redirectTarget) + }, 2600) + }) + .catch(() => setError(t('native.login.failed'))) + }, [nativeApp, loadUser, loadSettings, navigate, redirectTarget, t]) + + /** In the app: SSO and passkeys run in the system browser (native/browserSignIn.ts). */ + const handleBrowserSignIn = async (start?: BrowserSignInStart): Promise => { + setError('') + setIsLoading(true) + try { + await signInThroughBrowser(start) + await loadUser({ silent: true }) + takeOff() + } catch (err: unknown) { + if (!(err instanceof BrowserSignInCancelled)) setError(t('native.login.failed')) + setIsLoading(false) + } + } + + /** The SSO links: a plain navigation in a browser, the system browser in the app. */ + const handleSsoClick = (e: React.MouseEvent): void => { + clearSignedOut() + if (!nativeApp) return + e.preventDefault() + void handleBrowserSignIn('oidc') + } + const handlePasskeyLogin = async (): Promise => { + if (nativeApp) return handleBrowserSignIn('passkey') setError('') setIsLoading(true) try { @@ -393,5 +467,6 @@ export function useLogin() { noRedirect, showRegisterOption, oidcOnly, redirectScreen, configWait, idpSlow, idpName, handleDemoLogin, handleSubmit, handlePasskeyLogin, + handleSsoClick, } } diff --git a/client/src/pages/nativeHandoff/useNativeHandoff.test.tsx b/client/src/pages/nativeHandoff/useNativeHandoff.test.tsx new file mode 100644 index 000000000..7e9e0f4f1 --- /dev/null +++ b/client/src/pages/nativeHandoff/useNativeHandoff.test.tsx @@ -0,0 +1,190 @@ +// FE-NATIVE-HANDOFF-001 to FE-NATIVE-HANDOFF-011 +import React from 'react'; +import { MemoryRouter } from 'react-router'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, renderHook, waitFor } from '../../../tests/helpers/render'; +import { resetAllStores } from '../../../tests/helpers/store'; +import { rememberHandoffReturn, requestHandoffCode, signInWithPasskey } from '../../native/browserSignIn'; +import { useAuthStore } from '../../store/authStore'; +import { useNativeHandoff } from './useNativeHandoff'; + +const mockNavigate = vi.fn(); +vi.mock('react-router', async () => { + const actual = await vi.importActual('react-router'); + return { ...actual, useNavigate: () => mockNavigate }; +}); +vi.mock('../../native/browserSignIn', () => ({ + HANDOFF_PATH: '/native-handoff', + rememberHandoffReturn: vi.fn(), + requestHandoffCode: vi.fn(), + signInWithPasskey: vi.fn(), +})); + +const challenge = 'ab'.repeat(32); +const realLocation = window.location; +const logout = vi.fn(async () => {}); + +function setSearch(search: string) { + Object.defineProperty(window, 'location', { + configurable: true, + writable: true, + value: { ...realLocation, search, href: 'http://localhost/native-handoff' + search, replace: vi.fn() }, + }); +} + +function renderHandoff() { + return renderHook(() => useNativeHandoff(), { + wrapper: ({ children }: { children: React.ReactNode }) => {children}, + }); +} + +beforeEach(() => { + resetAllStores(); + mockNavigate.mockClear(); + logout.mockClear(); + vi.mocked(requestHandoffCode).mockReset(); + sessionStorage.clear(); + setSearch(`?challenge=${challenge}`); + useAuthStore.setState({ + isLoading: false, + isAuthenticated: true, + user: { id: 1, username: 'maria' } as never, + logout, + }); +}); + +afterEach(() => { + Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation }); +}); + +describe('useNativeHandoff', () => { + it('FE-NATIVE-HANDOFF-001: is ready for a signed-in user with a valid challenge', () => { + const { result } = renderHandoff(); + expect(result.current.valid).toBe(true); + expect(result.current.ready).toBe(true); + expect(result.current.userName).toBe('maria'); + expect(mockNavigate).not.toHaveBeenCalled(); + }); + + it('FE-NATIVE-HANDOFF-002: rejects a malformed challenge and does nothing with it', () => { + setSearch('?challenge=nope'); + useAuthStore.setState({ isAuthenticated: false }); + const { result } = renderHandoff(); + expect(result.current.valid).toBe(false); + expect(result.current.ready).toBe(false); + expect(mockNavigate).not.toHaveBeenCalled(); + }); + + it('FE-NATIVE-HANDOFF-003: sends a visitor to the login page and back here afterwards', () => { + useAuthStore.setState({ isAuthenticated: false }); + renderHandoff(); + expect(mockNavigate).toHaveBeenCalledWith( + `/login?redirect=${encodeURIComponent(`/native-handoff?challenge=${challenge}`)}`, + { replace: true } + ); + }); + + it('FE-NATIVE-HANDOFF-004: starts SSO straight away when the app asked for it, without looping', () => { + setSearch(`?challenge=${challenge}&start=oidc`); + useAuthStore.setState({ isAuthenticated: false }); + renderHandoff(); + expect(window.location.replace).toHaveBeenCalledWith('/api/auth/oidc/login?remember=1'); + expect(sessionStorage.getItem('oidc_redirect')).toBe(`/native-handoff?challenge=${challenge}`); + expect(rememberHandoffReturn).toHaveBeenCalledWith(`/native-handoff?challenge=${challenge}`); + }); + + it('FE-NATIVE-HANDOFF-005: waits while the session is still being checked', () => { + useAuthStore.setState({ isAuthenticated: false, isLoading: true }); + const { result } = renderHandoff(); + expect(result.current.ready).toBe(false); + expect(mockNavigate).not.toHaveBeenCalled(); + }); + + it('FE-NATIVE-HANDOFF-006: only mints the code on the tap, then hands it to the app scheme', async () => { + vi.mocked(requestHandoffCode).mockResolvedValue('c/1'); + localStorage.setItem('trek_native_signin', String(Date.now())); + const { result } = renderHandoff(); + expect(requestHandoffCode).not.toHaveBeenCalled(); + + await act(async () => { + await result.current.openApp(); + }); + + expect(requestHandoffCode).toHaveBeenCalledWith(challenge); + expect(window.location.href).toBe('com.liketrek.trek://auth?code=c%2F1'); + // Handed back: the browser registers its service worker again from here. + expect(localStorage.getItem('trek_native_signin')).toBeNull(); + }); + + it('FE-NATIVE-HANDOFF-007: reports a failed hand-off', async () => { + vi.mocked(requestHandoffCode).mockRejectedValue(new Error('401')); + const { result } = renderHandoff(); + await act(async () => { + await result.current.openApp(); + }); + expect(result.current.status).toBe('failed'); + }); + + it('FE-NATIVE-HANDOFF-008: lets the user switch accounts and come back', async () => { + const { result } = renderHandoff(); + await act(async () => { + await result.current.switchAccount(); + }); + expect(logout).toHaveBeenCalled(); + await waitFor(() => + expect(mockNavigate).toHaveBeenCalledWith( + `/login?redirect=${encodeURIComponent(`/native-handoff?challenge=${challenge}`)}`, + { replace: true } + ) + ); + }); + + describe('when the app asked for a passkey', () => { + const loadUser = vi.fn(async () => { + useAuthStore.setState({ isAuthenticated: true }); + }); + + beforeEach(() => { + setSearch(`?challenge=${challenge}&start=passkey`); + useAuthStore.setState({ isAuthenticated: false, loadUser }); + loadUser.mockClear(); + vi.mocked(signInWithPasskey).mockReset().mockResolvedValue(); + }); + + it('FE-NATIVE-HANDOFF-009: asks for the passkey itself instead of sending the user to the login', () => { + const { result } = renderHandoff(); + expect(result.current.passkeyStep).toBe(true); + expect(mockNavigate).not.toHaveBeenCalled(); + }); + + it('FE-NATIVE-HANDOFF-010: signs in with the passkey and goes straight back to the app', async () => { + vi.mocked(requestHandoffCode).mockResolvedValue('c1'); + const { result } = renderHandoff(); + await act(async () => { + await result.current.continueWithPasskey(); + }); + expect(signInWithPasskey).toHaveBeenCalled(); + expect(loadUser).toHaveBeenCalled(); + expect(requestHandoffCode).toHaveBeenCalledWith(challenge); + expect(window.location.href).toBe('com.liketrek.trek://auth?code=c1'); + }); + + it('FE-NATIVE-HANDOFF-011: stays quiet when the prompt is dismissed and offers the full login on request', async () => { + vi.mocked(signInWithPasskey).mockRejectedValue(Object.assign(new Error('no'), { name: 'NotAllowedError' })); + const { result } = renderHandoff(); + await act(async () => { + await result.current.continueWithPasskey(); + }); + expect(result.current.status).toBe('idle'); + expect(requestHandoffCode).not.toHaveBeenCalled(); + + act(() => result.current.otherSignIn()); + await waitFor(() => + expect(mockNavigate).toHaveBeenCalledWith( + `/login?redirect=${encodeURIComponent(`/native-handoff?challenge=${challenge}`)}`, + { replace: true } + ) + ); + }); + }); +}); diff --git a/client/src/pages/nativeHandoff/useNativeHandoff.ts b/client/src/pages/nativeHandoff/useNativeHandoff.ts new file mode 100644 index 000000000..7300bbcfe --- /dev/null +++ b/client/src/pages/nativeHandoff/useNativeHandoff.ts @@ -0,0 +1,99 @@ +import { useEffect, useState } from 'react'; +import { useNavigate } from 'react-router'; +import { useShallow } from 'zustand/react/shallow'; +import { HANDOFF_PATH, rememberHandoffReturn, requestHandoffCode, signInWithPasskey } from '../../native/browserSignIn'; +import { endBrowserSignIn } from '../../native/browserSignInFlag'; +import { APP_URL_SCHEME } from '../../native/trekShell'; +import { useAuthStore } from '../../store/authStore'; + +const CHALLENGE = /^[0-9a-f]{64}$/; + +/** + * The system-browser end of the app's sign-in (see native/browserSignIn.ts). + * Signs the user in here if needed, then hands the session to the app only + * after an explicit tap: a link to this page with somebody else's challenge + * must not be able to pass a session on silently. + */ +export function useNativeHandoff() { + const navigate = useNavigate(); + const { isAuthenticated, isLoading, userName, logout, loadUser } = useAuthStore( + useShallow((s) => ({ + isAuthenticated: s.isAuthenticated, + isLoading: s.isLoading, + userName: s.user?.username ?? '', + logout: s.logout, + loadUser: s.loadUser, + })) + ); + const [params] = useState(() => new URLSearchParams(window.location.search)); + const challenge = params.get('challenge') ?? ''; + const valid = CHALLENGE.test(challenge); + const [status, setStatus] = useState<'idle' | 'sending' | 'failed'>('idle'); + // The app asked for a passkey: this page asks for it itself instead of showing + // the whole login a second time, until the user picks another way to sign in. + const [passkeyStep, setPasskeyStep] = useState(() => params.get('start') === 'passkey'); + + // Back here once signed in, without `start`, so an SSO round trip cannot loop. + const returnPath = `${HANDOFF_PATH}?challenge=${challenge}`; + + useEffect(() => { + if (!valid || isLoading || isAuthenticated || passkeyStep) return; + if (params.get('start') === 'oidc') { + sessionStorage.setItem('oidc_redirect', returnPath); + rememberHandoffReturn(returnPath); + window.location.replace('/api/auth/oidc/login?remember=1'); + return; + } + void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true }); + }, [valid, isLoading, isAuthenticated, passkeyStep, params, returnPath, navigate]); + + const openApp = async (): Promise => { + setStatus('sending'); + try { + const code = await requestHandoffCode(challenge); + endBrowserSignIn(); + window.location.href = `${APP_URL_SCHEME}://auth?code=${encodeURIComponent(code)}`; + } catch { + setStatus('failed'); + } + }; + + /** + * The passkey prompt, then straight back to the app: the tap that started it + * is the explicit consent the handoff asks for, so no second page follows. + */ + const continueWithPasskey = async (): Promise => { + setStatus('sending'); + try { + await signInWithPasskey(); + await loadUser({ silent: true }); + } catch (err: unknown) { + const name = (err as { name?: string })?.name; + setStatus(name === 'NotAllowedError' || name === 'AbortError' ? 'idle' : 'failed'); + return; + } + await openApp(); + }; + + const otherSignIn = (): void => { + setStatus('idle'); + setPasskeyStep(false); + }; + + const switchAccount = async (): Promise => { + await logout(); + void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true }); + }; + + return { + valid, + passkeyStep: valid && !isLoading && !isAuthenticated && passkeyStep, + continueWithPasskey, + otherSignIn, + ready: valid && !isLoading && isAuthenticated, + userName, + status, + openApp, + switchAccount, + }; +} diff --git a/client/src/pages/sharedTrip/SharedChrome.tsx b/client/src/pages/sharedTrip/SharedChrome.tsx index d619eade6..4d3a3c42a 100644 --- a/client/src/pages/sharedTrip/SharedChrome.tsx +++ b/client/src/pages/sharedTrip/SharedChrome.tsx @@ -80,9 +80,9 @@ export function SharedHero({ trip, stats }: HeroProps) { {dates} )} -

    {trip.title}

    +

    {trip.title}

    {trip.description && ( -

    {trip.description}

    // theme-lint-disable: white type over a photo +

    {trip.description}

    // theme-lint-disable: white type over a photo )} {stats.length > 0 && (
    diff --git a/client/src/pages/sharedTrip/SharedDayCard.test.tsx b/client/src/pages/sharedTrip/SharedDayCard.test.tsx new file mode 100644 index 000000000..3f0a3285c --- /dev/null +++ b/client/src/pages/sharedTrip/SharedDayCard.test.tsx @@ -0,0 +1,49 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { render, screen } from '../../../tests/helpers/render'; +import { SharedDayCard, type SharedDayCardProps } from './SharedDayCard'; + +/** FE-PAGE-SHARED-DAY-001: a day note's detail line on a shared trip wraps inside its card (#3082). */ + +const LONG_DETAIL = + 'Lorem Ipsum is simply dummy text of the printing and typesetting industry, https://example.com/a/very/long/unbroken/path/that/never/stops'; + +function renderDay(note: { id: number; text: string; time: string | null }) { + const props: SharedDayCardProps = { + day: { id: 9, title: 'Day One', date: '2026-07-02', day_number: 1 }, + index: 0, + selected: false, + collapsed: false, + onSelect: vi.fn(), + onToggleCollapse: vi.fn(), + items: [{ type: 'note', sortKey: 0, data: note }], + stays: [], + placeCount: 0, + stopNumber: {}, + categories: [], + }; + return render(); +} + +describe('SharedDayCard', () => { + it('FE-PAGE-SHARED-DAY-001: a long note detail wraps in its row instead of running out of a nowrap pill', () => { + renderDay({ id: 1, text: 'Test', time: LONG_DETAIL }); + + const detail = screen.getByTestId('shared-note-detail'); + expect(detail).toHaveTextContent(LONG_DETAIL); + expect(detail.className).toContain('[overflow-wrap:anywhere]'); + expect(detail.className).toContain('min-w-0'); + // Nothing between the text and the row may forbid wrapping. + let el: HTMLElement | null = screen.getByText(/Lorem Ipsum/); + for (; el && el !== document.body; el = el.parentElement) { + expect(el.className).not.toMatch(/whitespace-nowrap/); + } + }); + + it('FE-PAGE-SHARED-DAY-001: a leading HH:MM stays a time pill and the rest becomes the wrapping detail', () => { + renderDay({ id: 2, text: 'Museum', time: '08:30 meet at the north entrance' }); + + expect(screen.getByText('08:30')).toBeInTheDocument(); + expect(screen.getByTestId('shared-note-detail')).toHaveTextContent('meet at the north entrance'); + }); +}); diff --git a/client/src/pages/sharedTrip/SharedDayCard.tsx b/client/src/pages/sharedTrip/SharedDayCard.tsx index 334290d25..dc83326a8 100644 --- a/client/src/pages/sharedTrip/SharedDayCard.tsx +++ b/client/src/pages/sharedTrip/SharedDayCard.tsx @@ -7,6 +7,8 @@ import { TypeTile } from '../../components/Planner/bookings/bookingParts' import { typeInfo } from '../../components/Planner/bookings/bookingsModel' import { getNoteIcon } from '../../components/Planner/DayPlanSidebar.constants' import { noteSurface } from '../../components/Planner/noteSurface' +import { SafeMarkdown } from '../../components/shared/SafeMarkdown' +import { splitNoteTime } from '../../mobile/screens/trip/lib/dayNotes' import { useTranslation } from '../../i18n' import { useSettingsStore } from '../../store/settingsStore' import { getDisplayTimeForDay, getSpanPhase, type MergedItem } from '../../utils/dayMerge' @@ -160,7 +162,7 @@ export function PlaceRow({ place, notes, number, category }: PlaceRowProps) {
    - {place.name} + {place.name} {time && {time}}
    @@ -197,9 +199,16 @@ function TransportRow({ r, dayId }: { r: SharedTransport; dayId: number }) { ) } +/** + * A day note. Its `time` column is not a time but the note's free detail line + * (#3082): only a leading HH:MM is a real time and gets the pill, the rest is + * the owner's text and wraps under the title, rendered as the planner renders it. + * In a pill, which never wraps, a sentence ran off the edge of the card. + */ function NoteRow({ note }: { note: { id: number; text: string; time?: string | null; icon?: string | null; color?: string | null } }) { const skin = noteSurface(note.color) const Icon = getNoteIcon(note.icon) + const { time, detail } = splitNoteTime(note.time) return (
    @@ -207,7 +216,16 @@ function NoteRow({ note }: { note: { id: number; text: string; time?: string | n
    {note.text}
    - {note.time &&
    {note.time}
    } + {(time || detail) && ( +
    + {time && {time}} + {detail && ( +
    + {detail} +
    + )} +
    + )}
    ) diff --git a/client/src/pages/sharedTrip/SharedListsViews.tsx b/client/src/pages/sharedTrip/SharedListsViews.tsx index b1043d0f8..ba7499f46 100644 --- a/client/src/pages/sharedTrip/SharedListsViews.tsx +++ b/client/src/pages/sharedTrip/SharedListsViews.tsx @@ -56,7 +56,7 @@ export function SharedPackingView({ items }: { items: PackingItem[] }) { {item.checked ? : } - {item.name} + {item.name} {(item.quantity ?? 1) > 1 && ×{item.quantity}} ))} @@ -149,7 +149,7 @@ export function SharedCostsView({ items, base, tripCurrency, convert }: CostsPro return (
  • -
    {item.name}
    +
    {item.name}
    {entered &&
    {entered}
    }
    {!!item.total_price && {money(valueOf(item))}} diff --git a/client/src/pages/tripPlanner/ListsContainer.test.tsx b/client/src/pages/tripPlanner/ListsContainer.test.tsx index f0d892c5e..7a139aaa1 100644 --- a/client/src/pages/tripPlanner/ListsContainer.test.tsx +++ b/client/src/pages/tripPlanner/ListsContainer.test.tsx @@ -1,4 +1,4 @@ -// FE-PAGE-PLANNER-LISTS-001 to FE-PAGE-PLANNER-LISTS-006 +// FE-PAGE-PLANNER-LISTS-001 to FE-PAGE-PLANNER-LISTS-007 import { render, screen, fireEvent, act } from '../../../tests/helpers/render' import { resetAllStores, seedStore } from '../../../tests/helpers/store' import { buildUser, buildTrip, buildPackingItem, buildTodoItem } from '../../../tests/helpers/factories' @@ -15,8 +15,13 @@ const stub = vi.hoisted(() => (name: string) => (props: Record) }) vi.mock('../../components/Packing/PackingListPanel', () => ({ default: stub('packingPanel') })) vi.mock('../../components/Todo/TodoListPanel', () => ({ default: stub('todoPanel') })) -vi.mock('../../components/Packing/ApplyTemplateButton', () => ({ default: stub('applyTemplate') })) -vi.mock('../../components/Packing/PackingExportMenu', () => ({ default: stub('exportMenu') })) +vi.mock('../../components/Packing/PackingListsMenu', () => ({ default: stub('listsMenu') })) + +type MenuProps = { + onImport: () => void; onSaveTemplate: () => void; onClearChecked: () => void; onOpenBags: () => void + onSortChange: (s: 'manual' | 'name') => void; onHideDoneChange: (v: boolean) => void +} +const menu = () => captured.listsMenu as unknown as MenuProps /** The props a lazily loaded panel was last rendered with, once its chunk is in. */ function loaded>(name: string): Promise { @@ -42,6 +47,7 @@ function renderLists(packing = [buildPackingItem(), buildPackingItem()], todos = beforeEach(() => { resetAllStores() sessionStorage.clear() + localStorage.removeItem('trek:packing-sort') for (const key of Object.keys(captured)) delete captured[key] }) @@ -85,39 +91,52 @@ describe('ListsContainer', () => { expect(await loaded('todoPanel')).toMatchObject({ addItemSignal: 2 }) }) - it('FE-PAGE-PLANNER-LISTS-004: without the packing right there is no Add list, the other tools stay', async () => { + it('FE-PAGE-PLANNER-LISTS-004: without the packing right there is no Add list, the menu still imports', async () => { seed({ packingPermission: 'trip_owner' }) renderLists() expect(screen.queryByRole('button', { name: 'Add list' })).toBeNull() - expect(screen.getByRole('button', { name: 'Import' })).toBeInTheDocument() + expect(captured.listsMenu).toMatchObject({ canEdit: false, tripId: TRIP_ID }) await loaded('packingPanel') - fireEvent.click(screen.getByRole('button', { name: 'Import' })) + act(() => { menu().onImport() }) expect(captured.packingPanel).toMatchObject({ openImportSignal: 1, addCategorySignal: 0 }) }) it('FE-PAGE-PLANNER-LISTS-005: an admin saves a template only when the list has items', async () => { seed({ role: 'admin' }) const { unmount } = renderLists([]) - expect(screen.queryByRole('button', { name: 'Save as template' })).toBeNull() + expect(captured.listsMenu).toMatchObject({ isAdmin: true, hasItems: false }) unmount() renderLists() - fireEvent.click(screen.getByRole('button', { name: 'Save as template' })) + expect(captured.listsMenu).toMatchObject({ hasItems: true }) + act(() => { menu().onSaveTemplate() }) fireEvent.click(screen.getByRole('button', { name: 'Add list' })) expect(await loaded('packingPanel')).toMatchObject({ saveTemplateSignal: 1, addCategorySignal: 1 }) }) - it('FE-PAGE-PLANNER-LISTS-006: the panel switches the view the template and export tools work on', async () => { + it('FE-PAGE-PLANNER-LISTS-006: the panel switches the view the menu works on, and the packed count follows it', async () => { seed() - renderLists() + renderLists([buildPackingItem({ checked: 1 }), buildPackingItem({ is_private: 1, checked: 1 }), buildPackingItem({ is_private: 1 })]) const panel = await loaded<{ onViewChange: (v: string) => void }>('packingPanel') - expect(captured.applyTemplate).toMatchObject({ tripId: TRIP_ID, visibility: 'common' }) - expect(captured.exportMenu).toMatchObject({ tripId: TRIP_ID, view: 'common' }) + expect(captured.listsMenu).toMatchObject({ tripId: TRIP_ID, view: 'common', packedCount: 1 }) act(() => { panel.onViewChange('personal') }) - expect(captured.applyTemplate).toMatchObject({ visibility: 'personal' }) - expect(captured.exportMenu).toMatchObject({ view: 'personal' }) + expect(captured.listsMenu).toMatchObject({ view: 'personal', packedCount: 1 }) expect(captured.packingPanel).toMatchObject({ view: 'personal' }) }) + + it('FE-PAGE-PLANNER-LISTS-007: order, hiding packed items, the clean-up and the bags reach the panel from the menu', async () => { + seed() + renderLists() + await loaded('packingPanel') + expect(captured.packingPanel).toMatchObject({ sort: 'manual', hideDone: false, clearCheckedSignal: 0, openBagsSignal: 0 }) + + act(() => { menu().onSortChange('name') }) + act(() => { menu().onHideDoneChange(true) }) + act(() => { menu().onClearChecked() }) + act(() => { menu().onOpenBags() }) + expect(captured.packingPanel).toMatchObject({ sort: 'name', hideDone: true, clearCheckedSignal: 1, openBagsSignal: 1 }) + expect(localStorage.getItem('trek:packing-sort')).toBe('name') + }) }) diff --git a/client/src/pages/tripPlanner/ListsContainer.tsx b/client/src/pages/tripPlanner/ListsContainer.tsx index 80cba31eb..a05c7562a 100644 --- a/client/src/pages/tripPlanner/ListsContainer.tsx +++ b/client/src/pages/tripPlanner/ListsContainer.tsx @@ -1,7 +1,8 @@ import React, { useState } from 'react' -import { PackageCheck, ListTodo, ListPlus, Download, Plus, FolderPlus } from 'lucide-react' -import ApplyTemplateButton from '../../components/Packing/ApplyTemplateButton' -import PackingExportMenu from '../../components/Packing/PackingExportMenu' +import { PackageCheck, ListTodo, ListPlus, Plus } from 'lucide-react' +import PackingListsMenu from '../../components/Packing/PackingListsMenu' +import { usePackingSortPreference } from '../../components/Packing/usePackingListPanel' +import { packingProgress, packingViewItems } from '../../components/Packing/packingListModel' import { useTranslation } from '../../i18n' import { useAuthStore } from '../../store/authStore' import { useTripStore } from '../../store/tripStore' @@ -18,6 +19,12 @@ export function ListsContainer({ tripId, packingItems, todoItems }: Readonly<{ t const [saveTemplateSignal, setSaveTemplateSignal] = useState(0) const [addTodoSignal, setAddTodoSignal] = useState(0) const [packingView, setPackingView] = useState<'common' | 'personal'>('common') + // The Lists menu sets these; the panel below reads them. + const [packingSort, setPackingSort] = usePackingSortPreference() + const [hideDone, setHideDone] = useState(false) + const [clearCheckedSignal, setClearCheckedSignal] = useState(0) + const [openBagsSignal, setOpenBagsSignal] = useState(0) + const packedInView = packingProgress(packingViewItems(packingItems, packingView)).checked const { t } = useTranslation() const isAdmin = useAuthStore(s => s.user?.role === 'admin') const trip = useTripStore(s => s.trip) @@ -71,48 +78,29 @@ export function ListsContainer({ tripId, packingItems, todoItems }: Readonly<{ t
  • {subTab === 'packing' && (() => { - const sharedBtnClass = 'inline-flex items-center gap-1.5 px-2.5 sm:px-[14px] py-[7px] sm:py-[9px] hover:opacity-[0.88]' - // Export and Import carry only their icon, with the name as tooltip and label. - const iconBtnClass = 'inline-flex items-center justify-center px-2.5 py-[7px] sm:py-[9px] hover:opacity-[0.88] bg-accent text-accent-text' - const sharedBtnStyle: React.CSSProperties = { + const btnClass = 'inline-flex items-center gap-1.5 px-2.5 sm:px-[14px] py-[7px] sm:py-[9px] hover:opacity-[0.88] bg-accent text-accent-text' + const btnStyle: React.CSSProperties = { appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', borderRadius: 10, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, } + // One button for what is done often, everything else in the menu beside it. return ( -
    +
    {canEditPacking && ( - )} - 0} packedCount={packedInView} + sort={packingSort} onSortChange={setPackingSort} hideDone={hideDone} onHideDoneChange={setHideDone} + onImport={() => setImportPackingSignal(s => s + 1)} onSaveTemplate={() => setSaveTemplateSignal(s => s + 1)} + onClearChecked={() => setClearCheckedSignal(s => s + 1)} onOpenBags={() => setOpenBagsSignal(s => s + 1)} + buttonClassName="inline-flex items-center justify-center px-2.5 py-[7px] sm:py-[9px] hover:opacity-[0.88] bg-accent text-accent-text" + buttonStyle={btnStyle} /> - {isAdmin && packingItems.length > 0 && ( - - )} - -
    ) })()} @@ -136,7 +124,8 @@ export function ListsContainer({ tripId, packingItems, todoItems }: Readonly<{ t
    {subTab === 'packing' && ( - + )} {subTab === 'todo' && ( diff --git a/client/src/pages/tripPlanner/PlanMapStage.tsx b/client/src/pages/tripPlanner/PlanMapStage.tsx index 828a4bbd2..026320d10 100644 --- a/client/src/pages/tripPlanner/PlanMapStage.tsx +++ b/client/src/pages/tripPlanner/PlanMapStage.tsx @@ -47,6 +47,8 @@ interface StagePageLocals { poiPillEnabled: boolean mapPois: Poi[] distanceUnit: Settings['distance_unit'] + /** The open place card's measured height, so the selected pin is panned above it. */ + inspectorHeight?: number } export interface PlanMapStageProps @@ -73,7 +75,7 @@ export function PlanMapStage({ dawarichEnabled, dawarichTrail, dawarichHiddenDates, dawarichTrailShown, toggleDawarichTrail, mobileSidebarOpen, showPlaceForm, showMembersModal, showReservationModal, poi, tourMap, leftPanelPx, rightPanelPx, mapInsetLeft, mapInsetRight, - glMap, setGlMap, poiPillEnabled, mapPois, distanceUnit, + glMap, setGlMap, poiPillEnabled, mapPois, distanceUnit, inspectorHeight = 0, }: Readonly): ReactElement { // ACT-02: a tour compared with its actual track lays the track into the day's lines, dotted. const compared = useActivityCompareMap({ @@ -115,6 +117,7 @@ export function PlanMapStage({ leftWidth={leftPanelPx} rightWidth={rightPanelPx} hasInspector={!!selectedPlace} + inspectorHeight={selectedPlace ? inspectorHeight : 0} hasDayDetail={!!showDayDetail && !selectedPlace} reservations={reservations} showReservationStats={true} diff --git a/client/src/pages/tripPlanner/b4a-wiring.test.ts b/client/src/pages/tripPlanner/b4a-wiring.test.ts index 298f1163d..7098c8f08 100644 --- a/client/src/pages/tripPlanner/b4a-wiring.test.ts +++ b/client/src/pages/tripPlanner/b4a-wiring.test.ts @@ -91,19 +91,24 @@ test('B4A Core testability debt: verify source without importing the page, hook, assert.equal(collect(self, node => ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword).length, 0) }) -test('B4A Tours tab is readable, desktop-only, and absent with addon OFF', () => { +test('B4A Tours tab is readable, desktop-only off a large screen, and absent with addon OFF', () => { const tabs = initializer(hook, 'TRIP_TABS') const branches = collect(tabs, node => ts.isConditionalExpression(node) && node.whenTrue.getText(hook).includes("id: 'tour-planner'")) assert.equal(branches.length, 1) const branch = branches[0] assert.ok(ts.isConditionalExpression(branch)) - assert.equal(branch.condition.getText(hook), 'enabledAddons.tours && !isMobile') + // Where the tab exists and whether the touch shell offers it: tourPlannerTabOf (tripPlannerModel.test.ts). + assert.equal(branch.condition.getText(hook), 'tourTab') + assert.equal(initializer(hook, 'tourTab').getText(hook), 'tourPlannerTabOf(!!enabledAddons.tours, isMobile, largeTouch)') assert.equal(branch.whenFalse.getText(hook), '[]') - assert.match(branch.whenTrue.getText(hook), /desktopOnly: true/) + assert.match(branch.whenTrue.getText(hook), /desktopOnly: tourTab\.desktopOnly/) assert.doesNotMatch(tabs.getText(hook), /\bcan\b|canPlaceEdit|canDayEdit/) assert.match(hookText, /!validTabIds\.includes\(activeTab\)[\s\S]*?setActiveTab\('plan'\)/) assert.match(pageText, /activeTab === 'tour-planner' && enabledAddons\.tours && !isMobile/) + // The app counts as a phone shell on an iPad too: the workspace follows its tab, not the phone test. + assert.equal(initializer(workspace, 'workspaceUp').getText(workspace), "activeTab === 'tour-planner' && (!isMobile || largeTouch)") + assert.doesNotMatch(workspaceText, /!isMobile(?! \|\| largeTouch)/) }) test('B4A selectedTour is derived only from explicit place selection and addon state', () => { @@ -135,16 +140,21 @@ test('B4A desktop page delegates Tours state and permissions to its page hook', const mobileFiles = mobileSourceFiles(resolve(process.cwd(), 'src/mobile')) for (const file of mobileFiles) { const mobileSource = parse(file, readFileSync(file, 'utf8')) + // The touch shell holds its own planner: it may build the page's state over that + // one (useTripPlannerPageOf), never a second planner through useTripPlannerPage. const importsDesktopHook = collect(mobileSource, ts.isImportDeclaration).some(node => { if (!ts.isImportDeclaration(node) || !ts.isStringLiteral(node.moduleSpecifier)) return false - const modulePath = node.moduleSpecifier.text - const namedImport = node.importClause?.namedBindings - return /(?:^|\/)useTripPlannerPage(?:\.tsx?)?$/.test(modulePath) - || (namedImport && ts.isNamedImports(namedImport) - && namedImport.elements.some(element => element.name.text === 'useTripPlannerPage')) + const fromPageModule = /(?:^|\/)useTripPlannerPage(?:\.tsx?)?$/.test(node.moduleSpecifier.text) + const clause = node.importClause + const namedImport = clause?.namedBindings + if (fromPageModule && (clause?.name || (namedImport && ts.isNamespaceImport(namedImport)))) return true + return !!(namedImport && ts.isNamedImports(namedImport) + && namedImport.elements.some(element => (element.propertyName ?? element.name).text === 'useTripPlannerPage')) }) assert.equal(importsDesktopHook, false, file) } + // And the desktop's own hook is that same state over a planner of its own. + assert.match(pageControllerText, /return useTripPlannerPageOf\(useTripPlanner\(\)\)/) const permissions = initializer(pageController, 'canPlaceEdit') const permissionCalls = collect(pageController, node => ts.isCallExpression(node) diff --git a/client/src/pages/tripPlanner/placeUndo.ts b/client/src/pages/tripPlanner/placeUndo.ts index e645ebe1f..4475ef8a2 100644 --- a/client/src/pages/tripPlanner/placeUndo.ts +++ b/client/src/pages/tripPlanner/placeUndo.ts @@ -87,6 +87,8 @@ export interface PlaceVisit { endTime: string | null; notes: string | null; endDay: boolean; + /** The visit's own stay (#3092), or null where it read the place's. */ + stayMinutes: number | null; routeExcluded: boolean; legMode: string | null; incomingLegMode: string | null; @@ -103,6 +105,7 @@ export function visitOf(dayId: number, a: Assignment): PlaceVisit { endTime: a.assignment_end_time ?? null, notes: a.notes ?? null, endDay: a.end_day === true, + stayMinutes: a.stay_minutes ?? null, routeExcluded: a.route_excluded === true, legMode: a.leg_transport_mode ?? null, incomingLegMode: a.incoming_leg_transport_mode ?? null, @@ -123,6 +126,7 @@ export type RestoreActions = Pick< | 'setAssignmentTimes' | 'setAssignmentNotes' | 'setAssignmentEndDay' + | 'setAssignmentStay' | 'setAssignmentRouteExcluded' | 'setAssignmentParticipants' | 'setAssignmentLegMode' @@ -153,7 +157,7 @@ export async function restorePlace( return restored; } -/** Gives a visit planned again the times, note, end of day, travellers and legs it had. */ +/** Gives a visit planned again the times, note, end of day, stay, travellers and legs it had. */ export async function restoreVisit( tripId: number | string, actions: Omit, @@ -166,6 +170,7 @@ export async function restoreVisit( } if (visit.notes) await actions.setAssignmentNotes(tripId, dayId, assignmentId, visit.notes); if (visit.endDay) await actions.setAssignmentEndDay(tripId, dayId, assignmentId, true); + if (visit.stayMinutes !== null) await actions.setAssignmentStay(tripId, dayId, assignmentId, visit.stayMinutes); if (visit.routeExcluded) await actions.setAssignmentRouteExcluded(tripId, dayId, assignmentId, true); if (visit.participantIds.length > 0) await actions.setAssignmentParticipants(tripId, dayId, assignmentId, visit.participantIds); diff --git a/client/src/pages/tripPlanner/tripPlannerModel.test.ts b/client/src/pages/tripPlanner/tripPlannerModel.test.ts index 7bebe088b..dc79678a5 100644 --- a/client/src/pages/tripPlanner/tripPlannerModel.test.ts +++ b/client/src/pages/tripPlanner/tripPlannerModel.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { placesForDays, resolvePoolAssignmentId } from './tripPlannerModel' +import { placesForDays, resolvePoolAssignmentId, tourPlannerTabOf } from './tripPlannerModel' import { buildAssignment, buildPlace } from '../../../tests/helpers/factories' describe('resolvePoolAssignmentId', () => { @@ -55,3 +55,19 @@ describe('placesForDays', () => { expect(kept.map(p => p.id)).toEqual([1, 2, 4, 5]) }) }) + +describe('tourPlannerTabOf', () => { + it('offers the editor on the desktop, as a desktop-only tab', () => { + expect(tourPlannerTabOf(true, false, false)).toEqual({ desktopOnly: true }) + }) + + it('offers it in the touch shell of a large screen, where the rail shows it', () => { + expect(tourPlannerTabOf(true, true, true)).toEqual({ desktopOnly: false }) + }) + + it('offers no tab on a phone, nor anywhere while the addon is off', () => { + expect(tourPlannerTabOf(true, true, false)).toBeNull() + expect(tourPlannerTabOf(false, false, false)).toBeNull() + expect(tourPlannerTabOf(false, true, true)).toBeNull() + }) +}) diff --git a/client/src/pages/tripPlanner/tripPlannerModel.ts b/client/src/pages/tripPlanner/tripPlannerModel.ts index 6f49ab4ea..cb3fd13a4 100644 --- a/client/src/pages/tripPlanner/tripPlannerModel.ts +++ b/client/src/pages/tripPlanner/tripPlannerModel.ts @@ -56,3 +56,14 @@ export function resolvePoolAssignmentId( .filter((a) => a.place?.id === placeId) return matches.length === 1 ? matches[0].id : null } + +/** + * Where the tour editor is a tab of the trip: always on the desktop, and in the + * touch shell only on a large screen (an iPad, an unfolded foldable), where it is + * offered in the rail. A phone has no such tab and keeps its tours in the places + * browser. Null while the addon is off or on a phone. + */ +export function tourPlannerTabOf(toursOn: boolean, touchShell: boolean, largeScreen: boolean): { desktopOnly: boolean } | null { + if (!toursOn || (touchShell && !largeScreen)) return null + return { desktopOnly: !largeScreen } +} diff --git a/client/src/pages/tripPlanner/useAssistantDeepLink.test.ts b/client/src/pages/tripPlanner/useAssistantDeepLink.test.ts index 8e4013b4d..f2d574b9f 100644 --- a/client/src/pages/tripPlanner/useAssistantDeepLink.test.ts +++ b/client/src/pages/tripPlanner/useAssistantDeepLink.test.ts @@ -65,10 +65,11 @@ describe('useAssistantTabLink', () => { const searchParams = new URLSearchParams(query); const setSearchParams = vi.fn((update: (params: URLSearchParams) => URLSearchParams) => update(searchParams)); const selectTab = vi.fn(); + const onLinked = vi.fn(); renderHook(() => - useAssistantTabLink({ searchParams, setSearchParams: setSearchParams as never, activeTab, selectTab }) + useAssistantTabLink({ searchParams, setSearchParams: setSearchParams as never, activeTab, selectTab, onLinked }) ); - return { searchParams, setSearchParams, selectTab }; + return { searchParams, setSearchParams, selectTab, onLinked }; } it('FE-PLANNER-ASSISTLINK-005: a ?tab= the chat opens while the planner is open switches the tab, once', () => { @@ -79,13 +80,20 @@ describe('useAssistantTabLink', () => { expect(searchParams.get('expense')).toBe('7'); }); - it('FE-PLANNER-ASSISTLINK-006: the tab on screen is not switched again; a tab it cannot open is left alone', () => { + it('FE-PLANNER-ASSISTLINK-006: the tab on screen is not switched again; a tab it cannot open is dropped from the URL', () => { const same = setupTab('tab=finanzplan', 'finanzplan'); expect(same.selectTab).not.toHaveBeenCalled(); expect(same.searchParams.has('tab')).toBe(false); - const unknown = setupTab('tab=nowhere', 'plan'); + const unknown = setupTab('tab=nowhere&place=3', 'plan'); expect(unknown.selectTab).not.toHaveBeenCalled(); - expect(unknown.setSearchParams).not.toHaveBeenCalled(); + expect(unknown.onLinked).not.toHaveBeenCalled(); + expect(unknown.searchParams.has('tab')).toBe(false); + expect(unknown.searchParams.get('place')).toBe('3'); + }); + + it('FE-PLANNER-ASSISTLINK-007: every link it takes is reported, also one to the tab already on screen', () => { + expect(setupTab('tab=collab', 'plan').onLinked).toHaveBeenCalledWith('collab'); + expect(setupTab('tab=collab', 'collab').onLinked).toHaveBeenCalledWith('collab'); }); }); diff --git a/client/src/pages/tripPlanner/useAssistantDeepLink.ts b/client/src/pages/tripPlanner/useAssistantDeepLink.ts index 46187dde6..1ef0f1011 100644 --- a/client/src/pages/tripPlanner/useAssistantDeepLink.ts +++ b/client/src/pages/tripPlanner/useAssistantDeepLink.ts @@ -59,27 +59,33 @@ interface AssistantTabLinkOptions { activeTab: string; /** Switches the planner's tab the way its tab bar does. */ selectTab: (tabId: string) => void; + /** Told about every link it took, so a shell can open the part of the tab a link means. */ + onLinked?: (tabId: string) => void; } /** - * `?tab=` while the planner is already open: what a card in the chat - * opens in another tab of this trip (`?tab=finanzplan&expense=7`). The - * planner reads the tab once when it opens; this takes a later one live, - * once, and then drops it from the URL. What the tab reads beside it stays - * for that tab to take. + * `?tab=` from a notification or a card in the chat, including while the + * planner is already open. Both desktop and mobile take the requested tab + * once and then drop it from the URL. A tab the planner does not have is + * dropped too, so it does not linger in the address bar. What the tab reads + * beside it stays for that tab to take (`?tab=finanzplan&expense=7`, for example). */ export function useAssistantTabLink({ searchParams, setSearchParams, activeTab, selectTab, + onLinked, }: AssistantTabLinkOptions): void { const requested = searchParams.get('tab'); const linkable = requested !== null && isDeepLinkableTripTab(requested); useEffect(() => { - if (!linkable || requested === null) return; - if (requested !== activeTab) selectTab(requested); + if (requested === null) return; + if (linkable) { + if (requested !== activeTab) selectTab(requested); + onLinked?.(requested); + } setSearchParams( (params) => { params.delete('tab'); @@ -87,5 +93,5 @@ export function useAssistantTabLink({ }, { replace: true } ); - }, [linkable, requested, activeTab, selectTab, setSearchParams]); + }, [linkable, requested, activeTab, selectTab, onLinked, setSearchParams]); } diff --git a/client/src/pages/tripPlanner/useAssistantEntityLinks.test.tsx b/client/src/pages/tripPlanner/useAssistantEntityLinks.test.tsx index f6b02b1b5..2c3c2df41 100644 --- a/client/src/pages/tripPlanner/useAssistantEntityLinks.test.tsx +++ b/client/src/pages/tripPlanner/useAssistantEntityLinks.test.tsx @@ -1,8 +1,7 @@ /** * FE-PLANNER-ENTITYLINK-001 to FE-PLANNER-ENTITYLINK-002 * - * The links the chat opens the planner with while it is on screen: another - * tab of the trip switches there and leaves the URL, and the parts' own links + * The links the chat opens the planner with while it is on screen: the parts' own links * (tours, bookings, road trip) are each handed the planner, the workspace and * the query (each part's own test covers what it does with them). */ @@ -37,10 +36,10 @@ function setup(path: string) { } describe('useAssistantEntityLinks', () => { - it('FE-PLANNER-ENTITYLINK-001: another tab switches there and leaves the URL, what it reads stays', () => { + it('FE-PLANNER-ENTITYLINK-001: leaves tab selection to the shared planner', () => { const { planner, hook } = setup('/trips/5?tab=finanzplan&expense=7'); - expect(planner.handleTabChange).toHaveBeenCalledWith('finanzplan'); - expect(hook.result.current.search).toBe('?expense=7'); + expect(planner.handleTabChange).not.toHaveBeenCalled(); + expect(hook.result.current.search).toBe('?tab=finanzplan&expense=7'); }); it("FE-PLANNER-ENTITYLINK-002: each part's own link gets the planner, the workspace and the query; nothing switches without a tab", () => { diff --git a/client/src/pages/tripPlanner/useAssistantEntityLinks.ts b/client/src/pages/tripPlanner/useAssistantEntityLinks.ts index 50a144c4a..a04700600 100644 --- a/client/src/pages/tripPlanner/useAssistantEntityLinks.ts +++ b/client/src/pages/tripPlanner/useAssistantEntityLinks.ts @@ -3,7 +3,6 @@ import { useSearchParams } from 'react-router'; import { useBookingDeepLink } from './deepLinks/useBookingDeepLink'; import { useRoadtripDeepLink } from './deepLinks/useRoadtripDeepLink'; import { useTourDeepLink } from './deepLinks/useTourDeepLink'; -import { useAssistantTabLink } from './useAssistantDeepLink'; import type { useTourWorkspace } from './useTourWorkspace'; import type { useTripPlanner } from './useTripPlanner'; @@ -14,18 +13,12 @@ interface AssistantEntityLinkOptions { /** * The links the chat opens the planner with while it is already on screen: - * another tab of the trip (`?tab=`), and what each part of TREK opens in its - * own tab (a tour, a booking, a stop of the road trip). Each is taken once - * and then leaves the URL. + * what each part of TREK opens in its own tab (a tour, a booking, a stop of + * the road trip). Each is taken once and then leaves the URL. The shared + * planner handles `?tab=` for both desktop and mobile. */ export function useAssistantEntityLinks({ planner, workspace }: AssistantEntityLinkOptions): void { const [searchParams, setSearchParams] = useSearchParams(); - useAssistantTabLink({ - searchParams, - setSearchParams, - activeTab: planner.activeTab, - selectTab: planner.handleTabChange, - }); const links = { planner, workspace, searchParams, setSearchParams }; useTourDeepLink(links); useBookingDeepLink(links); diff --git a/client/src/pages/tripPlanner/useDayPlanEdits.ts b/client/src/pages/tripPlanner/useDayPlanEdits.ts index 64b4efc53..bb3265eae 100644 --- a/client/src/pages/tripPlanner/useDayPlanEdits.ts +++ b/client/src/pages/tripPlanner/useDayPlanEdits.ts @@ -6,6 +6,7 @@ import { useTripStore, type TripStoreState } from '../../store/tripStore' import { isEffectivelyOffline } from '../../sync/networkMode' import type { Accommodation, Place } from '../../types' import { timedSlot } from '../../utils/dayMerge' +import { withHiddenRows } from '../../utils/mergedOrder' import { restoreVisit, visitOf } from './placeUndo' import type { PlannerBase, PlannerHistory } from './plannerTypes' import type { PlaceEdits } from './usePlaceEdits' @@ -142,9 +143,7 @@ export function useDayPlanEdits(options: DayPlanEditsOptions) { // pinned behind instead of being shifted arithmetically. Without this the // day's detours stayed on their old numbers and the drive quietly took a // different road, persisted and visible to every collaborator. - const visible = new Set(orderedIds) - let nextVisible = 0 - const completeOrder = prevIds.map(id => visible.has(id) ? orderedIds[nextVisible++] : id) + const completeOrder = withHiddenRows(prevIds, orderedIds) const stopIdsBefore = roadtripStopsOf(dayId).map(a => a.id) const stopIdsAfter = completeOrder.filter(id => stopIdsBefore.includes(id)) const plan = reanchorByStopOrder(roadtripVias.byDay[dayId] ?? [], stopIdsBefore, stopIdsAfter) diff --git a/client/src/pages/tripPlanner/usePlaceFormOpeners.ts b/client/src/pages/tripPlanner/usePlaceFormOpeners.ts index 170eb2374..08148e46c 100644 --- a/client/src/pages/tripPlanner/usePlaceFormOpeners.ts +++ b/client/src/pages/tripPlanner/usePlaceFormOpeners.ts @@ -306,7 +306,7 @@ export function usePlaceFormOpeners(options: PlaceFormOpenersOptions) { setStopDraft({ poi: { osm_id: place.osm_id ?? '', name: place.name, lat: place.lat, lng: place.lng, category, poi_type: category, address: place.address ?? null, website: place.website ?? null, phone: place.phone ?? null, opening_hours: null, cuisine: null, source: 'trek', offRouteKm: 0, alongKm: 0 }, arrivalTime, dayId, dayNumber: days.find(day => day.id === dayId)?.day_number ?? 0, position: visit.order_index ?? 0, - editing: { placeId: place.id, stopType: place.stop_type ?? (stay ? 'hotel' : null), dwellMinutes: place.duration_minutes ?? 30, accommodationId: stay?.id, checkIn: stay?.check_in ?? '', checkOut: stay?.check_out ?? '' }, + editing: { placeId: place.id, assignmentId: visit.id, stopType: place.stop_type ?? (stay ? 'hotel' : null), dwellMinutes: visit.stay_minutes ?? place.duration_minutes ?? 30, accommodationId: stay?.id, checkIn: stay?.check_in ?? '', checkOut: stay?.check_out ?? '' }, ...(isOvernightCategory(category) ? { overnight: { ...overnightOptions(dayId), ...(stay ? { defaultEndDayId: stay.end_day_id } : {}) } } : {}), }) return diff --git a/client/src/pages/tripPlanner/usePlannerDialogs.test.ts b/client/src/pages/tripPlanner/usePlannerDialogs.test.ts index 696702641..98e8e973a 100644 --- a/client/src/pages/tripPlanner/usePlannerDialogs.test.ts +++ b/client/src/pages/tripPlanner/usePlannerDialogs.test.ts @@ -1,4 +1,4 @@ -// FE-TP-DIALOGS-001 to FE-TP-DIALOGS-012 +// FE-TP-DIALOGS-001 to FE-TP-DIALOGS-013 // // The planner's dialogs and the URL intents that open them, driven straight through // usePlannerDialogs. The search params come in as options, so each test owns the URL @@ -136,13 +136,12 @@ describe('usePlannerDialogs', () => { expect(url.get('create')).toBe('expense') }) - it('FE-TP-DIALOGS-006: ?tab= is dropped from the URL once the planner has read it', () => { + it('FE-TP-DIALOGS-006: leaves ?tab= for the shared planner to handle', () => { url = new URLSearchParams('tab=dateien&keep=1') const { result } = renderDialogs({ searchParams: url }) - expect(setSearchParams).toHaveBeenCalledTimes(1) - expect(setSearchParams.mock.calls[0][1]).toEqual({ replace: true }) - expect(url.toString()).toBe('keep=1') + expect(setSearchParams).not.toHaveBeenCalled() + expect(url.toString()).toBe('tab=dateien&keep=1') expect(result.current.showPlaceForm).toBe(false) }) diff --git a/client/src/pages/tripPlanner/usePlannerDialogs.ts b/client/src/pages/tripPlanner/usePlannerDialogs.ts index bdb2840a1..00ffed539 100644 --- a/client/src/pages/tripPlanner/usePlannerDialogs.ts +++ b/client/src/pages/tripPlanner/usePlannerDialogs.ts @@ -19,9 +19,7 @@ interface PlannerDialogsOptions extends Pick { - if (searchParams.get('tab') === null) return - setSearchParams(p => { p.delete('tab'); return p }, { replace: true }) - }, [searchParams]) const [showTripForm, setShowTripForm] = useState(false) const [showMembersModal, setShowMembersModal] = useState(false) const [showReservationModal, setShowReservationModal] = useState(false) diff --git a/client/src/pages/tripPlanner/usePlannerMapView.ts b/client/src/pages/tripPlanner/usePlannerMapView.ts index dbd2ab107..13f613f27 100644 --- a/client/src/pages/tripPlanner/usePlannerMapView.ts +++ b/client/src/pages/tripPlanner/usePlannerMapView.ts @@ -4,6 +4,7 @@ import { usePlannerTripView } from './usePlannerTripView' import type { TripStoreState } from '../../store/tripStore' import type { Place } from '../../types' import type { PlannerBase } from './plannerTypes' +import { useMapLock } from '../../hooks/useMapLock' interface PlannerMapViewOptions extends Pick { places: Place[] @@ -60,20 +61,11 @@ export function usePlannerMapView(options: PlannerMapViewOptions) { // A locked map stays where the traveller put it (#2010): picking a day or a place no // longer zooms or pans it. Remembered per browser, like the other view toggles; the // first frame of a trip still fits, or the map would open on nothing. - const [mapLocked, setMapLocked] = useState(() => { - try { return localStorage.getItem('trek:map-locked') === '1' } catch { return false } - }) + const [mapLocked, toggleMapLocked] = useMapLock() const mapLockedRef = useRef(mapLocked) mapLockedRef.current = mapLocked const isMobileRef = useRef(isMobile) isMobileRef.current = isMobile - const toggleMapLocked = useCallback(() => { - setMapLocked(prev => { - const next = !prev - try { localStorage.setItem('trek:map-locked', next ? '1' : '0') } catch { /* private mode keeps it for the session */ } - return next - }) - }, []) // The recorded route from Dawarich (#2279), per trip and remembered on the // account for the same reason as the overview above: it answers "what // actually happened on this trip", a question about one trip rather than a diff --git a/client/src/pages/tripPlanner/useRoadtripStopEdits.test.ts b/client/src/pages/tripPlanner/useRoadtripStopEdits.test.ts index daa376498..65a81cd0f 100644 --- a/client/src/pages/tripPlanner/useRoadtripStopEdits.test.ts +++ b/client/src/pages/tripPlanner/useRoadtripStopEdits.test.ts @@ -1,4 +1,4 @@ -// FE-TP-STOPEDITS-001 to FE-TP-STOPEDITS-016 +// FE-TP-STOPEDITS-001 to FE-TP-STOPEDITS-018 // // Edits to one stop on the drive, driven straight through useRoadtripStopEdits. The // stop popup's draft and the stay release question are real state in the harness, so @@ -8,6 +8,7 @@ import { act, renderHook } from '@testing-library/react' import { accommodationsApi } from '../../api/client' import type { RoadtripStopDraft } from '../../components/Roadtrip/RoadtripStopPopup' import { reanchorAfterInsert, reanchorAfterRemove, reanchorAfterReorder } from '../../components/Roadtrip/roadtripModel' +import { stayOf } from '../../components/Roadtrip/stayReading' import type { CorridorPoi } from '../../components/Roadtrip/useCorridorPois' import type { RoadtripStop } from '../../components/Roadtrip/useRoadtripRoutes' import { useTripStore, type TripStoreState } from '../../store/tripStore' @@ -17,6 +18,7 @@ import type { Accommodation, AssignmentsMap } from '../../types' import type { Can, Translate } from './plannerTypes' import type { PlannerDialogs } from './usePlannerDialogs' import type { RoadtripFeed } from './useRoadtripFeed' +import { assignmentRepo } from '../../repo/assignmentRepo' import { useRoadtripStopEdits } from './useRoadtripStopEdits' type Options = Parameters[0] @@ -485,4 +487,47 @@ describe('useRoadtripStopEdits', () => { 'common.unknownError', 'common.unknownError', ]) }) + + // #3092: the same place planned twice on a day, once to stop and once only to steer the + // route past it. The stay belongs to the visit, so changing one leaves the other alone. + describe('a stay per visit', () => { + const viewpoint = buildPlace({ id: 70, lat: 50, lng: 13, duration_minutes: 45 }) + const twice: AssignmentsMap = { + 5: [ + buildAssignment({ id: 51, day_id: 5, place: viewpoint, place_id: 70, order_index: 0 }), + buildAssignment({ id: 52, day_id: 5, place: viewpoint, place_id: 70, order_index: 1 }), + ], + } + const seed = () => { + useTripStore.setState({ assignments: twice }) + vi.spyOn(assignmentRepo, 'setStay').mockImplementation(async (_tripId, visit, minutes) => ({ ...visit, stay_minutes: minutes })) + return { ...useTripStore.getState(), ...actions, setAssignmentStay: useTripStore.getState().setAssignmentStay } as unknown as TripStoreState + } + + it('FE-TP-STOPEDITS-017: the stay dialog changes one visit of a place and leaves the other visit of it alone', async () => { + const tripActions = seed() + const { result } = renderEdits(null, { tripActions, assignments: twice }) + + await act(async () => { await result.current.setRoadtripStay(70, 0, 52) }) + + expect(actions.updatePlace).not.toHaveBeenCalled() + expect(assignmentRepo.setStay).toHaveBeenCalledWith(42, expect.objectContaining({ id: 52 }), 0) + const [first, second] = useTripStore.getState().assignments['5'] + expect(stayOf(first)).toBe(45) + expect(stayOf(second)).toBe(0) + }) + + it('FE-TP-STOPEDITS-018: the stop popup writes the kind on the place and the stay on the visit it was opened on', async () => { + const tripActions = seed() + const editing = { placeId: 70, assignmentId: 51, dwellMinutes: 45, stopType: null } + const { result } = renderEdits({ poi: hit(), dayId: 5, position: 0, dayNumber: 5, editing }, { tripActions, assignments: twice }) + + await act(async () => { await result.current.saveStopDraft({ stopType: 'rest_area', dwellMinutes: 90 }) }) + + expect(actions.updatePlace).toHaveBeenCalledWith(42, 70, { stop_type: 'rest_area' }) + const [first, second] = useTripStore.getState().assignments['5'] + expect(stayOf(first)).toBe(90) + expect(stayOf(second)).toBe(45) + }) + }) }) diff --git a/client/src/pages/tripPlanner/useRoadtripStopEdits.ts b/client/src/pages/tripPlanner/useRoadtripStopEdits.ts index eb2a6d572..d153e2915 100644 --- a/client/src/pages/tripPlanner/useRoadtripStopEdits.ts +++ b/client/src/pages/tripPlanner/useRoadtripStopEdits.ts @@ -24,6 +24,40 @@ interface RoadtripStopEditsOptions updateRouteForDay: ReturnType['updateRouteForDay'] } +/** + * The day a saved visit is stored on, or null for none: no visit named, the optimistic + * row of one still being saved (a negative id the server never issued), or one no longer + * planned. A stay is written onto such a visit (#3092); without one it falls back to the + * place. + */ +function savedVisitDayOf(assignments: TripStoreState['assignments'], assignmentId: number | undefined): number | null { + if (assignmentId == null || assignmentId <= 0) return null + const day = Object.entries(assignments).find(([, visits]) => visits.some(visit => visit.id === assignmentId)) + return day ? Number(day[0]) : null +} + +/** + * Saves the stop popup over a stop already on the drive. The kind is the place's, the stay + * the visit's (#3092): a place planned twice keeps a stay per visit, so the popup on one + * of them leaves the other one's alone. A stop with no saved visit writes both onto the + * place, as before. + */ +async function writeEditedStop( + tripActions: TripStoreState, + tripId: PlannerBase['tripId'], + assignments: TripStoreState['assignments'], + { placeId, assignmentId }: { placeId: number; assignmentId?: number }, + { stopType, dwellMinutes }: { stopType: RoadtripStopType | null; dwellMinutes: number }, +): Promise { + const visitDayId = savedVisitDayOf(assignments, assignmentId) + if (assignmentId == null || visitDayId === null) { + await tripActions.updatePlace(tripId, placeId, { stop_type: stopType, duration_minutes: dwellMinutes }) + return + } + await tripActions.updatePlace(tripId, placeId, { stop_type: stopType }) + await tripActions.setAssignmentStay(tripId, visitDayId, assignmentId, dwellMinutes) +} + /** * Edits to one stop on the drive: saving the stop popup as a pause or as a night, * releasing a booked night, the kind, fill and stay of a stop, moving it within its day @@ -63,7 +97,7 @@ export function useRoadtripStopEdits(options: RoadtripStopEditsOptions) { } try { if (stopDraft.editing) { - await tripActions.updatePlace(tripId, stopDraft.editing.placeId, { stop_type: stopType, duration_minutes: dwellMinutes }) + await writeEditedStop(tripActions, tripId, assignments, stopDraft.editing, { stopType, dwellMinutes }) if (accommodationId) { // The night is what was switched off, not the stop: it stays where it is // in the drive and becomes an ordinary pause. @@ -106,7 +140,7 @@ export function useRoadtripStopEdits(options: RoadtripStopEditsOptions) { } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } - }, [stopDraft, tripId, tripActions, updateRouteForDay, toast, t, roadtripVias, viaLiesBefore, loadAccommodations, tripAccommodations, reservations, setStayRelease, setStopDraft]) + }, [stopDraft, tripId, tripActions, updateRouteForDay, toast, t, roadtripVias, viaLiesBefore, loadAccommodations, tripAccommodations, reservations, setStayRelease, setStopDraft, assignments]) /** The yes to the question above: the same save, this time allowed to drop the night. */ const confirmStayRelease = useCallback(async () => { @@ -315,22 +349,32 @@ export function useRoadtripStopEdits(options: RoadtripStopEditsOptions) { /** * How long the traveller stays at one stop. * - * Writes `places.duration_minutes`, which the schedule has read since it was written - * and which nothing in TREK has ever been able to set: the road trip is the only place - * the value means anything, so it is the only place that edits it. + * The stay belongs to the visit (#3092): the same place planned twice on a day can be + * stopped at once and only driven past the other time, so a stop the rail names by its + * assignment writes `day_assignments.stay_minutes` and leaves the place and its other + * visits alone. Only a stop without a saved visit of its own (no assignment, or the + * optimistic row of one still on its way) falls back to the place's + * `duration_minutes`, which every visit without a stay of its own reads. * - * Zero rather than null to clear: the update statement folds a null into "leave it - * alone" (`COALESCE(?, duration_minutes)`), so a null could give a stop a stay but - * never take one away. The rail reads zero and absent as the same thing. + * Zero rather than null to clear: on the place the update statement folds a null into + * "leave it alone" (`COALESCE(?, duration_minutes)`), and on a visit a null would hand + * it back to the place's stay instead of taking the stay away. The rail reads zero and + * absent as the same thing. */ - const setRoadtripStay = useCallback(async (placeId: number, minutes: number) => { - if (!can('place_edit', trip)) return + const setRoadtripStay = useCallback(async (placeId: number, minutes: number, assignmentId?: number) => { + const visitDayId = savedVisitDayOf(assignments, assignmentId) try { + if (assignmentId != null && visitDayId !== null) { + if (!can('day_edit', trip)) return + await tripActions.setAssignmentStay(tripId, visitDayId, assignmentId, minutes) + return + } + if (!can('place_edit', trip)) return await tripActions.updatePlace(tripId, placeId, { duration_minutes: minutes }) } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } - }, [tripId, tripActions, toast, t, can, trip]) + }, [assignments, tripId, tripActions, toast, t, can, trip]) /** * Moves a stop onto another day, from the road trip rail. diff --git a/client/src/pages/tripPlanner/useTourWorkspace.ts b/client/src/pages/tripPlanner/useTourWorkspace.ts index fbc3f757b..654d957c5 100644 --- a/client/src/pages/tripPlanner/useTourWorkspace.ts +++ b/client/src/pages/tripPlanner/useTourWorkspace.ts @@ -10,6 +10,7 @@ import { useSkiClassification } from '../../components/Tours/ski/useSkiClassific import { useRecordedTrack } from '../../components/Tours/useRecordedTrack'; import { useTourGpxImport } from '../../components/Tours/useTourGpxImport'; import { useWandererBrowser } from '../../components/Tours/wanderer/useWandererBrowser'; +import { useIsWide } from '../../hooks/sizeClass'; import { useAddonStore } from '../../store/addonStore'; import { useTripStore } from '../../store/tripStore'; import { useTourDetailActions } from './useTourDetailActions'; @@ -71,12 +72,17 @@ export function useTourWorkspace(planner: TripPlanner, canPlaceEdit: boolean, ca } = planner; // wanderer only while the admin allows it under Tours (the store reads Tours being on into it too). const wandererAllowed = useAddonStore((state) => state.toursWanderer); + // The workspace is up where its tab is: on a desktop, and in the touch shell on a + // large screen (an iPad, an unfolded foldable). The app counts as a phone shell on + // every device, so the phone test alone left the tablet's editor switched off. + const largeTouch = useIsWide(); + const workspaceUp = activeTab === 'tour-planner' && (!isMobile || largeTouch); const tourPlanner = useTourPlanner({ tripId, canEdit: canPlaceEdit, canAssign: canDayEdit, - active: activeTab === 'tour-planner' && enabledAddons.tours && !isMobile, + active: workspaceUp && enabledAddons.tours, onSaved: async (result) => { upsertTour(result.tour); toast.success(t('tours.planner.saved')); @@ -86,7 +92,7 @@ export function useTourWorkspace(planner: TripPlanner, canPlaceEdit: boolean, ca }); useTourRevisionWatch(tourPlanner, tours); // P2C-03: a save made elsewhere reaches the open editor - usePublishOpenTour(tourPlanner, activeTab === 'tour-planner' && !isMobile); // P6: the chat's "+ Tour" takes a found place into the tour open here + usePublishOpenTour(tourPlanner, workspaceUp); // P6: the chat's "+ Tour" takes a found place into the tour open here const { viewImportedTour, openTourInPlanner } = useTourOpeners(tourPlanner, places, tours); // The tours workspace's GPX import, shared by its button and its file drop. One new @@ -107,7 +113,7 @@ export function useTourWorkspace(planner: TripPlanner, canPlaceEdit: boolean, ca // Browsing the user's wanderer trails in place of the editor rail; the trail shows on the map. const wandererBrowser = useWandererBrowser({ tripId, - enabled: activeTab === 'tour-planner' && wandererAllowed && !isMobile && canPlaceEdit, + enabled: workspaceUp && wandererAllowed && canPlaceEdit, onImported: async (tour) => { upsertTour(tour); await useTripStore.getState().refreshPlaces(tripId); @@ -152,7 +158,7 @@ export function useTourWorkspace(planner: TripPlanner, canPlaceEdit: boolean, ca tours, tripMembers, canEdit: canPlaceEdit, - active: activeTab === 'tour-planner' && enabledAddons.tours && !isMobile, + active: workspaceUp && enabledAddons.tours, trackPaddlePlan, onSaved: takeInSavedTour, }); diff --git a/client/src/pages/tripPlanner/useTripPlanner.tabLink.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.tabLink.test.tsx new file mode 100644 index 000000000..21cb131e7 --- /dev/null +++ b/client/src/pages/tripPlanner/useTripPlanner.tabLink.test.tsx @@ -0,0 +1,110 @@ +// FE-TP-TABLINK-001 +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { ReactNode } from 'react'; + +import { buildTrip, buildUser } from '../../../tests/helpers/factories'; +import { makeActions } from '../../../tests/helpers/plannerActions'; +import { resetAllStores, seedStore } from '../../../tests/helpers/store'; +import { addonsApi, airtrailApi, authApi, healthApi, tripsApi } from '../../api/client'; +import { TranslationProvider } from '../../i18n/TranslationContext'; +import { useAuthStore } from '../../store/authStore'; +import { useBackgroundTasksStore } from '../../store/backgroundTasksStore'; +import { usePluginStore } from '../../store/pluginStore'; +import { type TripStoreState, useTripStore } from '../../store/tripStore'; +import { useTripPlanner } from './useTripPlanner'; + +/** + * A `?tab=` that arrives while the planner is already open, the way a notification + * opens one. The planner is shared by the desktop page and the phone shell, so the + * switch has to happen here and not in a part only one of them mounts. + */ + +let searchParams = new URLSearchParams(); +const setSearchParams = vi.fn((updater: (p: URLSearchParams) => URLSearchParams) => { + const next = new URLSearchParams(searchParams); + searchParams = typeof updater === 'function' ? updater(next) : next; +}); + +vi.mock('react-router', () => ({ + useParams: () => ({ id: '42' }), + useNavigate: () => vi.fn(), + useSearchParams: () => [searchParams, setSearchParams], +})); + +vi.mock('../../hooks/useTripWebSocket', () => ({ useTripWebSocket: vi.fn() })); + +vi.mock('../../hooks/useRouteCalculation', () => ({ + useRouteCalculation: () => ({ + route: null, + routeSegments: [], + routeVias: [], + routeInfo: null, + setRoute: vi.fn(), + setRouteInfo: vi.fn(), + updateRouteForDay: vi.fn(async () => {}), + }), +})); + +vi.mock('../../hooks/useAirtrailConnection', () => ({ + useAirtrailConnection: () => ({ airtrailEnabled: false, connected: false, available: false, loading: false }), +})); + +vi.mock('../../repo/accommodationRepo', async (importOriginal) => { + const real = await importOriginal(); + return { accommodationRepo: { ...real.accommodationRepo, list: vi.fn(async () => ({ accommodations: [] })) } }; +}); + +vi.mock('../../services/photoService', () => ({ + getCached: vi.fn(() => undefined), + fetchPhoto: vi.fn(), +})); + +function wrapper({ children }: { children: ReactNode }) { + return {children}; +} + +beforeEach(() => { + vi.clearAllMocks(); + resetAllStores(); + searchParams = new URLSearchParams(); + usePluginStore.setState({ plugins: [], loaded: true }); + useBackgroundTasksStore.setState({ tasks: [] }); + seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true, placesPhotosEnabled: false }); + useTripStore.setState({ + trip: buildTrip({ id: 42, title: 'Kyoto' }), + isLoading: false, + days: [], + places: [], + assignments: {}, + reservations: [], + ...(makeActions() as unknown as Partial), + } as Partial); + + vi.spyOn(addonsApi, 'enabled').mockResolvedValue({ addons: [{ id: 'collab' }] }); + vi.spyOn(authApi, 'getAppConfig').mockResolvedValue({}); + vi.spyOn(healthApi, 'features').mockResolvedValue({ bookingImport: false, aiParsing: false }); + vi.spyOn(tripsApi, 'getMembers').mockResolvedValue({ owner: null, members: [] }); + vi.spyOn(airtrailApi, 'sync').mockResolvedValue({ changed: 0 }); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('useTripPlanner — ?tab= while the planner is open', () => { + it('FE-TP-TABLINK-001: a message link switches an already mounted planner to Collab and remembers the tab', async () => { + const { result, rerender } = renderHook(() => useTripPlanner(), { wrapper }); + await act(async () => { + await Promise.resolve(); + }); + await waitFor(() => expect(result.current.TRIP_TABS.map((t) => t.id)).toContain('collab')); + expect(result.current.activeTab).toBe('plan'); + + searchParams = new URLSearchParams('tab=collab'); + rerender(); + + await waitFor(() => expect(result.current.activeTab).toBe('collab')); + expect(searchParams.has('tab')).toBe(false); + expect(sessionStorage.getItem('trip-tab-42')).toBe('collab'); + }); +}); diff --git a/client/src/pages/tripPlanner/useTripPlanner.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.test.tsx index b305e8c5d..e2a0e0a3e 100644 --- a/client/src/pages/tripPlanner/useTripPlanner.test.tsx +++ b/client/src/pages/tripPlanner/useTripPlanner.test.tsx @@ -296,15 +296,14 @@ describe('useTripPlanner — bootstrap', () => { expect(accommodationRepo.list).toHaveBeenCalledTimes(2) }) - it('FE-TP-HOOK-012: the splash gate opens once the trip finished loading', async () => { + it('FE-TP-HOOK-012: a trip that opens at once never asks for the splash, and holds no minimum', async () => { vi.useFakeTimers() seedTrip() const { result } = await renderPlanner() - expect(result.current.splashDone).toBe(false) await act(async () => { vi.advanceTimersByTime(1600) }) - expect(result.current.splashDone).toBe(true) + expect(result.current.slowOpen).toBe(false) vi.useRealTimers() }) diff --git a/client/src/pages/tripPlanner/useTripPlanner.ts b/client/src/pages/tripPlanner/useTripPlanner.ts index 44aa6554d..8c913dd32 100644 --- a/client/src/pages/tripPlanner/useTripPlanner.ts +++ b/client/src/pages/tripPlanner/useTripPlanner.ts @@ -34,7 +34,7 @@ import { usePluginStore } from '../../store/pluginStore' import type { Assignment, TripMember, Day, Reservation } from '../../types' import { OFM_POSITRON, DEFAULT_MAP_LAT, DEFAULT_MAP_LNG, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults' import { useTileUrl } from '../../hooks/useTileUrl' -import { placesForDays } from './tripPlannerModel' +import { placesForDays, tourPlannerTabOf } from './tripPlannerModel' import { isDeepLinkableTripTab, TRIP_TAB_LABEL_KEYS } from '../../constants/tripTabs' import { isRoutableReservation } from '../../utils/reservationRoutes' import { showReservationOnMap } from '../../components/Planner/bookings/showOnMap' @@ -50,7 +50,7 @@ import { useTripRosterSync } from './useTripRosterSync' import { useDayAdd } from './useDayAdd' import { usePlannerDialogs } from './usePlannerDialogs' import { usePlaceDeepLink } from './usePlaceDeepLink' -import { useAssistantDeepLink } from './useAssistantDeepLink' +import { useAssistantDeepLink, useAssistantTabLink } from './useAssistantDeepLink' import { useAssistantCompareView, useAssistantMapLink } from './useAssistantMapLink' import { useAssistantPlaceDraft } from './useAssistantPlaceDraft' import { usePlannerMapView } from './usePlannerMapView' @@ -66,7 +66,11 @@ import { useTourDayChoice } from './useTourDayChoice' import { useBookingEdits } from './useBookingEdits' import { usePlannerTripView } from './usePlannerTripView' import { useIsPhone } from '../../mobile/useIsPhone' +import { useIsWide } from '../../hooks/sizeClass' import { useRoadtripVias } from '../../components/Roadtrip/useRoadtripVias' +import { TRIP_SPLASH_AFTER_MS } from '../../components/shared/useTripSplashBeats' +import { useFlightLiveSync } from '../../components/Planner/flightLive/useFlightLiveSync' +import { useMailPrefillLink } from '../../components/MailIngest/useMailPrefillLink' /** * The trip's roster from the server: the owner and the members. Null offline @@ -118,6 +122,8 @@ export function useTripPlanner() { const todoItems = useTripStore(s => s.todoItems) const categories = useTripStore(s => s.categories) const reservations = useTripStore(s => s.reservations) + // Live flight states (status, position, delay) for the trip's flights, desktop and phone alike. + useFlightLiveSync(tripId, reservations.some(r => r.type === 'flight')) const budgetItems = useTripStore(s => s.budgetItems) const files = useTripStore(s => s.files) const selectedDayId = useTripStore(s => s.selectedDayId) @@ -150,6 +156,8 @@ export function useTripPlanner() { // road-trip mode is decided on it and the assignment and place lists below are // decided on that. One subscriber for the whole hook. const isMobile = useIsPhone() + // The touch shell on a tablet or an unfolded foldable, which has room for the tour editor. + const largeTouch = useIsWide() // The phone shell has no road-trip surface at all: no rail, no drive lines, and // no switch to turn the mode back off. Narrowing a desktop window past the // phone breakpoint used to carry the flag across anyway, which took the trip @@ -220,9 +228,10 @@ export function useTripPlanner() { // them; 'plan' is never replaceable) and may pick where its own tab sits. const journal = useTripJournal(Number.isFinite(tripId) ? tripId : null) const replacedTabs = new Set(tripPagePlugins.flatMap(p => p.tripPage?.replaces ?? [])) + const tourTab = tourPlannerTabOf(!!enabledAddons.tours, isMobile, largeTouch) const TRIP_TABS = [ { id: 'plan', label: t(TRIP_TAB_LABEL_KEYS.plan), icon: Map }, - ...(enabledAddons.tours && !isMobile ? [{ id: 'tour-planner', label: t(TRIP_TAB_LABEL_KEYS['tour-planner']), icon: Mountain, desktopOnly: true }] : []), + ...(tourTab ? [{ id: 'tour-planner', label: t(TRIP_TAB_LABEL_KEYS['tour-planner']), icon: Mountain, desktopOnly: tourTab.desktopOnly }] : []), { id: 'transports', label: t(TRIP_TAB_LABEL_KEYS.transports), icon: Train }, { id: 'buchungen', label: t(TRIP_TAB_LABEL_KEYS.buchungen), shortLabel: t('trip.tabs.reservationsShort'), icon: Ticket }, // Phone only: the desktop reaches the drive through the mode switch beside the @@ -267,7 +276,7 @@ export function useTripPlanner() { setActiveTab('plan') sessionStorage.setItem(`trip-tab-${tripId}`, 'plan') } - }, [activeTab, enabledAddons, addonsLoaded, tripPluginIds, pluginsLoaded, isMobile, journal.settled, journal.openJournalId]) + }, [activeTab, enabledAddons, addonsLoaded, tripPluginIds, pluginsLoaded, isMobile, largeTouch, journal.settled, journal.openJournalId]) const handleTabChange = (rawTabId: string): void => { // A core tab a plugin replaced is gone from the bar, but a programmatic jump @@ -280,6 +289,12 @@ export function useTripPlanner() { if (tabId === 'dateien' && (!files || files.length === 0)) tripActions.loadFiles?.(tripId) } + // Notifications can open a tab while this trip is already mounted, on either layout. + // Each link it takes is counted, so the phone shell can open the right part of the tab. + const [tabLink, setTabLink] = useState<{ tab: string; seq: number } | null>(null) + const onTabLinked = useCallback((tab: string) => setTabLink(prev => ({ tab, seq: (prev?.seq ?? 0) + 1 })), []) + useAssistantTabLink({ searchParams, setSearchParams, activeTab, selectTab: handleTabChange, onLinked: onTabLinked }) + // handleTabChange is where a tab's lazy load and its session memory happen, and // the tab we *start* on never goes through it — neither a ?tab= deep link nor a // tab restored from a previous visit. Catch both up once per trip, or opening @@ -295,7 +310,7 @@ export function useTripPlanner() { const { leftWidth, rightWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed, leftHidden, rightHidden, toggleLeft, toggleRight, narrow: narrowPanels, - startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizeMin, resizeMax, + startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing, resizeMin, resizeMaxLeft, resizeMaxRight, } = useResizablePanels() const { selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment } = usePlaceSelection() const toursEnabled = useAddonStore(state => state.isEnabled('tours')) @@ -643,6 +658,7 @@ export function useTripPlanner() { editingReservation, setEditingReservation, setShowReservationModal, editingTransport, setEditingTransport, setShowTransportModal, setTransportModalDayId, }) + useMailPrefillLink({ searchParams, setSearchParams, loaded: !isLoading && trip?.id === tripId, startImportReview }) // ── The plan's booking detail ─────────────────────────────────────────────── // A click on a booking in the plan shows it first; the editor is one Edit away. @@ -694,14 +710,28 @@ export function useTripPlanner() { const fontStyle = { fontFamily: "var(--font-system)" } - // Splash screen — show for initial load + a brief moment for photos to start loading - const [splashDone, setSplashDone] = useState(false) + // The trip's form saves alike from its own dialog and from the trip settings (#2811). + const saveTrip = useCallback(async (data: Parameters[1]) => { + await tripActions.updateTrip(tripId, data) + loadAccommodations() + toast.success(t('trip.toast.tripUpdated')) + }, [tripActions, tripId, loadAccommodations, toast, t]) + + // The splash only for a slow open, as on the phone (MTripOpening): a trip that + // loads within TRIP_SPLASH_AFTER_MS opens straight away, with no splash and no + // minimum on screen. + const [slowOpen, setSlowOpen] = useState(false) + // Every open is timed afresh: a trip opened after a slow one starts without the splash too. + const [wasLoading, setWasLoading] = useState(isLoading) + if (wasLoading !== isLoading) { + setWasLoading(isLoading) + if (isLoading) setSlowOpen(false) + } useEffect(() => { - if (!isLoading && trip) { - const timer = setTimeout(() => setSplashDone(true), 1500) - return () => clearTimeout(timer) - } - }, [isLoading, trip]) + if (!isLoading) return + const timer = setTimeout(() => setSlowOpen(true), TRIP_SPLASH_AFTER_MS) + return () => clearTimeout(timer) + }, [isLoading]) return { tripId, navigate, toast, t, language, locale, settings, placesPhotosEnabled, @@ -714,10 +744,10 @@ export function useTripPlanner() { dawarichTrailShown, toggleDawarichTrail, dawarichTrail, dawarichHiddenDates, dawarichEnabled: !!enabledAddons.dawarich, followTrack, roadtripViaCounts, allowedFileTypes, tripMembers, setTripMembers, refreshMembers, loadAccommodations, - TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange, + TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange, tabLink, leftWidth, rightWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed, leftHidden, rightHidden, toggleLeft, toggleRight, narrowPanels, - startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizeMin, resizeMax, + startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing, resizeMin, resizeMaxLeft, resizeMaxRight, selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment, toursEnabled, toursMode, setToursMode, tours, toursLoading, tourDataReady, tourPlaceIds, reloadTourPlaceIds, invalidateTourPlaceIds, upsertTour, selectedTour, tourStageStops, @@ -775,7 +805,7 @@ export function useTripPlanner() { ...dayClear, handleSaveReservation, handleSaveTransport, handleDeleteReservation, selectedPlace, dayOrderMap, dayPlaces, - mapTileUrl, fontStyle, splashDone, + mapTileUrl, fontStyle, slowOpen, saveTrip, // The assistant on the map, handed to MapViewAuto whole by both shells. assistantMap, } diff --git a/client/src/pages/tripPlanner/useTripPlannerPage.ts b/client/src/pages/tripPlanner/useTripPlannerPage.ts index d6c6b6156..47e21a1d1 100644 --- a/client/src/pages/tripPlanner/useTripPlannerPage.ts +++ b/client/src/pages/tripPlanner/useTripPlannerPage.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef } from 'react' +import { useCallback, useEffect, useMemo, useRef, useLayoutEffect } from 'react' import { usePoiExplore, type Bbox } from '../../components/Map/usePoiExplore' import { placeActions } from '../../components/Planner/usePlaceActions' import { tourRouteStyle } from '../../components/Tours/planner/tourRouteStyle' @@ -8,6 +8,7 @@ import { useTrackPortageParts } from '../../components/Tours/paddle/useTrackPort import { usePaddleObstacleSync } from '../../components/Tours/paddle/usePaddleObstacleSync' import { tourPlannedTimes as projectTourPlannedTimes } from '../../components/Tours/tourPresentation' import { usePlanMapViewport } from '../../hooks/usePlanMapViewport' +import { useMeasuredHeight } from '../../hooks/useReportedHeight' import { usePaddleObstacleStore } from '../../store/paddleObstacleStore' import { useHighlightedRoute } from '../../components/Tours/bike/useHighlightedRoute' import { useLegVariantLines } from '../../components/Tours/planner/legVariantPaint' @@ -21,7 +22,15 @@ import { mapFocusKeyOf, offeredWaysOf, paddleLineOf } from './tourMapFocus' import { placeFormContext } from './placeFormContext' export function useTripPlannerPage() { - const planner = useTripPlanner() + return useTripPlannerPageOf(useTripPlanner()) +} + +/** + * The planner page's state over a planner someone already holds. The touch shell + * owns its own useTripPlanner(), and its tours workspace on a large screen wires the + * desktop's tour editor from this, so the two cannot drift apart. + */ +export function useTripPlannerPageOf(planner: ReturnType) { const { activeTab, can, places, @@ -101,8 +110,12 @@ export function useTripPlannerPage() { }, [activeTab, closeGpxTour]) const poi = usePoiExplore() + // The place card's height over the desktop map, so the selection pans its pin above it (#2991). + const inspectorCard = useMeasuredHeight() const poiViewportChangeRef = useRef(poi.onViewportChange) - poiViewportChangeRef.current = poi.onViewportChange + useLayoutEffect(() => { + poiViewportChangeRef.current = poi.onViewportChange + }) // The place search looks where the plan map looks, and only while it is on screen. const reportViewport = usePlanMapViewport(tripId, activeTab === 'plan') const captureViewport = useCallback((bounds: Bbox) => { @@ -163,5 +176,6 @@ export function useTripPlannerPage() { // The day plan's tours: which places are tours, their planned times and where their stages run (MDT-02). dayPlanTours: { tourPlaceIds: planner.tourPlaceIds, plannedTourDurations, tourStageStops: planner.tourStageStops }, placeForm: { close: closePlaceForm, ...placeFormContext(planner.editingPlace, planner.assignments, tours) }, + inspectorCard, } } \ No newline at end of file diff --git a/client/src/push/webPush.native.test.ts b/client/src/push/webPush.native.test.ts new file mode 100644 index 000000000..5119fbc9d --- /dev/null +++ b/client/src/push/webPush.native.test.ts @@ -0,0 +1,80 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { pushApi } from '../api/push'; +import { + NativePushDenied, + forgetNativePush, + nativePushActive, + nativePushEndpoint, + registerNativePush, +} from '../native/push'; +import { + WebPushError, + disableWebPush, + enableWebPush, + forgetPushDeviceOnLogout, + getWebPushSupport, + readWebPushDeviceState, +} from './webPush'; + +vi.mock('../native/push', () => { + class NativePushDenied extends Error {} + return { + NativePushDenied, + nativePushActive: vi.fn(), + nativePushEndpoint: vi.fn(), + registerNativePush: vi.fn(), + forgetNativePush: vi.fn(), + }; +}); +vi.mock('../api/push', () => ({ pushApi: { subscribe: vi.fn(), unsubscribe: vi.fn(), getPublicKey: vi.fn() } })); + +const SUB = { endpoint: 'https://push.liketrek.com/v1/apns/production/abcd', keys: { p256dh: 'BPk', auth: 'aa' } }; + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(nativePushActive).mockReturnValue(true); + vi.mocked(nativePushEndpoint).mockReturnValue(null); + vi.mocked(registerNativePush).mockResolvedValue(SUB); + vi.mocked(pushApi.subscribe).mockResolvedValue(undefined as never); + vi.mocked(pushApi.unsubscribe).mockResolvedValue(undefined as never); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(null, { status: 204 })) + ); +}); + +describe('web push inside the app', () => { + it('counts as supported without a service worker, and reads on or off from the remembered endpoint', async () => { + expect(getWebPushSupport()).toEqual({ supported: true, reason: null }); + expect(await readWebPushDeviceState()).toBe('off'); + vi.mocked(nativePushEndpoint).mockReturnValue(SUB.endpoint); + expect(await readWebPushDeviceState()).toBe('on'); + }); + + it('switches on with the app subscription, and rolls it back when the server refuses', async () => { + await enableWebPush('server-key'); + expect(pushApi.subscribe).toHaveBeenCalledWith(SUB); + + vi.mocked(pushApi.subscribe).mockRejectedValueOnce(new Error('400')); + await expect(enableWebPush('server-key')).rejects.toBeInstanceOf(WebPushError); + expect(forgetNativePush).toHaveBeenCalled(); + }); + + it('reads a refused permission as denied', async () => { + vi.mocked(registerNativePush).mockRejectedValue(new NativePushDenied()); + await expect(enableWebPush('server-key')).rejects.toMatchObject({ code: 'denied' }); + }); + + it('switches off and forgets the device at logout through the endpoint it remembers', async () => { + vi.mocked(nativePushEndpoint).mockReturnValue(SUB.endpoint); + await disableWebPush(); + expect(pushApi.unsubscribe).toHaveBeenCalledWith(SUB.endpoint); + expect(forgetNativePush).toHaveBeenCalled(); + + await forgetPushDeviceOnLogout(500); + expect(fetch).toHaveBeenCalledWith( + '/api/notifications/push/subscriptions', + expect.objectContaining({ method: 'DELETE' }) + ); + }); +}); diff --git a/client/src/push/webPush.ts b/client/src/push/webPush.ts index b394cb810..47f4dd336 100644 --- a/client/src/push/webPush.ts +++ b/client/src/push/webPush.ts @@ -1,7 +1,9 @@ -import type { PushSubscriptionInput, PushUnsubscribeRequest } from '@trek/shared' +import { WEB_PUSH_CHANNEL_ID, type PushSubscriptionInput, type PushUnsubscribeRequest } from '@trek/shared' +import { notificationsApi } from '../api/client' import { pushApi } from '../api/push' import { isEffectivelyOffline } from '../sync/networkMode' import { isIosDevice, isIosStandalone } from '../utils/iosDevice' +import { NativePushDenied, forgetNativePush, nativePushActive, nativePushEndpoint, registerNativePush } from '../native/push' /** * Web Push on this device: whether it can work here, and switching it on and @@ -72,6 +74,9 @@ function hasPushApis(): boolean { */ export function getWebPushSupport(): WebPushSupport { if (typeof window === 'undefined') return unsupported('unsupported') + // Inside the app the app makes the subscription (native/push.ts), with no + // service worker and no Notification API in the WebView. + if (nativePushActive()) return { supported: true, reason: null } // A service worker, and push with it, exists only in a secure context: HTTPS, // or localhost while developing. A plain http LAN address never gets one. if (window.isSecureContext === false) return unsupported('insecure') @@ -174,7 +179,21 @@ export async function loadPushPublicKey(): Promise { } /** What the settings card shows for this device. Never rejects. */ +/** + * Whether this server offers push to its users: the admin has the channel on + * and the server can sign. The same answer the settings' push card goes by. + */ +export async function pushChannelOffered(): Promise { + try { + const matrix = (await notificationsApi.getPreferences()) as { channels?: { id: string; active?: boolean }[] } + return matrix.channels?.some((ch) => ch.id === WEB_PUSH_CHANNEL_ID && ch.active) ?? false + } catch { + return false + } +} + export async function readWebPushDeviceState(): Promise { + if (nativePushActive()) return nativePushEndpoint() ? 'on' : 'off' const { reason } = getWebPushSupport() if (reason) return reason if (getPushPermission() === 'denied') return 'denied' @@ -215,6 +234,7 @@ async function subscribeWithKey( * spend it. The permission request is therefore the first thing that runs. */ export async function enableWebPush(publicKey: string, registration?: ServiceWorkerRegistration | null): Promise { + if (nativePushActive()) return enableNativePush() const permission = Notification.permission === 'granted' ? 'granted' : await Notification.requestPermission() if (permission === 'denied') throw new WebPushError('denied') @@ -247,6 +267,12 @@ export async function enableWebPush(publicKey: string, registration?: ServiceWor * push service answers 404 or 410 for on its next send. */ export async function disableWebPush(): Promise { + if (nativePushActive()) { + const endpoint = nativePushEndpoint() + if (endpoint) await bestEffort('forgetting the device on the server', () => pushApi.unsubscribe(endpoint)) + forgetNativePush() + return + } const subscription = await currentPushSubscription() if (!subscription) return await bestEffort('forgetting the device on the server', () => pushApi.unsubscribe(subscription.endpoint)) @@ -265,6 +291,12 @@ export async function disableWebPush(): Promise { * to switch it on. Never rejects. */ export async function resyncPushSubscription(): Promise { + if (nativePushActive()) { + // The app's subscription carries no server key, so only the row is restored. + if (!nativePushEndpoint() || isEffectivelyOffline()) return + await bestEffort('re-registering this device', async () => pushApi.subscribe(await registerNativePush())) + return + } if (!getWebPushSupport().supported || getPushPermission() !== 'granted' || isEffectivelyOffline()) return await bestEffort('re-registering this device', async () => { const registration = await existingRegistration() @@ -325,6 +357,14 @@ async function forgetOnServerAtLogout(endpoint: string, timeoutMs: number): Prom * or 410. */ export async function forgetPushDeviceOnLogout(timeoutMs = LOGOUT_PUSH_TIMEOUT_MS): Promise { + if (nativePushActive()) { + const endpoint = nativePushEndpoint() + forgetNativePush() + if (endpoint) { + await withTimeout(bestEffort('forgetting this device at logout', () => forgetOnServerAtLogout(endpoint, timeoutMs)), timeoutMs, undefined) + } + return + } if (!hasPushApis()) return const teardown = bestEffort('forgetting this device at logout', async () => { const subscription = await currentPushSubscription() @@ -336,3 +376,19 @@ export async function forgetPushDeviceOnLogout(timeoutMs = LOGOUT_PUSH_TIMEOUT_M }) await withTimeout(teardown, timeoutMs, undefined) } + +/** Push on for the app: its own subscription, then the server, rolled back if the server refuses. */ +async function enableNativePush(): Promise { + let subscription: PushSubscriptionInput + try { + subscription = await registerNativePush() + } catch (err) { + throw new WebPushError(err instanceof NativePushDenied ? 'denied' : 'failed', err) + } + try { + await pushApi.subscribe(subscription) + } catch (err) { + forgetNativePush() + throw err instanceof WebPushError ? err : new WebPushError('failed', err) + } +} diff --git a/client/src/repo/apiKeysRepo.ts b/client/src/repo/apiKeysRepo.ts new file mode 100644 index 000000000..ab64306df --- /dev/null +++ b/client/src/repo/apiKeysRepo.ts @@ -0,0 +1,12 @@ +import { authApi } from '../api/client'; + +/** + * Public API keys, deliberately online-only: a key is minted by the server and + * its secret is shown exactly once, so there is nothing a device could hold or + * replay offline. The settings views reach them through here, never the API. + */ +export const apiKeysRepo = { + list: authApi.apiKeys.list, + create: authApi.apiKeys.create, + delete: authApi.apiKeys.delete, +}; diff --git a/client/src/repo/assignmentRepo.test.ts b/client/src/repo/assignmentRepo.test.ts index 6de6f5b08..c7305e491 100644 --- a/client/src/repo/assignmentRepo.test.ts +++ b/client/src/repo/assignmentRepo.test.ts @@ -3,12 +3,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { assignmentRepo } from './assignmentRepo' import { offlineDb, clearAll } from '../db/offlineDb' import { saveAssignmentEndDay } from '../api/assignmentEndDay' +import { saveAssignmentStay } from '../api/assignmentStay' import { isEffectivelyOffline } from '../sync/networkMode' import { mutationQueue } from '../sync/mutationQueue' import { apiClient, assignmentsApi } from '../api/client' import type { Assignment, Day } from '../types' vi.mock('../api/assignmentEndDay', () => ({ saveAssignmentEndDay: vi.fn() })) +vi.mock('../api/assignmentStay', () => ({ saveAssignmentStay: vi.fn() })) vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => true) })) vi.mock('../sync/authGate', () => ({ isAuthed: () => true })) vi.mock('../api/client', () => ({ apiClient: { request: vi.fn() }, assignmentsApi: { updateTime: vi.fn(), updateNotes: vi.fn(), clearDay: vi.fn() } })) @@ -51,6 +53,24 @@ describe('assignment day-end persistence', () => { }) }) +describe('assignment stay persistence (#3092)', () => { + it('stores the stay on the one visit offline with a replayable write', async () => { + await assignmentRepo.setStay(9, assignment, 0) + expect((await offlineDb.days.get(1))?.assignments?.[0]).toMatchObject({ id: 7, stay_minutes: 0 }) + expect(await offlineDb.mutationQueue.toArray()).toEqual([expect.objectContaining({ + url: '/trips/9/assignments/7/stay', method: 'PUT', body: { stay_minutes: 0 }, resource: 'assignments', entityId: 7, + })]) + }) + + it('saves through the online API and caches what came back', async () => { + vi.mocked(isEffectivelyOffline).mockReturnValue(false) + vi.mocked(saveAssignmentStay).mockResolvedValue({ ...assignment, stay_minutes: 20 }) + await assignmentRepo.setStay(9, assignment, 20) + expect(saveAssignmentStay).toHaveBeenCalledWith(9, 7, { stay_minutes: 20 }) + expect((await offlineDb.days.get(1))?.assignments?.[0].stay_minutes).toBe(20) + }) +}) + describe('assignment time persistence', () => { const times = { place_time: '07:00', end_time: null } diff --git a/client/src/repo/assignmentRepo.ts b/client/src/repo/assignmentRepo.ts index 2d483e2a8..0fbdeb4a2 100644 --- a/client/src/repo/assignmentRepo.ts +++ b/client/src/repo/assignmentRepo.ts @@ -1,5 +1,6 @@ import { assignmentSchema } from '@trek/shared' import { saveAssignmentEndDay } from '../api/assignmentEndDay' +import { saveAssignmentStay } from '../api/assignmentStay' import { assignmentsApi } from '../api/client' import { offlineDb } from '../db/offlineDb' import { cacheAssignment } from '../db/cacheAssignment' @@ -32,6 +33,34 @@ async function cacheVisitFields(tripId: number, id: number, fields: Partial; fields: Partial; send: () => Promise }, +): Promise { + if (!(await mutationQueue.mustQueue('assignments', assignment.id))) { + const saved = await write.send() + await cacheAssignment(saved) + return saved + } + const updated = { ...assignment, ...write.fields } + await offlineDb.transaction('rw', offlineDb.days, offlineDb.mutationQueue, async () => { + await mutationQueue.enqueue({ + id: generateUUID(), tripId: Number(tripId), method: 'PUT', + url: `/trips/${tripId}/assignments/${assignment.id}/${write.suffix}`, + body: write.body, resource: 'assignments', entityId: assignment.id, + }) + await cacheAssignment(updated) + }) + mutationQueue.sendSoon() + return updated +} + function inOrder(items: Assignment[], orderedIds: number[]): Assignment[] { const rank = new Map(orderedIds.map((id, index) => [id, index])) return items @@ -237,42 +266,29 @@ export const assignmentRepo = { }, async setEndDay(tripId: number | string, assignment: Assignment, endDay: boolean): Promise { - if (!(await mutationQueue.mustQueue('assignments', assignment.id))) { - const saved = await saveAssignmentEndDay(tripId, assignment.id, { end_day: endDay }) - await cacheAssignment(saved) - return saved - } - const updated = { ...assignment, end_day: endDay } - await offlineDb.transaction('rw', offlineDb.days, offlineDb.mutationQueue, async () => { - await mutationQueue.enqueue({ - id: generateUUID(), tripId: Number(tripId), method: 'PUT', - url: `/trips/${tripId}/assignments/${assignment.id}/end-day`, - body: { end_day: endDay }, resource: 'assignments', entityId: assignment.id, - }) - await cacheAssignment(updated) + return await writeVisitField(tripId, assignment, { + suffix: 'end-day', body: { end_day: endDay }, fields: { end_day: endDay }, + send: () => saveAssignmentEndDay(tripId, assignment.id, { end_day: endDay }), + }) + }, + + /** + * How long the drive stands at this one visit (#3092), offline too. Null hands the + * visit back to the stay its place carries. + */ + async setStay(tripId: number | string, assignment: Assignment, stayMinutes: number | null): Promise { + return await writeVisitField(tripId, assignment, { + suffix: 'stay', body: { stay_minutes: stayMinutes }, fields: { stay_minutes: stayMinutes }, + send: () => saveAssignmentStay(tripId, assignment.id, { stay_minutes: stayMinutes }), }) - mutationQueue.sendSoon() - return updated }, /** Takes a stop out of the day's route or puts it back (#2532), offline too. */ async setRouteExcluded(tripId: number | string, assignment: Assignment, excluded: boolean): Promise { - if (!(await mutationQueue.mustQueue('assignments', assignment.id))) { - const saved = assignmentSchema.parse((await assignmentsApi.setRouteExcluded(tripId, assignment.id, excluded)).assignment) - await cacheAssignment(saved) - return saved - } - const updated = { ...assignment, route_excluded: excluded } - await offlineDb.transaction('rw', offlineDb.days, offlineDb.mutationQueue, async () => { - await mutationQueue.enqueue({ - id: generateUUID(), tripId: Number(tripId), method: 'PUT', - url: `/trips/${tripId}/assignments/${assignment.id}/route`, - body: { excluded }, resource: 'assignments', entityId: assignment.id, - }) - await cacheAssignment(updated) + return await writeVisitField(tripId, assignment, { + suffix: 'route', body: { excluded }, fields: { route_excluded: excluded }, + send: async () => assignmentSchema.parse((await assignmentsApi.setRouteExcluded(tripId, assignment.id, excluded)).assignment), }) - mutationQueue.sendSoon() - return updated }, /** diff --git a/client/src/repo/fileRepo.offline.test.ts b/client/src/repo/fileRepo.offline.test.ts index 9506233d1..0af966bac 100644 --- a/client/src/repo/fileRepo.offline.test.ts +++ b/client/src/repo/fileRepo.offline.test.ts @@ -1,4 +1,4 @@ -// FE-REPO-FILE-OFF-001 to FE-REPO-FILE-OFF-008 +// FE-REPO-FILE-OFF-001 to FE-REPO-FILE-OFF-009 // Offline write paths (#2601), fileRepo.test.ts covers the reads. import 'fake-indexeddb/auto'; import { http, HttpResponse } from 'msw'; @@ -160,3 +160,21 @@ describe('fileRepo — online', () => { expect(await offlineDb.mutationQueue.count()).toBe(0); }); }); + +describe('fileRepo.previewUrl', () => { + it('FE-REPO-FILE-OFF-009: online a preview gets a signed address, offline the plain one the cache may serve', async () => { + let asked = 0; + server.use( + http.post('/api/auth/resource-token', () => { + asked++; + return HttpResponse.json({ token: 'abc' }); + }) + ); + expect(await fileRepo.previewUrl('/api/trips/1/files/6/download')).toBe('/api/trips/1/files/6/download'); + expect(asked).toBe(0); + + setOnline(true); + expect(await fileRepo.previewUrl('/api/trips/1/files/6/download')).toBe('/api/trips/1/files/6/download?token=abc'); + expect(asked).toBe(1); + }); +}); diff --git a/client/src/repo/fileRepo.ts b/client/src/repo/fileRepo.ts index a07592ffd..66db6e117 100644 --- a/client/src/repo/fileRepo.ts +++ b/client/src/repo/fileRepo.ts @@ -1,4 +1,5 @@ import { filesApi } from '../api/client' +import { getAuthUrl } from '../api/authUrl' import { offlineDb, replaceTripRows } from '../db/offlineDb' import { mutationQueue, generateUUID } from '../sync/mutationQueue' import { isEffectivelyOffline } from '../sync/networkMode' @@ -198,4 +199,14 @@ export const fileRepo = { const link = links.find(matches) if (link) await filesApi.removeLink(tripId, id, link.id) }, + + /** + * A file's address signed for showing it in place (an image tile, a document + * preview), good for one download. Online only: offline it answers the plain + * address, which the service worker serves from its cache when it has the file. + */ + async previewUrl(url: string): Promise { + if (isEffectivelyOffline()) return url + return getAuthUrl(url, 'download') + }, } diff --git a/client/src/repo/mailIngestRepo.test.ts b/client/src/repo/mailIngestRepo.test.ts new file mode 100644 index 000000000..999dc38d0 --- /dev/null +++ b/client/src/repo/mailIngestRepo.test.ts @@ -0,0 +1,38 @@ +// FE-MAILINGEST-REPO-001 to FE-MAILINGEST-REPO-003 +import { afterEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../api/mailIngest', () => ({ + mailIngestApi: { inboxCount: vi.fn(), tripAddress: vi.fn(), adminSettings: vi.fn() }, +})); + +import { mailIngestApi } from '../api/mailIngest'; +import { _resetNetworkMode, setForcedOffline } from '../sync/networkMode'; +import { mailIngestRepo } from './mailIngestRepo'; +import { OnlineOnlyError } from './onlineOnly'; + +afterEach(() => { + _resetNetworkMode(); + vi.mocked(mailIngestApi.inboxCount).mockReset(); +}); + +describe('mailIngestRepo', () => { + it('FE-MAILINGEST-REPO-001: answers parsed against the shared contract', async () => { + vi.mocked(mailIngestApi.inboxCount).mockResolvedValue({ pending: 3 }); + vi.mocked(mailIngestApi.tripAddress).mockResolvedValue({ address: null }); + expect(await mailIngestRepo.inboxCount()).toBe(3); + expect(await mailIngestRepo.tripAddress(7)).toBeNull(); + }); + + it('FE-MAILINGEST-REPO-002: an answer of another shape fails here, not in the view', async () => { + vi.mocked(mailIngestApi.inboxCount).mockResolvedValue({ pending: 'many' }); + await expect(mailIngestRepo.inboxCount()).rejects.toThrow(); + vi.mocked(mailIngestApi.adminSettings).mockResolvedValue(null); + expect(await mailIngestRepo.adminSettings()).toEqual({}); + }); + + it('FE-MAILINGEST-REPO-003: offline nothing is asked, and the caller hears why', async () => { + setForcedOffline(true); + await expect(mailIngestRepo.inboxCount()).rejects.toBeInstanceOf(OnlineOnlyError); + expect(mailIngestApi.inboxCount).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/repo/mailIngestRepo.ts b/client/src/repo/mailIngestRepo.ts new file mode 100644 index 000000000..c1c4f4cb5 --- /dev/null +++ b/client/src/repo/mailIngestRepo.ts @@ -0,0 +1,104 @@ +import { + mailIngestAddressResponseSchema, + mailIngestAdminStatusResponseSchema, + mailIngestAdminTestResponseSchema, + mailIngestCandidateResponseSchema, + mailIngestInboxCountResponseSchema, + mailIngestInboxResponseSchema, + mailIngestMessagePreviewResponseSchema, + mailIngestPrefillResponseSchema, + mailIngestSettingsResponseSchema, + mailIngestUploadResponseSchema, +} from '@trek/shared'; +import { mailIngestApi, type MailIngestAction } from '../api/mailIngest'; +import { requireOnline } from './onlineOnly'; + +/** + * The booking mail import: the person's settings and forwarding addresses, + * the inbox of bookings read from forwarded mails, the actions on them, and + * the admin's transport settings and status. + * + * **Deliberately online-only, and no Dexie table.** Every action asks the + * server to decide (which trip, whether it is a duplicate, whether the mail + * may still be undone), so there is nothing an offline copy could do. + * Answers are parsed against the shared contracts rather than cast, so a + * server that answered something else fails here, naming the field. + */ +export const mailIngestRepo = { + async settings() { + requireOnline(); + return mailIngestSettingsResponseSchema.parse(await mailIngestApi.settings()); + }, + + async updateSettings(body: { enabled?: boolean; ai_enabled?: boolean; auto_add?: boolean }) { + requireOnline(); + return mailIngestSettingsResponseSchema.parse(await mailIngestApi.updateSettings(body)); + }, + + async renewAddress() { + requireOnline(); + return mailIngestAddressResponseSchema.parse(await mailIngestApi.renewAddress()); + }, + + async tripAddress(tripId: number) { + requireOnline(); + return mailIngestAddressResponseSchema.parse(await mailIngestApi.tripAddress(tripId)).address; + }, + + async createTripAddress(tripId: number) { + requireOnline(); + return mailIngestAddressResponseSchema.parse(await mailIngestApi.createTripAddress(tripId)).address; + }, + + async inbox(before?: number) { + requireOnline(); + return mailIngestInboxResponseSchema.parse(await mailIngestApi.inbox({ status: 'open', before })); + }, + + async inboxCount() { + requireOnline(); + return mailIngestInboxCountResponseSchema.parse(await mailIngestApi.inboxCount()).pending; + }, + + async preview(messageId: number) { + requireOnline(); + return mailIngestMessagePreviewResponseSchema.parse(await mailIngestApi.preview(messageId)); + }, + + async prefill(candidateId: number) { + requireOnline(); + return mailIngestPrefillResponseSchema.parse(await mailIngestApi.prefill(candidateId)); + }, + + async act(candidateId: number, action: MailIngestAction, body: Record = {}) { + requireOnline(); + return mailIngestCandidateResponseSchema.parse(await mailIngestApi.act(candidateId, action, body)).candidate; + }, + + async upload(file: File) { + requireOnline(); + return mailIngestUploadResponseSchema.parse(await mailIngestApi.upload(file)); + }, + + async adminStatus() { + requireOnline(); + return mailIngestAdminStatusResponseSchema.parse(await mailIngestApi.adminStatus()); + }, + + async adminTest() { + requireOnline(); + return mailIngestAdminTestResponseSchema.parse(await mailIngestApi.adminTest()); + }, + + /** The admin's stored app settings (passwords masked), of which the mail form reads its own keys. */ + async adminSettings(): Promise> { + requireOnline(); + const raw = await mailIngestApi.adminSettings(); + return raw && typeof raw === 'object' ? (raw as Record) : {}; + }, + + async saveAdminSettings(patch: Record) { + requireOnline(); + await mailIngestApi.saveAdminSettings(patch); + }, +}; diff --git a/client/src/repo/placeRepo.offline.test.ts b/client/src/repo/placeRepo.offline.test.ts index e9242d661..fa7435c77 100644 --- a/client/src/repo/placeRepo.offline.test.ts +++ b/client/src/repo/placeRepo.offline.test.ts @@ -1,4 +1,4 @@ -// FE-REPO-PLACE-001 to FE-REPO-PLACE-013, FE-REPO-PLACE-030 +// FE-REPO-PLACE-001 to FE-REPO-PLACE-013, FE-REPO-PLACE-030 to FE-REPO-PLACE-032 // Offline write paths (mutation queue + optimistic Dexie rows) and the bulk // online paths, which tests/unit/repo/placeRepo.test.ts does not touch. import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' @@ -8,7 +8,7 @@ import { server } from '../../tests/helpers/msw/server' import { placeRepo } from './placeRepo' import { offlineDb, clearAll } from '../db/offlineDb' import type { QueuedMutation } from '../db/offlineDb' -import { buildPlace } from '../../tests/helpers/factories' +import { buildPlace, buildTag } from '../../tests/helpers/factories' function setOnline(v: boolean): void { Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true }) @@ -66,6 +66,37 @@ describe('placeRepo — field origins offline', () => { }) }) +describe('placeRepo — tags offline', () => { + it('FE-REPO-PLACE-031: the queued body names the tags by id, the optimistic row carries the tags themselves', async () => { + const monument = buildTag({ id: 7, trip_id: 3, name: 'Monument' }) + await offlineDb.tripTags.put({ tripId: 3, tags: [monument] }) + + const { place } = await placeRepo.create(3, { name: 'Belem Tower', tags: [7, 99] }) + + // The trip's tag as the device knows it; an id it does not know shows nothing until the sync. + expect(place.tags).toEqual([monument]) + expect((await offlineDb.places.get(place.id))?.tags).toEqual([monument]) + expect((await queue())[0].body).toEqual({ name: 'Belem Tower', tags: [7, 99] }) + }) + + it('FE-REPO-PLACE-032: an update keeps a tag of the place the trip does not list, and a write without tags leaves them', async () => { + const zone = buildTag({ id: 8, trip_id: 3, name: 'Zone' }) + await offlineDb.tripTags.put({ tripId: 3, tags: [zone] }) + const personal = { id: 50, name: 'Hidden gem', color: '#f59e0b' } + await offlineDb.places.put(buildPlace({ id: 12, trip_id: 3, tags: [personal] })) + + const tagged = await placeRepo.update(3, 12, { tags: [50, 8] }) + expect(tagged.place.tags).toEqual([personal, zone]) + + const renamed = await placeRepo.update(3, 12, { name: 'Renamed' }) + expect(renamed.place.tags).toEqual([personal, zone]) + + const cleared = await placeRepo.update(3, 12, { tags: [] }) + expect(cleared.place.tags).toEqual([]) + expect((await offlineDb.places.get(12))?.tags).toEqual([]) + }) +}) + describe('placeRepo.update — offline', () => { it('FE-REPO-PLACE-003: merges into the cached row and sends the concurrency token', async () => { await offlineDb.places.put(buildPlace({ id: 90, trip_id: 3, name: 'Old', updated_at: '2026-01-01T00:00:00.000Z' })) diff --git a/client/src/repo/placeRepo.ts b/client/src/repo/placeRepo.ts index 849b968f8..0da4415e9 100644 --- a/client/src/repo/placeRepo.ts +++ b/client/src/repo/placeRepo.ts @@ -1,4 +1,5 @@ import { placesApi } from '../api/client' +import { cachedTripTags } from '../db/cacheTripTags' import { offlineDb, replaceTripRows, upsertPlaces } from '../db/offlineDb' import { mutationQueue, generateUUID, nextTempId } from '../sync/mutationQueue' import { isEffectivelyOffline } from '../sync/networkMode' @@ -8,11 +9,15 @@ import type { Place } from '../types' /** * What of a write the optimistic row keeps. `fieldOrigins` says which fields the * user typed; it travels in the queued body for the server's origin tracking and - * is no column of the place. + * is no column of the place. `tags` names the place's tags by id, while a row + * carries the tags themselves, so the row gets the ones the device knows by those + * ids: the trip's cached ones, and those the place had before. */ -function placeRow(data: Record): Record { - const { fieldOrigins: _origins, ...row } = data - return row +async function placeRow(tripId: number, data: Record, before?: Place): Promise> { + const { fieldOrigins: _origins, tags, ...row } = data + if (!Array.isArray(tags)) return row + const known = [...(await cachedTripTags(tripId)), ...(before?.tags ?? [])] + return { ...row, tags: tags.flatMap(id => known.find(tag => tag.id === id) ?? []) } } export const placeRepo = { @@ -35,7 +40,7 @@ export const placeRepo = { if (isEffectivelyOffline()) { const tempId = nextTempId() const tempPlace: Place = { - ...(placeRow(data) as Partial), + ...(await placeRow(Number(tripId), data) as Partial), id: tempId, trip_id: Number(tripId), name: (data.name as string) ?? 'New place', @@ -66,7 +71,7 @@ export const placeRepo = { // a row without it is invisible and never cleaned up. const optimistic: Place = { ...(existing ?? {} as Place), - ...(placeRow(data) as Partial), + ...(await placeRow(Number(tripId), data, existing) as Partial), id: Number(id), trip_id: Number(tripId), } diff --git a/client/src/repo/tripTagRepo.test.ts b/client/src/repo/tripTagRepo.test.ts new file mode 100644 index 000000000..b93d802b3 --- /dev/null +++ b/client/src/repo/tripTagRepo.test.ts @@ -0,0 +1,96 @@ +// FE-REPO-TRIPTAG-001 to FE-REPO-TRIPTAG-007: the tags a trip owns, read through to the +// server and kept on this device, read from there without a connection, and added +// online only. +import 'fake-indexeddb/auto'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildTag } from '../../tests/helpers/factories'; +import { clearAll, clearTripData, offlineDb } from '../db/offlineDb'; +import { isEffectivelyOffline } from '../sync/networkMode'; +import { OnlineOnlyError } from './onlineOnly'; +import { tripTagRepo } from './tripTagRepo'; + +const { client } = vi.hoisted(() => ({ client: { get: vi.fn(), post: vi.fn() } })); + +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) })); +vi.mock('../api/client', () => ({ default: client, apiClient: client })); + +const monument = buildTag({ id: 7, trip_id: 4, name: 'Monument' }); +const zone = buildTag({ id: 8, trip_id: 4, name: 'Zone' }); +/** An axios failure that never reached the server. */ +const networkError = () => Object.assign(new Error('Network Error'), { isAxiosError: true }); + +beforeEach(async () => { + await clearAll(); + vi.clearAllMocks(); + vi.mocked(isEffectivelyOffline).mockReturnValue(false); +}); + +describe('tripTagRepo', () => { + it('FE-REPO-TRIPTAG-001: reads the tags of the trip and keeps them on this device', async () => { + client.get.mockResolvedValue({ data: { tags: [monument, zone] } }); + + expect(await tripTagRepo.list('4')).toEqual({ tags: [monument, zone] }); + + expect(client.get).toHaveBeenCalledWith('/trips/4/tags'); + expect((await offlineDb.tripTags.get(4))?.tags).toEqual([monument, zone]); + }); + + it('FE-REPO-TRIPTAG-002: without a connection answers what the device last read, and nothing for a trip it never read', async () => { + await offlineDb.tripTags.put({ tripId: 4, tags: [monument] }); + vi.mocked(isEffectivelyOffline).mockReturnValue(true); + + expect(await tripTagRepo.list(4)).toEqual({ tags: [monument] }); + expect(await tripTagRepo.list(5)).toEqual({ tags: [] }); + expect(client.get).not.toHaveBeenCalled(); + }); + + it('FE-REPO-TRIPTAG-003: a request that never reached the server falls back to the device, a refusal does not', async () => { + await offlineDb.tripTags.put({ tripId: 4, tags: [zone] }); + client.get.mockRejectedValueOnce(networkError()); + expect(await tripTagRepo.list(4)).toEqual({ tags: [zone] }); + + const refused = Object.assign(new Error('Forbidden'), { isAxiosError: true, response: { status: 403 } }); + client.get.mockRejectedValueOnce(refused); + await expect(tripTagRepo.list(4)).rejects.toBe(refused); + }); + + it('FE-REPO-TRIPTAG-004: a new tag is sent to the trip and joins the list on this device, by name', async () => { + await offlineDb.tripTags.put({ tripId: 4, tags: [zone] }); + client.post.mockResolvedValue({ data: { tag: monument } }); + + expect(await tripTagRepo.create(4, { name: 'Monument', color: '#6366f1' })).toEqual(monument); + + expect(client.post).toHaveBeenCalledWith('/trips/4/tags', { name: 'Monument', color: '#6366f1' }); + expect((await offlineDb.tripTags.get(4))?.tags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + }); + + it('FE-REPO-TRIPTAG-005: the tag the trip has already under that name is not kept twice', async () => { + await offlineDb.tripTags.put({ tripId: 4, tags: [monument, zone] }); + client.post.mockResolvedValue({ data: { tag: zone } }); + + await tripTagRepo.create(4, { name: 'zone' }); + + expect((await offlineDb.tripTags.get(4))?.tags.map((tag) => tag.id)).toEqual([7, 8]); + }); + + it('FE-REPO-TRIPTAG-006: adding a tag needs a connection, and says so before anything is sent', async () => { + vi.mocked(isEffectivelyOffline).mockReturnValue(true); + + await expect(tripTagRepo.create(4, { name: 'Monument' })).rejects.toBeInstanceOf(OnlineOnlyError); + + expect(client.post).not.toHaveBeenCalled(); + expect(await offlineDb.tripTags.get(4)).toBeUndefined(); + }); + + it('FE-REPO-TRIPTAG-007: the tags kept for a trip go with it, and another trip keeps its own', async () => { + await offlineDb.tripTags.bulkPut([ + { tripId: 4, tags: [monument] }, + { tripId: 5, tags: [zone] }, + ]); + + await clearTripData(4); + + expect(await offlineDb.tripTags.get(4)).toBeUndefined(); + expect((await offlineDb.tripTags.get(5))?.tags).toEqual([zone]); + }); +}); diff --git a/client/src/repo/tripTagRepo.ts b/client/src/repo/tripTagRepo.ts new file mode 100644 index 000000000..f396ad6d3 --- /dev/null +++ b/client/src/repo/tripTagRepo.ts @@ -0,0 +1,46 @@ +import type { Tag, TripTagCreateRequest, TripTagListResponse, TripTagUpdateRequest } from '@trek/shared'; + +import { tripTagsApi } from '../api/tripTags'; +import { cachedTripTags, cacheTripTags } from '../db/cacheTripTags'; +import { withTripTag } from '../utils/placeTags'; +import { requireOnline } from './onlineOnly'; +import { onlineThenCache } from './withOfflineFallback'; + +/** + * The tags a trip owns. Reading them works offline, from the list the device last + * read. Adding one is online only, on purpose: the place it is then put on is saved + * with the tag's id, and a queued place cannot name a tag the server has not made. + * Putting a tag the trip already has on a place is the place's own write, which the + * offline queue holds like any other. + */ +export const tripTagRepo = { + async list(tripId: number | string): Promise { + const id = Number(tripId); + return onlineThenCache( + async () => { + const result = await tripTagsApi.list(id); + await cacheTripTags(id, result.tags); + return result; + }, + async () => ({ tags: await cachedTripTags(id) }) + ); + }, + + /** The new tag, or the one the trip already has under that name. */ + async create(tripId: number | string, body: TripTagCreateRequest): Promise { + requireOnline(); + const id = Number(tripId); + const { tag } = await tripTagsApi.create(id, body); + await cacheTripTags(id, withTripTag(await cachedTripTags(id), tag)); + return tag; + }, + + /** Renames or recolours a tag of the trip. Online only, like adding one: the tag is the trip's, not a place's own write. */ + async update(tripId: number | string, tagId: number, body: TripTagUpdateRequest): Promise { + requireOnline(); + const id = Number(tripId); + const { tag } = await tripTagsApi.update(id, tagId, body); + await cacheTripTags(id, withTripTag(await cachedTripTags(id), tag)); + return tag; + }, +}; diff --git a/client/src/store/flightLiveStore.test.ts b/client/src/store/flightLiveStore.test.ts new file mode 100644 index 000000000..002039806 --- /dev/null +++ b/client/src/store/flightLiveStore.test.ts @@ -0,0 +1,118 @@ +// FE-STORE-FLIGHTLIVE-001 to FE-STORE-FLIGHTLIVE-007 +import type { FlightLiveLeg } from '@trek/shared'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const listeners = new Set<(event: Record) => void>(); + +vi.mock('../api/flightLive', () => ({ flightLiveApi: { trip: vi.fn() } })); +vi.mock('../api/websocket', () => ({ + addListener: (fn: (event: Record) => void) => listeners.add(fn), + removeListener: (fn: (event: Record) => void) => listeners.delete(fn), +})); +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) })); + +import { flightLiveApi } from '../api/flightLive'; +import { isEffectivelyOffline } from '../sync/networkMode'; +import { legKey, useFlightLiveStore, watchFlightLive } from './flightLiveStore'; + +function leg(over: Partial = {}): FlightLiveLeg { + return { + reservation_id: 6, + leg_index: 0, + callsign: 'DLH400', + flight_number: 'LH 400', + service_date: '2026-06-11', + origin: { code: 'FRA', name: 'Frankfurt', lat: 50.03, lng: 8.57, timezone: 'Europe/Berlin' }, + destination: { code: 'JFK', name: 'New York JFK', lat: 40.64, lng: -73.78, timezone: 'America/New_York' }, + phase: 'scheduled', + scheduled_departure: '2026-06-11T11:50:00.000Z', + scheduled_arrival: '2026-06-11T20:35:00.000Z', + departed_at: null, + landed_at: null, + estimated_arrival: null, + departure_delay_min: null, + arrival_delay_min: null, + progress: null, + distance_total_km: null, + distance_remaining_km: null, + position: null, + aircraft: null, + last_seen_at: null, + fetched_at: null, + stale: false, + source: null, + ...over, + }; +} + +beforeEach(() => { + useFlightLiveStore.setState({ trips: {} }); + listeners.clear(); + vi.mocked(flightLiveApi.trip).mockReset(); + vi.mocked(isEffectivelyOffline).mockReturnValue(false); +}); + +describe('flightLiveStore', () => { + it('FE-STORE-FLIGHTLIVE-001: keeps a valid answer by leg', async () => { + vi.mocked(flightLiveApi.trip).mockResolvedValue({ enabled: true, attribution: 'adsb.lol', flights: [leg()] }); + await useFlightLiveStore.getState().load(1); + const trip = useFlightLiveStore.getState().trips[1]; + expect(trip.attribution).toBe('adsb.lol'); + expect(trip.legs[legKey(6, 0)].callsign).toBe('DLH400'); + }); + + it('FE-STORE-FLIGHTLIVE-002: ignores a malformed answer and a failed request', async () => { + vi.mocked(flightLiveApi.trip).mockResolvedValueOnce({ nope: true }); + await useFlightLiveStore.getState().load(1); + vi.mocked(flightLiveApi.trip).mockRejectedValueOnce(new Error('down')); + await useFlightLiveStore.getState().load(1); + expect(useFlightLiveStore.getState().trips[1]).toBeUndefined(); + }); + + it('FE-STORE-FLIGHTLIVE-003: asks nothing offline', async () => { + vi.mocked(isEffectivelyOffline).mockReturnValue(true); + await useFlightLiveStore.getState().load(1); + expect(flightLiveApi.trip).not.toHaveBeenCalled(); + }); + + it('FE-STORE-FLIGHTLIVE-004: merges a push for its trip only', async () => { + vi.mocked(flightLiveApi.trip).mockResolvedValue({ enabled: true, attribution: null, flights: [leg()] }); + await useFlightLiveStore.getState().load(1); + const stop = watchFlightLive(1); + for (const fn of listeners) fn({ type: 'flight:live', tripId: 2, flights: [leg({ phase: 'airborne' })] }); + expect(useFlightLiveStore.getState().trips[1].legs[legKey(6, 0)].phase).toBe('scheduled'); + for (const fn of listeners) + fn({ type: 'flight:live', tripId: 1, flights: [leg({ phase: 'airborne' }), { broken: true }] }); + expect(useFlightLiveStore.getState().trips[1].legs[legKey(6, 0)].phase).toBe('airborne'); + stop(); + expect(listeners.size).toBe(0); + }); + + it('FE-STORE-FLIGHTLIVE-005: a push for a trip never loaded is dropped', () => { + useFlightLiveStore.getState().merge(3, [leg()]); + expect(useFlightLiveStore.getState().trips[3]).toBeUndefined(); + }); + + it('FE-STORE-FLIGHTLIVE-006: an answer with the switch off keeps no legs', async () => { + vi.mocked(flightLiveApi.trip).mockResolvedValue({ enabled: false, attribution: null, flights: [] }); + await useFlightLiveStore.getState().load(1); + expect(useFlightLiveStore.getState().trips[1]).toEqual({ enabled: false, attribution: null, legs: {} }); + }); + + it('FE-STORE-FLIGHTLIVE-007: a read keeps a push that arrived while it was under way', async () => { + vi.mocked(flightLiveApi.trip).mockResolvedValue({ + enabled: true, + attribution: null, + flights: [leg({ fetched_at: '2026-06-11T12:00:00.000Z' })], + }); + await useFlightLiveStore.getState().load(1); + useFlightLiveStore.getState().merge(1, [leg({ phase: 'airborne', fetched_at: '2026-06-11T12:05:00.000Z' })]); + vi.mocked(flightLiveApi.trip).mockResolvedValue({ + enabled: true, + attribution: null, + flights: [leg({ fetched_at: '2026-06-11T12:01:00.000Z' })], + }); + await useFlightLiveStore.getState().load(1); + expect(useFlightLiveStore.getState().trips[1].legs[legKey(6, 0)].phase).toBe('airborne'); + }); +}); diff --git a/client/src/store/flightLiveStore.ts b/client/src/store/flightLiveStore.ts new file mode 100644 index 000000000..aa5b5f9dc --- /dev/null +++ b/client/src/store/flightLiveStore.ts @@ -0,0 +1,107 @@ +import { flightLiveLegSchema, tripFlightLiveResponseSchema, type FlightLiveLeg } from '@trek/shared'; +import { create } from 'zustand'; +import { useShallow } from 'zustand/react/shallow'; +import { flightLiveApi } from '../api/flightLive'; +import { addListener, removeListener } from '../api/websocket'; +import { isEffectivelyOffline } from '../sync/networkMode'; + +/** + * Live flight states per trip (GET /trips/:id/flights/live plus the + * `flight:live` pushes). Kept apart from the trip store on purpose: it is + * transient feed data with no offline copy, so it never goes through the + * repo/Dexie layer, and an old state is worth nothing once the flight is over. + */ + +interface TripFlightLive { + enabled: boolean; + attribution: string | null; + /** By `legKey`. */ + legs: Record; +} + +interface FlightLiveState { + trips: Record; + load: (tripId: number) => Promise; + merge: (tripId: number, legs: FlightLiveLeg[]) => void; +} + +export const legKey = (reservationId: number, legIndex: number): string => `${reservationId}:${legIndex}`; + +const byKey = (legs: FlightLiveLeg[]): Record => + Object.fromEntries(legs.map((leg) => [legKey(leg.reservation_id, leg.leg_index), leg])); + +/** The incoming legs, except where the one already held was fetched later. */ +function newest(held: Record | undefined, incoming: Record) { + if (!held) return incoming; + const out: Record = {}; + for (const [key, leg] of Object.entries(incoming)) { + const mine = held[key]; + out[key] = mine && (mine.fetched_at ?? '') > (leg.fetched_at ?? '') ? mine : leg; + } + return out; +} + +export const useFlightLiveStore = create((set) => ({ + trips: {}, + + load: async (tripId) => { + if (!tripId || isEffectivelyOffline()) return; + try { + const parsed = tripFlightLiveResponseSchema.safeParse(await flightLiveApi.trip(tripId)); + // A server without the feature (older version) or a malformed answer leaves + // the cards on their schedule-only look rather than breaking the sheet. + if (!parsed.success) return; + const { enabled, attribution, flights } = parsed.data; + // A push that landed while this read was under way is newer than its answer and stays. + set((state) => ({ + trips: { + ...state.trips, + [tripId]: { enabled, attribution, legs: newest(state.trips[tripId]?.legs, byKey(flights)) }, + }, + })); + } catch { + // Offline or the feed is down: the last known state stays, marked stale by its age. + } + }, + + merge: (tripId, legs) => + set((state) => { + const current = state.trips[tripId]; + if (!current) return state; + return { trips: { ...state.trips, [tripId]: { ...current, legs: { ...current.legs, ...byKey(legs) } } } }; + }), +})); + +/** The live state of one leg, or null while there is none. */ +export function useFlightLiveLeg(tripId: number, reservationId: number, legIndex: number): FlightLiveLeg | null { + return useFlightLiveStore((s) => s.trips[tripId]?.legs[legKey(reservationId, legIndex)] ?? null); +} + +/** The live legs of one booking in leg order; empty while TREK follows none of them. */ +export function useFlightLiveLegs(tripId: number, reservationId: number): FlightLiveLeg[] { + return useFlightLiveStore( + useShallow((s) => + Object.values(s.trips[tripId]?.legs ?? {}) + .filter((leg) => leg.reservation_id === reservationId) + .sort((a, b) => a.leg_index - b.leg_index) + ) + ); +} + +export function useFlightLiveAttribution(tripId: number): string | null { + return useFlightLiveStore((s) => (s.trips[tripId]?.enabled ? s.trips[tripId].attribution : null)); +} + +/** Applies `flight:live` pushes for the given trip. Returns the function that stops listening. */ +export function watchFlightLive(tripId: number): () => void { + const onEvent = (event: Record) => { + if (event?.type !== 'flight:live' || Number(event.tripId) !== tripId || !Array.isArray(event.flights)) return; + const legs = event.flights.flatMap((raw) => { + const leg = flightLiveLegSchema.safeParse(raw); + return leg.success ? [leg.data] : []; + }); + if (legs.length > 0) useFlightLiveStore.getState().merge(tripId, legs); + }; + addListener(onEvent); + return () => removeListener(onEvent); +} diff --git a/client/src/store/mailIngestStore.test.ts b/client/src/store/mailIngestStore.test.ts new file mode 100644 index 000000000..2da9c890a --- /dev/null +++ b/client/src/store/mailIngestStore.test.ts @@ -0,0 +1,111 @@ +// FE-STORE-MAILINGEST-001 to FE-STORE-MAILINGEST-005 +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../api/mailIngest', () => ({ + mailIngestApi: { settings: vi.fn(), inbox: vi.fn(), inboxCount: vi.fn(), act: vi.fn() }, +})); +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) })); +const listeners = vi.hoisted(() => new Set<(event: Record) => void>()); +vi.mock('../api/websocket', () => ({ + addListener: (fn: (event: Record) => void) => listeners.add(fn), + removeListener: (fn: (event: Record) => void) => listeners.delete(fn), +})); + +import { mailIngestApi } from '../api/mailIngest'; +import { useMailIngestStore, watchMailInbox } from './mailIngestStore'; + +const candidate = (id: number, resolution = 'pending') => ({ + id, + message_id: 10 + id, + item: null, + source: null, + uncertain_fields: [], + checks: {}, + suggested_trip: null, + suggested_new_trip: null, + resolution, + reason: 'not_a_booking', + resolved_trip_id: null, + reservation_ids: [], + file_ids: [], + created_at: '2026-06-01T10:00:00.000Z', + resolved_at: null, + undo_until: null, +}); +const entry = (id: number) => ({ + ...candidate(id), + message: { + id: 10 + id, + transport: 'upload', + subject: null, + received_at: '2026-06-01T09:59:00.000Z', + status: 'processed', + reason: null, + hints: [], + ai_used: false, + trip_id: null, + attachments: [], + forwarding_code: null, + }, +}); + +beforeEach(() => { + useMailIngestStore.setState({ settings: null, entries: [], nextBefore: null, pending: 0, loadingInbox: false }); + vi.mocked(mailIngestApi.inbox).mockReset(); + vi.mocked(mailIngestApi.act).mockReset(); +}); + +describe('mailIngestStore', () => { + it('FE-STORE-MAILINGEST-001: reads the open entries and the count', async () => { + vi.mocked(mailIngestApi.inbox).mockResolvedValue({ entries: [entry(1), entry(2)], pending: 2, next_before: null }); + await useMailIngestStore.getState().loadInbox(); + expect(useMailIngestStore.getState().entries.map((e) => e.id)).toEqual([1, 2]); + expect(useMailIngestStore.getState().pending).toBe(2); + }); + + it('FE-STORE-MAILINGEST-002: a further page is appended, a malformed answer is ignored', async () => { + vi.mocked(mailIngestApi.inbox).mockResolvedValueOnce({ entries: [entry(1)], pending: 2, next_before: 1 }); + await useMailIngestStore.getState().loadInbox(); + vi.mocked(mailIngestApi.inbox).mockResolvedValueOnce({ entries: [entry(2)], pending: 2, next_before: null }); + await useMailIngestStore.getState().loadInbox(true); + vi.mocked(mailIngestApi.inbox).mockResolvedValueOnce({ nope: true }); + await useMailIngestStore.getState().loadInbox(true); + expect(useMailIngestStore.getState().entries.map((e) => e.id)).toEqual([1, 2]); + }); + + it('FE-STORE-MAILINGEST-003: a decided entry leaves the list and the count', async () => { + useMailIngestStore.setState({ entries: [entry(1), entry(2)] as never, pending: 2 }); + vi.mocked(mailIngestApi.act).mockResolvedValue({ candidate: candidate(1, 'discarded') }); + await useMailIngestStore.getState().act(1, 'discard'); + expect(useMailIngestStore.getState().entries.map((e) => e.id)).toEqual([2]); + expect(useMailIngestStore.getState().pending).toBe(1); + }); + + it('FE-STORE-MAILINGEST-004: an entry still open after an action stays, updated', async () => { + useMailIngestStore.setState({ entries: [entry(1)] as never, pending: 1 }); + vi.mocked(mailIngestApi.act).mockResolvedValue({ candidate: { ...candidate(1), reason: 'ai_provider_error' } }); + await useMailIngestStore.getState().act(1, 'apply'); + expect(useMailIngestStore.getState().entries[0].reason).toBe('ai_provider_error'); + expect(useMailIngestStore.getState().pending).toBe(1); + }); + + it('FE-STORE-MAILINGEST-005: the server inbox events move the count, read the list again and reload the settings', async () => { + vi.mocked(mailIngestApi.inbox).mockResolvedValue({ entries: [entry(3)], pending: 1, next_before: null }); + vi.mocked(mailIngestApi.settings).mockResolvedValue({ nope: true }); + const stop = watchMailInbox(); + const send = (event: Record) => listeners.forEach((fn) => fn(event)); + + send({ type: 'mailInbox:changed', pending: 1 }); + expect(useMailIngestStore.getState().pending).toBe(1); + await vi.waitFor(() => expect(useMailIngestStore.getState().entries.map((e) => e.id)).toEqual([3])); + + send({ type: 'mailInbox:settings' }); + expect(mailIngestApi.settings).toHaveBeenCalled(); + + // A malformed event changes nothing, and after stopping nothing is heard. + send({ type: 'mailInbox:changed', pending: 'many' }); + expect(useMailIngestStore.getState().pending).toBe(1); + stop(); + expect(listeners.size).toBe(0); + }); +}); diff --git a/client/src/store/mailIngestStore.ts b/client/src/store/mailIngestStore.ts new file mode 100644 index 000000000..23f7525d8 --- /dev/null +++ b/client/src/store/mailIngestStore.ts @@ -0,0 +1,106 @@ +import type { MailIngestCandidate, MailIngestInboxEntry, MailIngestSettingsResponse } from '@trek/shared'; +import { create } from 'zustand'; +import type { MailIngestAction } from '../api/mailIngest'; +import { addListener, removeListener } from '../api/websocket'; +import { mailIngestRepo } from '../repo/mailIngestRepo'; +import { isEffectivelyOffline } from '../sync/networkMode'; + +/** + * The booking mail import as the person sees it: their settings and address, + * and the inbox of bookings that wait for them. Online only on purpose: every + * action asks the server to decide (which trip, whether it is a duplicate), so + * there is nothing an offline copy could do. The pending count drives the badge + * on the menu entry, on the desktop and on the phone alike. + */ +interface MailIngestState { + settings: MailIngestSettingsResponse | null; + entries: MailIngestInboxEntry[]; + nextBefore: number | null; + pending: number; + loadingInbox: boolean; + loadSettings: () => Promise; + setSettings: (settings: MailIngestSettingsResponse) => void; + loadCount: () => Promise; + loadInbox: (more?: boolean) => Promise; + /** Runs an action on an entry; the entry leaves the open list once it is decided. */ + act: (candidateId: number, action: MailIngestAction, body?: Record) => Promise; +} + +const OPEN = new Set(['pending']); + +export const useMailIngestStore = create((set, get) => ({ + settings: null, + entries: [], + nextBefore: null, + pending: 0, + loadingInbox: false, + + loadSettings: async () => { + if (isEffectivelyOffline()) return; + try { + const settings = await mailIngestRepo.settings(); + set({ settings, pending: settings.pending }); + } catch { + // Without an answer the menus keep what they showed; the next sign-in or event reads it again. + } + }, + + setSettings: (settings) => set({ settings, pending: settings.pending }), + + loadCount: async () => { + if (isEffectivelyOffline()) return; + try { + set({ pending: await mailIngestRepo.inboxCount() }); + } catch { + // The badge keeps its last count until the next event brings a new one. + } + }, + + loadInbox: async (more = false) => { + if (isEffectivelyOffline() || get().loadingInbox) return; + set({ loadingInbox: true }); + try { + const before = more ? (get().nextBefore ?? undefined) : undefined; + const { entries, pending, next_before } = await mailIngestRepo.inbox(before); + set((state) => ({ entries: more ? [...state.entries, ...entries] : entries, pending, nextBefore: next_before })); + } catch { + // The inbox stays as it was; the next open reads it again. + } finally { + set({ loadingInbox: false }); + } + }, + + act: async (candidateId, action, body = {}) => { + const candidate = await mailIngestRepo.act(candidateId, action, body); + set((state) => { + const stillOpen = OPEN.has(candidate.resolution); + const entries = state.entries.flatMap((entry) => + entry.id !== candidate.id ? [entry] : stillOpen ? [{ ...entry, ...candidate }] : [] + ); + const removed = state.entries.length - entries.length; + return { entries, pending: Math.max(0, state.pending - removed) }; + }); + return candidate; + }, +})); + +/** + * Keeps the inbox current while the app is open: the server says when the + * person's open count changed (a mail read, an entry decided on another + * device) and when their import settings did. The count moves at once; a + * list already read is read again, so an open inbox shows the new entry + * without a reload. Mounted once per signed-in shell (Navbar, MMailInboxHost). + */ +export function watchMailInbox(): () => void { + const onEvent = (event: Record) => { + const store = useMailIngestStore.getState(); + if (event?.type === 'mailInbox:changed' && typeof event.pending === 'number') { + useMailIngestStore.setState({ pending: event.pending }); + if (store.entries.length > 0 || event.pending > 0) void store.loadInbox(); + } else if (event?.type === 'mailInbox:settings') { + void store.loadSettings(); + } + }; + addListener(onEvent); + return () => removeListener(onEvent); +} diff --git a/client/src/store/slices/assignmentsSlice.ts b/client/src/store/slices/assignmentsSlice.ts index 3f8b78d07..cd057e7ba 100644 --- a/client/src/store/slices/assignmentsSlice.ts +++ b/client/src/store/slices/assignmentsSlice.ts @@ -11,6 +11,8 @@ type GetState = StoreApi['getState'] export interface AssignmentsSlice { setAssignmentEndDay: (tripId: number | string, dayId: number, assignmentId: number, endDay: boolean) => Promise + /** The stay of one visit (#3092); null reads the place's duration_minutes again. */ + setAssignmentStay: (tripId: number | string, dayId: number, assignmentId: number, stayMinutes: number | null) => Promise setAssignmentRouteExcluded: (tripId: number | string, dayId: number, assignmentId: number, excluded: boolean) => Promise setAssignmentTimes: (tripId: number | string, dayId: number, assignmentId: number, times: AssignmentTimes) => Promise setAssignmentNotes: (tripId: number | string, dayId: number, assignmentId: number, notes: string | null) => Promise @@ -25,6 +27,38 @@ export interface AssignmentsSlice { setAssignments: (assignments: AssignmentsMap) => void } +/** + * One field of a saved visit on its day, written optimistically: shown at once, settled + * on what the save answers, and put back when the save is refused. `read` is how the + * field is read off a row, so an absent value settles the same way every time. + */ +async function writeVisitField( + set: SetState, + get: GetState, + { dayId, assignmentId, field, value, read, save }: { + dayId: number + assignmentId: number + field: K + value: Assignment[K] + read: (a: Assignment) => Assignment[K] + save: (assignment: Assignment) => Promise + }, +): Promise { + const key = String(dayId) + const assignment = get().assignments[key]?.find(a => a.id === assignmentId) + if (!assignment || assignmentId < 0) return + const apply = (next: Assignment[K]) => set(state => ({ + assignments: { ...state.assignments, [key]: (state.assignments[key] || []).map(a => a.id === assignmentId ? { ...a, [field]: next } : a) }, + })) + apply(value) + try { + apply(read(await save(assignment))) + } catch (err: unknown) { + apply(read(assignment)) + throw err + } +} + export const createAssignmentsSlice = (set: SetState, get: GetState): AssignmentsSlice => ({ setAssignmentEndDay: async (tripId, dayId, assignmentId, endDay) => { const assignment = get().assignments[String(dayId)]?.find(a => a.id === assignmentId) @@ -43,21 +77,14 @@ export const createAssignmentsSlice = (set: SetState, get: GetState): Assignment throw err } }, - setAssignmentRouteExcluded: async (tripId, dayId, assignmentId, excluded) => { - const assignment = get().assignments[String(dayId)]?.find(a => a.id === assignmentId) - if (!assignment || assignmentId < 0) return - const apply = (value: boolean) => set(state => ({ - assignments: { ...state.assignments, [String(dayId)]: (state.assignments[String(dayId)] || []).map(a => a.id === assignmentId ? { ...a, route_excluded: value } : a) }, - })) - apply(excluded) - try { - const saved = await assignmentRepo.setRouteExcluded(tripId, assignment, excluded) - apply(saved.route_excluded === true) - } catch (err: unknown) { - apply(assignment.route_excluded === true) - throw err - } - }, + setAssignmentStay: (tripId, dayId, assignmentId, stayMinutes) => writeVisitField(set, get, { + dayId, assignmentId, field: 'stay_minutes', value: stayMinutes, read: a => a.stay_minutes ?? null, + save: assignment => assignmentRepo.setStay(tripId, assignment, stayMinutes), + }), + setAssignmentRouteExcluded: (tripId, dayId, assignmentId, excluded) => writeVisitField(set, get, { + dayId, assignmentId, field: 'route_excluded', value: excluded, read: a => a.route_excluded === true, + save: assignment => assignmentRepo.setRouteExcluded(tripId, assignment, excluded), + }), setAssignmentTimes: async (tripId, dayId, assignmentId, times) => { const assignment = get().assignments[String(dayId)]?.find(a => a.id === assignmentId) if (!assignment || assignmentId < 0) return diff --git a/client/src/store/slices/packingSlice.ts b/client/src/store/slices/packingSlice.ts index cd0c1c556..3ffc92c84 100644 --- a/client/src/store/slices/packingSlice.ts +++ b/client/src/store/slices/packingSlice.ts @@ -21,7 +21,8 @@ export interface PackingSlice { // Three-tier sharing (#858) setPackingItemSharing: (tripId: number | string, id: number, visibility: 'common' | 'personal' | 'shared', recipientIds: number[]) => Promise clonePackingItem: (tripId: number | string, id: number) => Promise - addPackingContributor: (tripId: number | string, id: number) => Promise + /** Without a userId the caller pledges themselves; with one, that member is put down as a bringer (#3098). */ + addPackingContributor: (tripId: number | string, id: number, userId?: number) => Promise removePackingContributor: (tripId: number | string, id: number, userId: number) => Promise } @@ -141,9 +142,9 @@ export const createPackingSlice = (set: SetState, get: GetState): PackingSlice = } }, - addPackingContributor: async (tripId, id) => { + addPackingContributor: async (tripId, id, userId) => { try { - const result = await packingApi.addContributor(tripId, id) + const result = await packingApi.addContributor(tripId, id, userId) set(state => ({ packingItems: state.packingItems.map(i => i.id === id ? result.item : i) })) } catch (err: unknown) { notify(getApiErrorMessage(err, 'Error joining item'), 'error') diff --git a/client/src/store/slices/remoteEventHandler.ts b/client/src/store/slices/remoteEventHandler.ts index f7903ff3c..e52333299 100644 --- a/client/src/store/slices/remoteEventHandler.ts +++ b/client/src/store/slices/remoteEventHandler.ts @@ -719,6 +719,13 @@ export const STORE_REFRESHES: Partial> const tripId = get().trip?.id if (tripId) void get().reloadPackingItems(tripId) }), + // A tag of the trip added, renamed or deleted elsewhere: the event says only + // that the list changed, and the read takes a rename or a delete into the + // places that carry the tag. + 'tripTags:changed': get => refreshOncePerBurst('tripTags', () => { + const tripId = get().trip?.id + if (tripId) void get().loadTripTags(tripId) + }), } /** diff --git a/client/src/store/slices/tripTagsSlice.test.ts b/client/src/store/slices/tripTagsSlice.test.ts new file mode 100644 index 000000000..2d987a111 --- /dev/null +++ b/client/src/store/slices/tripTagsSlice.test.ts @@ -0,0 +1,135 @@ +// FE-STORE-TRIPTAGS-001 to FE-STORE-TRIPTAGS-006: the tags of the open trip in the store, +// and what a tag renamed or deleted elsewhere does to the places that carry it. +import 'fake-indexeddb/auto'; +import { http, HttpResponse } from 'msw'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { buildAssignment, buildPlace, buildTag, buildTrip } from '../../../tests/helpers/factories'; +import { server } from '../../../tests/helpers/msw/server'; +import { resetAllStores } from '../../../tests/helpers/store'; +import { clearAll } from '../../db/offlineDb'; +import { OnlineOnlyError } from '../../repo/onlineOnly'; +import { useTripStore } from '../tripStore'; + +const monument = buildTag({ id: 7, trip_id: 5, name: 'Monument', color: '#6366f1' }); +const zone = buildTag({ id: 8, trip_id: 5, name: 'Zone', color: '#10b981' }); + +function setOnline(online: boolean): void { + Object.defineProperty(navigator, 'onLine', { value: online, writable: true, configurable: true }); +} + +/** What the server lists as the tags of trip 5. */ +function serve(tags: unknown[]): void { + server.use(http.get('/api/trips/5/tags', () => HttpResponse.json({ tags }))); +} + +beforeEach(async () => { + await clearAll(); + resetAllStores(); + setOnline(true); + useTripStore.setState({ trip: buildTrip({ id: 5 }) }); +}); + +afterEach(() => { + setOnline(true); +}); + +describe('tripTagsSlice', () => { + it('FE-STORE-TRIPTAGS-001: reads the tags of the open trip, and drops an answer for a trip that is no longer open', async () => { + serve([monument, zone]); + await useTripStore.getState().loadTripTags(5); + expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + + server.use( + http.get('/api/trips/6/tags', () => HttpResponse.json({ tags: [buildTag({ id: 9, name: 'Other trip' })] })) + ); + await useTripStore.getState().loadTripTags(6); + expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + }); + + it('FE-STORE-TRIPTAGS-002: a tag renamed or deleted elsewhere is taken into the places and visits that carry it', async () => { + const tagged = buildPlace({ + id: 21, + trip_id: 5, + tags: [ + { id: 7, name: 'Monument', color: '#6366f1' }, + { id: 8, name: 'Zone' }, + ], + }); + const untouched = buildPlace({ id: 22, trip_id: 5, tags: [{ id: 50, name: 'Hidden gem' }] }); + const visit = buildAssignment({ id: 31, place: { ...tagged } }); + const otherVisit = buildAssignment({ id: 32, place: { ...untouched } }); + useTripStore.setState({ + tripTags: [monument, zone], + places: [tagged, untouched], + assignments: { '11': [visit, otherVisit] }, + placesCategoryFilter: new Set(['4', 'tag:7', 'tag:8']), + }); + serve([{ ...monument, name: 'Landmark', color: '#ef4444' }]); + + await useTripStore.getState().loadTripTags(5); + + const state = useTripStore.getState(); + expect(state.tripTags.map((tag) => tag.name)).toEqual(['Landmark']); + expect(state.places[0].tags).toEqual([{ id: 7, name: 'Landmark', color: '#ef4444' }]); + expect(state.assignments['11'][0].place.tags).toEqual([{ id: 7, name: 'Landmark', color: '#ef4444' }]); + // What carries none of the changed tags is the same object as before. + expect(state.places[1]).toBe(untouched); + expect(state.assignments['11'][1]).toBe(otherVisit); + // The deleted tag no longer filters; the renamed one and the category still do. + expect([...state.placesCategoryFilter]).toEqual(['4', 'tag:7']); + }); + + it('FE-STORE-TRIPTAGS-003: a reading that changes no tag on a place leaves the places and the filter as they are', async () => { + const tagged = buildPlace({ id: 21, trip_id: 5, tags: [{ id: 7, name: 'Monument', color: '#6366f1' }] }); + const filter = new Set(['tag:7']); + const assignments = { '11': [buildAssignment({ id: 31, place: { ...tagged } })] }; + useTripStore.setState({ tripTags: [monument], places: [tagged], assignments, placesCategoryFilter: filter }); + serve([monument, zone]); + + await useTripStore.getState().loadTripTags(5); + + const state = useTripStore.getState(); + expect(state.tripTags).toHaveLength(2); + expect(state.places[0]).toBe(tagged); + expect(state.assignments).toBe(assignments); + expect(state.placesCategoryFilter).toBe(filter); + }); + + it('FE-STORE-TRIPTAGS-004: a reading the server refuses keeps the tags on screen', async () => { + useTripStore.setState({ tripTags: [monument] }); + server.use(http.get('/api/trips/5/tags', () => HttpResponse.json({ error: 'Trip not found' }, { status: 404 }))); + + await useTripStore.getState().loadTripTags(5); + + expect(useTripStore.getState().tripTags).toEqual([monument]); + }); + + it('FE-STORE-TRIPTAGS-005: a new tag joins the list by name, and the one the trip has already is not listed twice', async () => { + useTripStore.setState({ tripTags: [zone] }); + let sent: unknown; + server.use( + http.post('/api/trips/5/tags', async ({ request }) => { + sent = await request.json(); + return HttpResponse.json({ tag: monument }, { status: 201 }); + }) + ); + + expect(await useTripStore.getState().addTripTag(5, { name: 'Monument', color: '#6366f1' })).toEqual(monument); + expect(sent).toEqual({ name: 'Monument', color: '#6366f1' }); + expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + + await useTripStore.getState().addTripTag(5, { name: 'monument' }); + expect(useTripStore.getState().tripTags.map((tag) => tag.id)).toEqual([7, 8]); + }); + + it('FE-STORE-TRIPTAGS-006: without a connection a new tag is refused and the list stays; another trip starts without tags', async () => { + useTripStore.setState({ tripTags: [zone] }); + setOnline(false); + + await expect(useTripStore.getState().addTripTag(5, { name: 'Monument' })).rejects.toBeInstanceOf(OnlineOnlyError); + expect(useTripStore.getState().tripTags).toEqual([zone]); + + useTripStore.getState().resetTrip(); + expect(useTripStore.getState().tripTags).toEqual([]); + }); +}); diff --git a/client/src/store/slices/tripTagsSlice.ts b/client/src/store/slices/tripTagsSlice.ts new file mode 100644 index 000000000..70d92af03 --- /dev/null +++ b/client/src/store/slices/tripTagsSlice.ts @@ -0,0 +1,72 @@ +import type { Tag, TripTagCreateRequest, TripTagUpdateRequest } from '@trek/shared'; +import type { StoreApi } from 'zustand'; + +import { tripTagRepo } from '../../repo/tripTagRepo'; +import { withoutTagFilters } from '../../utils/placesFilter'; +import { tagChanges, withTagChanges, withTripTag } from '../../utils/placeTags'; +import type { TripStoreState } from '../tripStore'; + +type SetState = StoreApi['setState']; +type GetState = StoreApi['getState']; + +export interface TripTagsSlice { + /** The tags the open trip owns, the same list for everybody on it (`tags` holds the user's personal ones). */ + tripTags: Tag[]; + /** Reads the trip's tags again: on a reconnect, and when they changed elsewhere (`tripTags:changed`). */ + loadTripTags: (tripId: number | string) => Promise; + /** Adds a tag to the trip, or hands back the one it already has under that name. Needs a connection. */ + addTripTag: (tripId: number | string, data: TripTagCreateRequest) => Promise; + /** Renames or recolours one of the trip's tags, and takes the change into the places carrying it. Needs a connection. */ + updateTripTag: (tripId: number | string, tagId: number, data: TripTagUpdateRequest) => Promise; +} + +/** + * The store once the trip's tags were read again. A place carries a copy of each of + * its tags, so a tag renamed, recoloured or deleted elsewhere is taken into the places + * and into the visits that embed them, and a deleted one leaves the category filter. + */ +function withTripTags(state: TripStoreState, tags: Tag[]): Partial { + const changes = tagChanges(state.tripTags, tags); + if (!changes) return { tripTags: tags }; + return { + tripTags: tags, + places: state.places.map((place) => withTagChanges(place, changes)), + assignments: Object.fromEntries( + Object.entries(state.assignments).map(([dayId, visits]) => [ + dayId, + visits.map((visit) => { + const place = visit.place && withTagChanges(visit.place, changes); + return place === visit.place ? visit : { ...visit, place }; + }), + ]) + ), + placesCategoryFilter: withoutTagFilters(state.placesCategoryFilter, changes.removed), + }; +} + +export const createTripTagsSlice = (set: SetState, get: GetState): TripTagsSlice => ({ + tripTags: [], + + loadTripTags: async (tripId) => { + try { + const { tags } = await tripTagRepo.list(tripId); + // Another trip was opened while the answer was on its way. + if (String(get().trip?.id) !== String(tripId)) return; + set((state) => withTripTags(state, tags)); + } catch { + // The tags on screen stay; the next reload or reconnect reads them again. + } + }, + + addTripTag: async (tripId, data) => { + const tag = await tripTagRepo.create(tripId, data); + set((state) => ({ tripTags: withTripTag(state.tripTags, tag) })); + return tag; + }, + + updateTripTag: async (tripId, tagId, data) => { + const tag = await tripTagRepo.update(tripId, tagId, data); + set((state) => withTripTags(state, withTripTag(state.tripTags, tag))); + return tag; + }, +}); diff --git a/client/src/store/tripStore.ts b/client/src/store/tripStore.ts index 80c975bbf..2ce87b045 100644 --- a/client/src/store/tripStore.ts +++ b/client/src/store/tripStore.ts @@ -10,6 +10,7 @@ import { todoRepo } from '../repo/todoRepo' import { budgetRepo } from '../repo/budgetRepo' import { reservationRepo } from '../repo/reservationRepo' import { fileRepo } from '../repo/fileRepo' +import { tripTagRepo } from '../repo/tripTagRepo' import { isEffectivelyOnline } from '../sync/networkMode' import { createPlacesSlice } from './slices/placesSlice' import { createAssignmentsSlice } from './slices/assignmentsSlice' @@ -20,6 +21,7 @@ import { createTodoSlice } from './slices/todoSlice' import { createBudgetSlice } from './slices/budgetSlice' import { createReservationsSlice } from './slices/reservationsSlice' import { createFilesSlice } from './slices/filesSlice' +import { createTripTagsSlice } from './slices/tripTagsSlice' import { handleRemoteEvent } from './slices/remoteEventHandler' import type { Trip, Day, Place, Assignment, DayNote, PackingItem, TodoItem, @@ -36,6 +38,7 @@ import type { TodoSlice } from './slices/todoSlice' import type { BudgetSlice } from './slices/budgetSlice' import type { ReservationsSlice } from './slices/reservationsSlice' import type { FilesSlice } from './slices/filesSlice' +import type { TripTagsSlice } from './slices/tripTagsSlice' import type { PlacesRatingFloor } from '../utils/placesFilter' /** The part of the world the trip's plan map shows, as its last move left it. */ @@ -63,7 +66,8 @@ export interface TripStoreState TodoSlice, BudgetSlice, ReservationsSlice, - FilesSlice { + FilesSlice, + TripTagsSlice { trip: Trip | null days: Day[] places: Place[] @@ -152,7 +156,7 @@ export const useTripStore = create((set, get) => ({ // Clear every trip-scoped slice so switching trips (or losing access to one) // can never leave a previous trip's data visible. Global tags/categories are - // left intact. Called at the top of loadTrip. + // left intact; the trip's own tags go with it. Called at the top of loadTrip. resetTrip: () => set({ trip: null, days: [], @@ -164,6 +168,7 @@ export const useTripStore = create((set, get) => ({ budgetItems: [], files: [], reservations: [], + tripTags: [], selectedDayId: null, placesFilter: 'all', placesCategoryFilter: new Set(), @@ -179,7 +184,7 @@ export const useTripStore = create((set, get) => ({ get().resetTrip() set({ isLoading: true, error: null }) try { - const [tripData, daysData, placesData, packingData, todoData, budgetData, reservationsData, filesData, tagsData, categoriesData] = await Promise.all([ + const [tripData, daysData, placesData, packingData, todoData, budgetData, reservationsData, filesData, tagsData, categoriesData, tripTagsData] = await Promise.all([ tripRepo.get(tripId), dayRepo.list(tripId), placeRepo.list(tripId), @@ -197,6 +202,9 @@ export const useTripStore = create((set, get) => ({ isEffectivelyOnline() ? categoriesApi.list().catch(() => offlineDb.categories.toArray().then(categories => ({ categories }))) : offlineDb.categories.toArray().then(categories => ({ categories })), + // The trip's own tags, non-fatal like the three above: without them the + // places still show the tags they carry. + tripTagRepo.list(tripId).catch(() => ({ tags: [] as Tag[] })), ]) const assignmentsMap: AssignmentsMap = {} @@ -219,6 +227,7 @@ export const useTripStore = create((set, get) => ({ files: filesData.files, tags: tagsData.tags, categories: categoriesData.categories, + tripTags: tripTagsData.tags, isLoading: false, }) } catch (err: unknown) { @@ -241,6 +250,7 @@ export const useTripStore = create((set, get) => ({ get().loadBudgetItems(tripId), get().loadReservations(tripId), get().loadFiles(tripId), + get().loadTripTags(tripId), ]) // Accommodations live in planner-local state, not this store — nudge the // planner to reload them too (e.g. a trip date change made while offline). @@ -344,4 +354,5 @@ export const useTripStore = create((set, get) => ({ ...createBudgetSlice(set, get), ...createReservationsSlice(set, get), ...createFilesSlice(set, get), + ...createTripTagsSlice(set, get), })) diff --git a/client/src/styles/collections.css b/client/src/styles/collections.css index 9533458b7..55c177253 100644 --- a/client/src/styles/collections.css +++ b/client/src/styles/collections.css @@ -215,6 +215,13 @@ display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 18px; padding: 10px 14px; border-radius: var(--r-md); background: var(--glass-bg); border: 1px solid var(--glass-border); box-shadow: var(--sh-sm); } +.trek-dash .col-selbar { container-type: inline-size; } +/* Too narrow for every action's words: the actions keep their icon and say what they do + in their tooltip, so the bar stays one line instead of stranding "Delete" below. */ +@container (max-width: 1120px) { + .trek-dash .col-selbar-btn.act { padding-inline: 9px; } + .trek-dash .col-selbar-btn.act .col-selbar-txt { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +} .trek-dash .col-selbar .lbl { font-size: 13px; font-weight: 600; color: var(--ink); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .trek-dash .col-selbar-btn { display: inline-flex; align-items: center; gap: 6px; padding: 7px 12px; border-radius: 9px; font-size: 12.5px; font-weight: 600; color: var(--ink-2); transition: background .12s, color .12s; } .trek-dash .col-selbar-btn:hover { background: var(--surface-2); color: var(--ink); } @@ -254,6 +261,8 @@ /* ----------------- list view ----------------- */ .trek-dash .col-listview { display: flex; flex-direction: column; gap: 7px; } +/* A row: tile, name and address, then whatever sits at its end. A kept tour keeps one + line: tile, name, its end group. */ .trek-dash .col-lrow { display: grid; grid-template-columns: 40px minmax(0, 1fr) auto; gap: 14px; align-items: center; padding: 10px 14px; border-radius: var(--r-md); @@ -272,8 +281,40 @@ /* The pin before the address must not be squeezed by a long address. */ .trek-dash .col-lrow .li .s svg { flex-shrink: 0; } .trek-dash .col-lrow-end { display: flex; align-items: center; gap: 8px; flex-shrink: 0; } + +/* A place row (#2981). Its labels and category used to sit in an end group that could + not shrink, so with two or three long labels the name got one letter or none. Now the + name keeps the room it needs and the labels give way: on a wide list they share the + line and end in an ellipsis; on a narrow one (below 760px) the row has two fixed lines, + name and status on top, labels and category below, still on one line. */ +.trek-dash .col-listview { container-type: inline-size; } +.trek-dash .col-lrow-place { + grid-template-columns: 40px minmax(12rem, max-content) minmax(0, 1fr) auto; + grid-template-areas: "tile main tags status"; +} +.trek-dash .col-lrow-place > :first-child { grid-area: tile; } +.trek-dash .col-lrow-place > .li { grid-area: main; } +.trek-dash .col-lrow-tags { grid-area: tags; position: relative; display: flex; justify-content: flex-end; align-items: center; gap: 8px; min-width: 0; overflow: hidden; } +/* A label the row has no room for stays in it, out of sight, so it can be measured. */ +.trek-dash .col-lrow-tags > .is-over { position: absolute; inset-inline-start: 0; visibility: hidden; pointer-events: none; } +.trek-dash .col-lrow-tags > * { flex-shrink: 0; } +.trek-dash .col-lrow-tags > .col-lrow-label, .trek-dash .col-lrow-tags > .col-lrow-cat { flex-shrink: 1; min-width: 0; } +.trek-dash .col-lrow-more { display: inline-flex; align-items: center; flex-shrink: 0; padding: 3px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; color: var(--ink-3); background: var(--surface-2); cursor: default; } +.trek-dash .col-lrow-status { grid-area: status; display: flex; } +@container (max-width: 760px) { + .trek-dash .col-lrow-place { + grid-template-columns: 40px minmax(0, 1fr) auto; + grid-template-areas: "tile main status" "tile tags tags"; + row-gap: 0; align-items: start; + } + .trek-dash .col-lrow-place > :first-child { align-self: center; } + .trek-dash .col-lrow-tags { margin-top: 8px; justify-content: flex-start; } + .trek-dash .col-lrow-tags .col-lrow-div { display: none; } + .trek-dash .col-lrow-tags > .col-lrow-label, .trek-dash .col-lrow-tags > .col-lrow-cat { max-width: 170px; } +} .trek-dash .col-lrow-cat { display: inline-flex; align-items: center; gap: 5px; max-width: 130px; padding: 3px 9px; border-radius: 999px; font-size: 11px; font-weight: 600; white-space: nowrap; overflow: hidden; color: var(--cat, var(--accent)); background: color-mix(in oklch, var(--cat, var(--accent)) 14%, transparent); } .trek-dash .col-lrow-cat svg { flex-shrink: 0; } +.trek-dash .col-lrow-txt { min-width: 0; overflow: hidden; text-overflow: ellipsis; } .trek-dash .col-lrow-div { width: 1px; height: 18px; flex-shrink: 0; background: var(--line-2); } /* A kept tour (LIB-03) is a row of the same list: its grade tile stands where @@ -318,7 +359,7 @@ /* On the map the tray joins the floating controls, so it takes their glass, their radius and their shadow instead of the row's flat surface. */ .trek-dash .col-labelfilter.on-map { - pointer-events: auto; max-width: min(52ch, 100%); flex-wrap: nowrap; overflow-x: auto; + pointer-events: auto; max-width: 100%; flex-wrap: nowrap; overflow: hidden; border-radius: 11px; border-color: var(--glass-border); box-shadow: var(--sh-md); background: color-mix(in oklch, var(--surface) 92%, transparent); backdrop-filter: blur(8px) saturate(1.2); -webkit-backdrop-filter: blur(8px) saturate(1.2); @@ -326,6 +367,17 @@ } .trek-dash .col-labelfilter.on-map::-webkit-scrollbar { display: none; } .trek-dash .col-labelfilter.on-map .col-labelchip { flex-shrink: 0; } +/* The strip takes the room the map's top bar leaves between its toggle and the search. + When its labels need more, it folds into one button with the labels as a list; the + hidden copy measures what the labels need, so the strip unfolds once the room is back. */ +.trek-dash .col-map-group:not(.right) { flex: 1 1 auto; min-width: 0; } +.trek-dash .col-labelfilter-slot { position: relative; display: flex; flex: 1 1 0; min-width: 0; } +.trek-dash .col-labelfilter-measure { position: absolute; top: 0; inset-inline-start: 0; width: max-content; max-width: none; visibility: hidden; pointer-events: none; } +.trek-dash .col-labelfilter-fold { gap: 7px; padding-inline: 10px 9px; font: inherit; font-size: 12.5px; font-weight: 600; color: var(--ink-2); cursor: pointer; } +.trek-dash .col-labelfilter-fold:hover, .trek-dash .col-labelfilter-fold.open { color: var(--ink); } +.trek-dash .col-labelfilter-active { min-width: 18px; height: 18px; padding: 0 5px; border-radius: 999px; display: grid; place-items: center; font-size: 11px; font-weight: 700; color: var(--accent-text); background: var(--accent); } +.trek-dash .col-labelfilter-pop { pointer-events: auto; } +.trek-dash .col-labelfilter-manage { color: var(--ink-3); border-top: 1px solid var(--line); border-radius: 0 0 8px 8px; margin-top: 2px; } .trek-dash .col-labelfilter.on-map .col-labelchip:hover { background: var(--surface-2); } .trek-dash .col-labelchip { display: inline-flex; align-items: center; gap: 6px; max-width: 180px; padding: 5px 9px; border-radius: 8px; font-size: 12.5px; font-weight: 600; white-space: nowrap; color: var(--ink-2); background: transparent; border: 1px solid transparent; transition: background .12s, border-color .12s, color .12s; } .trek-dash .col-labelchip:hover { background: var(--surface); color: var(--ink); } @@ -358,7 +410,21 @@ over the map are read as a single band when the page is scrolled to the top, so they share a height and a top offset instead of each having their own. */ .trek-dash { --col-ctl-h: 38px; } -.trek-dash .col-filterbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 12px; } +/* One line on desktop: the dropdowns shorten their labels instead of pushing the sort + control onto a second line. Phones wrap (see the 720px block). */ +.trek-dash .col-filterbar { display: flex; flex-wrap: nowrap; align-items: center; gap: 8px; margin-bottom: 12px; min-width: 0; } +.trek-dash .col-filterbar > * { flex-shrink: 0; } +.trek-dash .col-filterbar > .col-filter { flex-shrink: 1; min-width: 0; } +.trek-dash .col-filterbar > .col-filter > .col-filter-btn { max-width: 100%; min-width: 0; } +.trek-dash .col-filterbar > .col-filter > .col-filter-btn > svg { flex-shrink: 0; } +.trek-dash .col-filterbar > .col-filter .col-filter-lbl { min-width: 0; } +/* Narrow: a dropdown left at its default ("All", "Default") keeps its icon and says its + value in its tooltip; one set to a value still shows it. */ +.trek-dash .col-filterbar { container-type: inline-size; } +@container (max-width: 540px) { + .trek-dash .col-filter-btn.is-default .col-filter-lbl { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + .trek-dash .col-filter-btn.is-default { padding-inline: 9px; } +} /* Beside the map, the row starts where the map's own top bar does. */ .trek-dash .col-split-list .col-filterbar { margin-top: 12px; } .trek-dash .col-filter { position: relative; } @@ -480,7 +546,7 @@ the link chips below — it is an action on the place, not a piece of it. */ /* status segmented control */ -.trek-dash .col-detail-seg { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; padding: 4px; border-radius: 12px; background: var(--surface-2); } +.trek-dash .col-detail-seg { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; padding: 4px; border-radius: 12px; background: var(--surface-2); } .trek-dash .col-detail-seg button { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 8px 6px; border-radius: 9px; font-size: 12.5px; font-weight: 600; color: var(--ink-2); transition: background .12s, color .12s, box-shadow .12s; } .trek-dash .col-detail-seg button:hover { color: var(--ink); } .trek-dash .col-detail-seg button.on { background: var(--surface); color: var(--ink); box-shadow: var(--sh-xs); } @@ -529,6 +595,8 @@ @media (max-width: 720px) { .trek-dash .col-detail { inset-inline: 0; bottom: 0; transform: none; width: 100%; max-height: 84dvh; border-radius: var(--r-xl) var(--r-xl) 0 0; } + /* four statuses side by side leave a label no room at this width: two by two */ + .trek-dash .col-detail-seg { grid-template-columns: repeat(2, 1fr); } /* the read-mode footer (Edit · Copy · Remove) would otherwise clip its last button — let it wrap, drop the growing spacer, and clear the home indicator */ .trek-dash .col-detail-footer { flex-wrap: wrap; padding-bottom: calc(12px + env(safe-area-inset-bottom, 0px)); } @@ -583,12 +651,13 @@ .trek-dash .col-drawer .col-rail-new { min-height: 44px; } .trek-dash .col-drawer .col-rail-import { min-width: 44px; } /* enlarge the interactive status badge's tap area without changing its look */ - .trek-dash .col-lrow-end > [role="button"] { position: relative; } - .trek-dash .col-lrow-end > [role="button"]::after { content: ''; position: absolute; inset: -9px -6px; } + .trek-dash .col-lrow-status > [role="button"] { position: relative; } + .trek-dash .col-lrow-status > [role="button"]::after { content: ''; position: absolute; inset: -9px -6px; } /* select action bar: break the bulk actions onto their own line instead of stranding them behind a growing spacer */ .trek-dash .col-selbar .col-toolbar-spacer { flex-basis: 100%; height: 0; } + .trek-dash .col-filterbar { flex-wrap: wrap; } } /* ----------------- mobile rail drawer ----------------- */ diff --git a/client/src/styles/dashboard.css b/client/src/styles/dashboard.css index 59bc82757..d6596fae0 100644 --- a/client/src/styles/dashboard.css +++ b/client/src/styles/dashboard.css @@ -175,6 +175,9 @@ transition: transform .35s cubic-bezier(0.23,1,0.32,1), box-shadow .35s cubic-bezier(0.23,1,0.32,1); } .trek-dash .hero-trip:hover { transform: translateY(-4px); box-shadow: var(--sh-xl, 0 24px 60px oklch(0 0 0 / .28)); } +/* The hero's place while the trips load: same box, nothing to open or lift (#3009). */ +.trek-dash .hero-trip.hero-trip-pending { cursor: default; box-shadow: none; } +.trek-dash .hero-trip.hero-trip-pending:hover { transform: none; box-shadow: none; } .trek-dash .hero-trip img.bg { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; z-index: 0; transition: transform 12s ease-out; @@ -400,7 +403,7 @@ .trek-dash .atlas-card.passport .label { color: oklch(1 0 0 / .65); } .trek-dash .atlas-card.passport .value { font-size: 56px; } .trek-dash .atlas-card.passport .delta { color: oklch(1 0 0 / .65); } -.trek-dash .passport-flags { display: flex; margin-top: 18px; } +.trek-dash .passport-flags { display: flex; margin-top: 18px; min-height: 24px; } /* a flag's height, so the flags arriving move nothing (#3009) */ .trek-dash .flag { width: 24px; height: 24px; border-radius: 50%; overflow: hidden; background: oklch(0.4 0.06 60); border: 2px solid oklch(0.28 0.04 50); @@ -639,7 +642,7 @@ .trek-dash .tz-del:hover { background: var(--bg-2); color: #ef4444; } .trek-dash .tz-empty { font-size: 12px; color: var(--ink-3); } .trek-dash .upc-list { display: flex; flex-direction: column; gap: 12px; } -.trek-dash .upc-item { display: grid; grid-template-columns: 56px 1fr auto; gap: 14px; padding: 12px; border-radius: 14px; align-items: center; transition: background .12s; cursor: pointer; } +.trek-dash .upc-item { display: grid; grid-template-columns: 56px minmax(0, 1fr) auto; gap: 14px; padding: 12px; border-radius: 14px; align-items: center; transition: background .12s; cursor: pointer; } .trek-dash .upc-item:hover { background: var(--surface-2); } .trek-dash .upc-date { background: var(--surface-2); border-radius: 10px; padding: 8px 4px; text-align: center; } .trek-dash .upc-date .d { font-size: 18px; font-weight: 600; letter-spacing: -0.02em; line-height: 1; } @@ -647,10 +650,17 @@ .trek-dash .upc-info .t { font-size: 14px; font-weight: 500; margin-bottom: 2px; } .trek-dash .upc-info .t { display: flex; align-items: center; gap: 7px; } /* An unconfirmed booking looked exactly like a confirmed one here (#1934). */ -.trek-dash .upc-pending { font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.08em; padding: 2px 6px; border-radius: 999px; background: var(--bg-2); color: var(--ink-3); } -.trek-dash .upc-info .s { font-size: 12px; color: var(--ink-3); display: flex; align-items: center; gap: 6px; } +/* A pending booking: its status's first letter on a dot at the type icon's corner, the word as its tooltip. */ +.trek-dash .upc-pending { position: absolute; top: -5px; inset-inline-start: -5px; width: 16px; height: 16px; border-radius: 50%; display: grid; place-items: center; font-size: 9px; font-weight: 700; line-height: 1; background: var(--ink); color: var(--surface); box-shadow: 0 0 0 2px var(--surface); } +.trek-dash .upc-info .s { font-size: 12px; color: var(--ink-3); display: flex; align-items: center; gap: 5px; margin-top: 3px; min-width: 0; } +.trek-dash .upc-info .s .upc-chip:first-child { flex-shrink: 0; } +.trek-dash .upc-info .s .upc-chip { min-width: 0; } +/* A long trip name ends in an ellipsis inside its badge. */ +.trek-dash .upc-chip-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +/* The time and the where as soft badges instead of a line strung together with dots. */ +.trek-dash .upc-chip { display: inline-flex; align-items: center; gap: 4px; max-width: 100%; padding: 2px 8px; border-radius: 999px; background: var(--bg-2); color: var(--ink-2); font-size: 11.5px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .trek-dash .upc-info .s svg { width: 11px; height: 11px; } -.trek-dash .upc-type { width: 32px; height: 32px; border-radius: 10px; display: grid; place-items: center; } +.trek-dash .upc-type { position: relative; width: 32px; height: 32px; border-radius: 10px; display: grid; place-items: center; } .trek-dash .upc-type.flight { background: oklch(0.95 0.04 230); color: oklch(0.45 0.13 230); } .trek-dash .upc-type.hotel { background: oklch(0.95 0.04 145); color: oklch(0.4 0.12 155); } .trek-dash .upc-type.food { background: oklch(0.95 0.05 60); color: oklch(0.5 0.13 50); } @@ -665,6 +675,8 @@ cursor: pointer; text-align: start; box-shadow: var(--sh-sm); transition: transform .15s cubic-bezier(.2,.7,.2,1), box-shadow .2s; } .trek-dash .col-badge:hover { transform: translateY(-2px); box-shadow: var(--sh-md); } +.trek-dash .col-badge.col-badge-pending { cursor: default; box-shadow: none; } +.trek-dash .col-badge.col-badge-pending:hover { transform: none; box-shadow: none; } .trek-dash .col-badge-media { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; background-size: cover; background-position: center; } .trek-dash .col-badge-tint { position: absolute; inset: 0; @@ -806,3 +818,7 @@ /* The bottom tab bar's centre "+" replaces the floating FAB on mobile */ .trek-dash .fab-new-trip { display: none; } } + +/* A figure's line while the stats load: its real text, invisible under the + shimmer, so it wraps as the loaded line will and the cards keep their height (#3009). */ +.trek-dash .atlas-card .delta .delta-pending { color: transparent; border-radius: 4px; } diff --git a/client/src/styles/rtl.css b/client/src/styles/rtl.css new file mode 100644 index 000000000..dc3527959 --- /dev/null +++ b/client/src/styles/rtl.css @@ -0,0 +1,63 @@ +/* + * Right to left (Arabic). Layout already follows the reading direction through + * the logical utilities (ms-, ps-, start-, text-start); what is here are the + * three things a logical utility cannot say. + */ + +/* + * User text in its own direction. A name, title or address carries dir="auto", + * so a Latin one in an Arabic row keeps its punctuation at its own end and, when + * it is cut, loses its end rather than its beginning. Cut, clamped or typed into + * a field, it still lines up with the row and the form: on the UI's start edge, + * wherever its own start is (an empty field reads as left to right, so without + * this its placeholder would jump to the far side). A free paragraph shown on + * its own (a note, a chat message) keeps the alignment of its own language. + * Zero specificity, so an explicit text-center or text-end on the element wins. + */ +:where( + :root[dir='rtl'] [dir='auto']:dir(ltr):is(.truncate, [class*='line-clamp-'], input, textarea), + :root[dir='ltr'] [dir='auto']:dir(rtl):is(.truncate, [class*='line-clamp-'], input, textarea) +) { + text-align: end; +} + +/* + * Arrows and chevrons that point along the reading direction (back, forward, a + * disclosure row, a date range, a payment from one person to another) turn + * round in a right-to-left language. The touch shell draws them all with + * lucide, so the shell (and the sheets it portals, which carry m-root too) + * mirrors them here instead of every icon carrying its own class. An icon that + * names its own RTL treatment keeps it: rtl:-scale-x-100 already turns it, and + * rtl:scale-x-100 marks an arrow that is physical on purpose. `scale` is its + * own property, so it composes with a rotation the icon carries (an open + * disclosure pointing down) instead of replacing it. + */ +:root[dir='rtl'] + .m-root + :is( + .lucide-chevron-left, + .lucide-chevron-right, + .lucide-chevrons-left, + .lucide-chevrons-right, + .lucide-arrow-left, + .lucide-arrow-right, + .lucide-move-left, + .lucide-move-right + ):not([class*='rtl:']) { + scale: -1 1; +} + +/* + * Arabic (and Hebrew) has no capitals, so the touch shell's small uppercase + * eyebrows (field labels, stat labels, status pills) lose the weight capitals + * give a Latin label and read as grey specks. There they grow by a fifth (about + * 2px, padding and pill with them), drop the tracking that pulls joined letters + * apart, and take the muted ink instead of the faint one. + */ +:root:is(:lang(ar), :lang(he)) .m-root .uppercase { + zoom: 1.2; + letter-spacing: 0; +} +:root:is(:lang(ar), :lang(he)) .m-root .uppercase.text-m-faint { + color: var(--m-muted); +} diff --git a/client/src/styles/rtlCss.test.ts b/client/src/styles/rtlCss.test.ts new file mode 100644 index 000000000..8952d5b83 --- /dev/null +++ b/client/src/styles/rtlCss.test.ts @@ -0,0 +1,63 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { describe, expect, it } from 'vitest'; + +// FE-RTL-CSS-001 to FE-RTL-CSS-004 +// +// styles/rtl.css carries what the logical utilities cannot say for Arabic: user +// text that lines up with the UI in its own direction, arrows that turn round +// in the touch shell, and Arabic's caption labels. jsdom applies no +// stylesheet, so these read the real file. +const css = readFileSync(resolve(process.cwd(), 'src/styles/rtl.css'), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ''); + +/** The declarations of the rule whose selector text contains every given part. */ +function ruleBody(...parts: string[]): string { + for (const chunk of css.split('}')) { + const open = chunk.indexOf('{'); + if (open < 0) continue; + // Prettier breaks a long selector over lines; compared with its white space folded. + const head = chunk.slice(0, open).replace(/\s+/g, ' '); + if (parts.every((part) => head.includes(part))) return chunk.slice(open + 1); + } + return ''; +} + +describe('rtl.css', () => { + it('FE-RTL-CSS-001: the stylesheet is loaded with the app', () => { + const main = readFileSync(resolve(process.cwd(), 'src/main.tsx'), 'utf8'); + expect(main).toMatch(/import '\.\/styles\/rtl\.css'/); + }); + + it('FE-RTL-CSS-002: cut, clamped or typed user text in its own direction sits on the UI start edge', () => { + const body = ruleBody( + ":root[dir='rtl'] [dir='auto']:dir(ltr)", + '.truncate', + "[class*='line-clamp-']", + 'input', + 'textarea' + ); + expect(body).toMatch(/text-align:\s*end/); + // The left-to-right UI gets the mirror case: Arabic text in an English row. + expect(css).toContain(":root[dir='ltr'] [dir='auto']:dir(rtl)"); + // Zero specificity: an explicit alignment class on the element still wins. + expect(css).toMatch(/:where\(\s*:root\[dir='rtl'\]/); + }); + + it('FE-RTL-CSS-003: in the touch shell every back, forward and flow arrow turns round in a right-to-left language', () => { + const body = ruleBody( + ":root[dir='rtl'] .m-root", + '.lucide-chevron-left', + '.lucide-chevron-right', + '.lucide-arrow-left', + '.lucide-arrow-right' + ); + expect(body).toMatch(/scale:\s*-1 1/); + // An icon that names its own treatment keeps it. + expect(css).toContain(":not([class*='rtl:'])"); + }); + + it('FE-RTL-CSS-004: Arabic and Hebrew caption labels grow, drop the tracking and take the muted ink', () => { + expect(ruleBody(':lang(ar)', ':lang(he)', '.m-root .uppercase')).toMatch(/zoom:\s*1\.2[\s\S]*letter-spacing:\s*0/); + expect(ruleBody('.uppercase.text-m-faint')).toMatch(/color:\s*var\(--m-muted\)/); + }); +}); diff --git a/client/src/styles/studio-floating.css b/client/src/styles/studio-floating.css new file mode 100644 index 000000000..428519c5a --- /dev/null +++ b/client/src/styles/studio-floating.css @@ -0,0 +1,12 @@ +/* + * Studio's side panels where they float over the workbench (studio.css, under + * 1080px: an iPad in portrait). The docked panels' glass let the page show + * through there and the text washed out, so a floating panel is opaque. Higher + * specificity than `.st-panel`, which sets the glass after these breakpoints. + */ +@media (max-width: 1079px) { + .trek-dash .st-panel.st-inspector, + .trek-dash .st-panel.st-side { + background: var(--surface); + } +} diff --git a/client/src/styles/studio.css b/client/src/styles/studio.css index d55ed7494..b44a39c3a 100644 --- a/client/src/styles/studio.css +++ b/client/src/styles/studio.css @@ -218,10 +218,13 @@ min-height: 0; } -/* Under 1280 the inspector floats over the workbench instead of narrowing it — - below roughly 700px of canvas a spread stops being legible at any zoom. */ +/* Under 1280 the inspector narrows and stays docked: floating over the workbench it + hid the page an iPad in landscape was editing. Under 1080 it floats after all. */ @media (max-width: 1279px) { - .trek-dash .st-body { grid-template-columns: minmax(64px, min-content) 236px minmax(0, 1fr); } + .trek-dash .st-body { grid-template-columns: minmax(64px, min-content) 236px minmax(0, 1fr) 280px; } +} +@media (max-width: 1079px) { + .trek-dash .st-body { grid-template-columns: minmax(64px, min-content) minmax(0, 1fr); } .trek-dash .st-inspector { position: absolute; top: 56px; @@ -230,9 +233,6 @@ width: 300px; box-shadow: var(--sh-lg); } -} -@media (max-width: 1079px) { - .trek-dash .st-body { grid-template-columns: minmax(64px, min-content) minmax(0, 1fr); } /* The panel floats over the workbench's cell, so it starts wherever the rail ends. */ .trek-dash .st-side, .trek-dash .st-work-wrap { grid-area: 1 / 2; } .trek-dash .st-side { diff --git a/client/src/sync/glPrefetcher.ts b/client/src/sync/glPrefetcher.ts index af1daf568..9257f5fbe 100644 --- a/client/src/sync/glPrefetcher.ts +++ b/client/src/sync/glPrefetcher.ts @@ -17,6 +17,8 @@ */ import { computeBbox, tileRange, type TileBbox } from './tilePrefetcher' import type { Place } from '../types' +import { openCacheStorage } from './openCacheStorage' +import { isNativeIos } from '../native/platform' /** OpenFreeMap serves vector tiles up to z14 and overzooms from there. */ const VECTOR_MAX_ZOOM = 14 @@ -25,8 +27,15 @@ const VECTOR_MAX_ZOOM = 14 // The low zooms cost a few dozen tiles at most. const VECTOR_MIN_ZOOM = 0 -/** Requests in flight, kept low for the same reason the raster side keeps it low. */ -const CONCURRENCY = 6 +/** + * Requests in flight. OpenFreeMap allows offline downloads with at most four + * parallel requests, at most 3000 tiles and at most 50 MB each + * (openfreemap.org/tos), so the run keeps under all three. + */ +const CONCURRENCY = 4 + +/** Byte budget per run, the 50 MB OpenFreeMap allows for one download. */ +const MAX_RUN_BYTES = 50 * 1024 * 1024 /** * Hard cap on vector tiles per run. Each is far larger than a raster tile but @@ -35,15 +44,55 @@ const CONCURRENCY = 6 const MAX_VECTOR_TILES = 2000 /** Workbox runtime cache for the vector basemap (see vite.config.js). */ -const VECTOR_CACHE = 'gl-map-offline' +export const VECTOR_CACHE = 'gl-map-offline' /** - * Latin glyph ranges. A label needs the range its codepoints fall in, and Latin - * text lives in the first few; asking for all 256 ranges would download megabytes - * of CJK nobody on this map is going to render. + * Glyph ranges every map needs: Latin, Greek, Cyrillic, Hebrew, Arabic and the + * punctuation blocks. A label needs the range its codepoints fall in; asking for + * all 256 ranges would download megabytes of scripts nobody on this map renders. */ const GLYPH_RANGES = ['0-255', '256-511', '512-767', '768-1023', '1024-1279', '1280-1535', '1536-1791', '8192-8447', '8448-8703'] +/** One range string per 256 codepoints from `from` up to `to`. */ +function rangesBetween(from: number, to: number): string[] { + const out: string[] = [] + for (let start = from - (from % 256); start <= to; start += 256) out.push(`${start}-${start + 255}`) + return out +} + +/** + * Scripts whose labels a trip in that part of the world shows in the local + * name, so a trip there gets their ranges too, or its labels render blank + * offline. Boxes are generous [minLng, minLat, maxLng, maxLat]. + */ +const REGIONAL_GLYPHS: { box: [number, number, number, number]; ranges: string[] }[] = [ + // China, Japan, Korea, Taiwan: kana and CJK punctuation, unified ideographs, Hangul, full-width forms. + { + box: [73, 18, 146, 54], + ranges: [...rangesBetween(0x3000, 0x30ff), ...rangesBetween(0x4e00, 0x9fff), ...rangesBetween(0xac00, 0xd7af), ...rangesBetween(0xff00, 0xffef)], + }, + // Thailand, Laos, Cambodia, Myanmar. + { box: [92, 5, 110, 28], ranges: rangesBetween(0x0e00, 0x0eff).concat(rangesBetween(0x1000, 0x109f), rangesBetween(0x1780, 0x17ff)) }, + // India, Nepal, Bangladesh, Sri Lanka: Devanagari through Malayalam, Sinhala. + { box: [60, 5, 98, 36], ranges: rangesBetween(0x0900, 0x0dff) }, + // Georgia and Armenia. + { box: [39, 38, 47, 44], ranges: rangesBetween(0x0530, 0x058f).concat(rangesBetween(0x10a0, 0x10ff)) }, + // Ethiopia and Eritrea. + { box: [33, 3, 48, 18], ranges: rangesBetween(0x1200, 0x139f) }, +] + +/** The glyph ranges a map of `bbox` needs: the common ones plus its region's scripts. */ +function glyphRangesFor(bbox: TileBbox | null): string[] { + const out = new Set(GLYPH_RANGES) + if (bbox) { + for (const { box, ranges } of REGIONAL_GLYPHS) { + const overlaps = bbox.minLng <= box[2] && bbox.maxLng >= box[0] && bbox.minLat <= box[3] && bbox.maxLat >= box[1] + if (overlaps) for (const r of ranges) out.add(r) + } + } + return [...out] +} + interface StyleSource { type?: string url?: string @@ -96,24 +145,20 @@ function fontStacks(style: StyleDoc): string[] { * the Service Worker's handler, so a repeated or resumed run over a warm cache * costs almost nothing. Same reasoning as the raster side. */ -async function warm(cache: Cache | null, url: string): Promise { +async function warm(cache: Cache | null, url: string): Promise { try { - if (cache && (await cache.match(url))) return false + if (cache && (await cache.match(url))) return 0 const res = await fetch(url, { mode: 'cors' }) - if (!res.ok) return false + if (!res.ok) return 0 await cache?.put(url, res.clone()) - return true + return await sizeOf(res) } catch { - return false + return 0 } } async function openVectorCache(): Promise { - try { - return await caches.open(VECTOR_CACHE) - } catch { - return null - } + return openCacheStorage(VECTOR_CACHE) } /** @@ -178,11 +223,11 @@ async function readTileSources(style: StyleDoc, cache: Cache | null): Promise { - return (await prefetchStyle(styleUrl))?.[0]?.template ?? null +export async function prefetchStyleAssets(styleUrl: string, bbox: TileBbox | null = null): Promise { + return (await prefetchStyle(styleUrl, bbox))?.[0]?.template ?? null } -async function prefetchStyle(styleUrl: string): Promise { +async function prefetchStyle(styleUrl: string, bbox: TileBbox | null = null): Promise { const cache = await openVectorCache() const style = await fetchJson(styleUrl) if (!style) return null @@ -198,15 +243,16 @@ async function prefetchStyle(styleUrl: string): Promise { ]) } - if (style.glyphs) { - const stacks = fontStacks(style) - await Promise.all( - stacks.flatMap(stack => - GLYPH_RANGES.map(range => - warm(cache, style.glyphs!.replace('{fontstack}', encodeURIComponent(stack)).replace('{range}', range)), - ), + const glyphs = style.glyphs + if (glyphs) { + // Through the same pool as the tiles: a trip in East Asia asks for a few + // hundred glyph ranges, and OpenFreeMap allows four requests at a time. + const urls = fontStacks(style).flatMap(stack => + glyphRangesFor(bbox).map(range => + glyphs.replace('{fontstack}', encodeURIComponent(stack)).replace('{range}', range), ), ) + await inPool(urls, url => warm(cache, url)) } return readTileSources(style, cache) @@ -229,11 +275,14 @@ export async function prefetchVectorForPlaces( isCancelled: () => boolean = () => false, ): Promise { if (!navigator.onLine) return { tiles: 0, template: null } + // The iOS app has no service worker: with Cache Storage given up on, nothing + // would keep what is downloaded, so nothing is downloaded. + if (isNativeIos() && !(await openVectorCache())) return { tiles: 0, template: null } const bbox = computeBbox(places) if (!bbox) return { tiles: 0, template: null } - const sources = await prefetchStyle(styleUrl) + const sources = await prefetchStyle(styleUrl, bbox) const template = sources?.[0]?.template ?? null if (!sources?.length || isCancelled()) return { tiles: 0, template } @@ -242,13 +291,18 @@ export async function prefetchVectorForPlaces( let cursor = 0 let fetched = 0 + let bytes = 0 async function worker(): Promise { while (cursor < urls.length) { - if (isCancelled() || !navigator.onLine) return + if (isCancelled() || !navigator.onLine || bytes >= MAX_RUN_BYTES) return const url = urls[cursor++] if (!url) return - if (await warm(cache, url)) fetched++ + const size = await warm(cache, url) + if (size > 0) { + fetched++ + bytes += size + } } } @@ -256,6 +310,34 @@ export async function prefetchVectorForPlaces( return { tiles: fetched, template } } +/** + * The bytes a response brought, for the run's budget: the length header when + * the server sends one, else the body itself, and at least 1 so a fetched tile + * always counts as fetched. + */ +async function sizeOf(res: Response): Promise { + const header = Number(res.headers?.get('content-length')) + if (header > 0) return header + try { + return (await res.blob()).size || 1 + } catch { + return 1 + } +} + +/** Runs `task` over `items`, CONCURRENCY at a time. */ +async function inPool(items: T[], task: (item: T) => Promise): Promise { + let cursor = 0 + async function worker(): Promise { + while (cursor < items.length) { + const item = items[cursor++] + if (item === undefined) return + await task(item) + } + } + await Promise.all(Array.from({ length: CONCURRENCY }, () => worker())) +} + /** Drop the offline vector basemap, alongside the raster cache. */ export async function clearVectorCache(): Promise { try { diff --git a/client/src/sync/openCacheStorage.test.ts b/client/src/sync/openCacheStorage.test.ts new file mode 100644 index 000000000..4086290b1 --- /dev/null +++ b/client/src/sync/openCacheStorage.test.ts @@ -0,0 +1,37 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { _resetCacheStorage, cacheStorageUnusable, openCacheStorage } from './openCacheStorage'; + +beforeEach(() => _resetCacheStorage()); +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +describe('openCacheStorage', () => { + it('FE-SYNC-CACHEOPEN-001: hands back the bucket, and null where Cache Storage is missing or throws', async () => { + const bucket = {} as Cache; + vi.stubGlobal('caches', { open: vi.fn(async () => bucket) }); + expect(await openCacheStorage('tiles')).toBe(bucket); + + vi.stubGlobal('caches', { open: vi.fn(async () => Promise.reject(new DOMException('denied', 'SecurityError'))) }); + expect(await openCacheStorage('tiles')).toBeNull(); + expect(cacheStorageUnusable()).toBe(false); + + vi.stubGlobal('caches', undefined); + expect(await openCacheStorage('tiles')).toBeNull(); + }); + + it('FE-SYNC-CACHEOPEN-002: an open that never settles is given up on after a few seconds, and not tried again', async () => { + vi.useFakeTimers(); + const open = vi.fn(() => new Promise(() => undefined)); + vi.stubGlobal('caches', { open }); + + const pending = openCacheStorage('gl-map-offline'); + await vi.advanceTimersByTimeAsync(4000); + expect(await pending).toBeNull(); + expect(cacheStorageUnusable()).toBe(true); + + expect(await openCacheStorage('gl-map-offline')).toBeNull(); + expect(open).toHaveBeenCalledTimes(1); + }); +}); diff --git a/client/src/sync/openCacheStorage.ts b/client/src/sync/openCacheStorage.ts new file mode 100644 index 000000000..23bd0b296 --- /dev/null +++ b/client/src/sync/openCacheStorage.ts @@ -0,0 +1,43 @@ +/** + * Opens a Cache Storage bucket, or null where it cannot be had: no Cache + * Storage at all, an open that throws, or one that never settles. + * + * The last is the one that hurt. On iPadOS the app's web view can leave + * caches.open() pending for good instead of refusing it, and everything that + * awaited it waited with it: "prepare for offline" stood still on its first + * trip's map tiles, and the offline map protocol never answered MapLibre, so + * the map stayed blank without an error. An open that has not settled after a + * few seconds is given up on, and Cache Storage is not tried again for the + * rest of the session, so no later caller pays the wait again. + */ + +const OPEN_TIMEOUT_MS = 4000; + +let unusable = false; + +export async function openCacheStorage(name: string): Promise { + if (unusable || typeof caches === 'undefined') return null; + let timer: ReturnType | undefined; + const gaveUp = new Promise((resolve) => { + timer = setTimeout(() => resolve(null), OPEN_TIMEOUT_MS); + }); + try { + const cache = await Promise.race([caches.open(name), gaveUp]); + if (!cache) unusable = true; + return cache; + } catch { + return null; + } finally { + clearTimeout(timer); + } +} + +/** Whether Cache Storage was given up on this session. */ +export function cacheStorageUnusable(): boolean { + return unusable; +} + +/** Tests only: try Cache Storage again. */ +export function _resetCacheStorage(): void { + unusable = false; +} diff --git a/client/src/sync/tilePrefetcher.ts b/client/src/sync/tilePrefetcher.ts index 120c054cb..86837385e 100644 --- a/client/src/sync/tilePrefetcher.ts +++ b/client/src/sync/tilePrefetcher.ts @@ -27,9 +27,12 @@ import type { Place } from '../types' import { offlineDb, upsertSyncMeta } from '../db/offlineDb' import { isAuthed } from './authGate' import { isStoragePersisted } from './persistentStorage' -import { isVectorStyle, normalizeTileUrl, resolveTileUrl, withTileApiKey } from '../utils/tileUrl' -import { OFM_POSITRON } from '../constants/mapDefaults' -import { clearVectorCache, prefetchVectorForPlaces } from './glPrefetcher' +import { isOfflineForbiddenTemplate, isVectorStyle, normalizeTileUrl, resolveTileUrl, withTileApiKey } from '../utils/tileUrl' +import { OFM_DARK, OFM_POSITRON } from '../constants/mapDefaults' +import { clearVectorCache, prefetchStyleAssets, prefetchVectorForPlaces } from './glPrefetcher' +import { isNativeIos } from '../native/platform' +import { isIosDevice } from '../utils/iosDevice' +import { openCacheStorage } from './openCacheStorage' // ── Constants ───────────────────────────────────────────────────────────────── @@ -46,6 +49,21 @@ const AVG_TILE_KB = 15 */ export const MAX_TILES = Math.floor((180 * 1024) / AVG_TILE_KB) // = 12288 +/** + * The tile budget on an iPhone or iPad. WebKit reads the origin's Cache Storage + * before the service worker can answer the app's first request, and that read + * grows with the number of entries: a full cache of 12,288 tiles held a home + * screen app on a black screen for about 8 s on every cold start, about 0.7 ms + * an entry (#3008). 2,048 keeps that near a second and still covers the zooms a + * trip map opens at. + */ +export const IOS_MAX_TILES = 2048 + +/** How many tiles a prefetch may hold here: the iOS budget in Safari and its home screen apps. */ +export function tileBudget(): number { + return isIosDevice() && !isNativeIos() ? IOS_MAX_TILES : MAX_TILES +} + /** * Tile requests in flight at once. * @@ -222,7 +240,7 @@ export function countTiles(bbox: TileBbox, minZoom: number, maxZoom: number): nu for (let z = minZoom; z <= maxZoom; z++) { const { minX, maxX, minY, maxY } = tileRange(bbox, z) total += (maxX - minX + 1) * (maxY - minY + 1) - if (total > MAX_TILES) return total + if (total > tileBudget()) return total } return total } @@ -250,7 +268,7 @@ export function buildTileUrl(template: string, z: number, x: number, y: number, /** * Enumerate the tile coordinates to prefetch, lowest zoom first, stopping at - * the zoom level whose tiles would push the total past MAX_TILES. + * the zoom level whose tiles would push the total past the budget (tileBudget). */ function enumerateTiles( bbox: TileBbox, @@ -258,11 +276,12 @@ function enumerateTiles( maxZoom: number, ): Array<[z: number, x: number, y: number]> { const coords: Array<[number, number, number]> = [] + const budget = tileBudget() for (let z = minZoom; z <= maxZoom; z++) { const { minX, maxX, minY, maxY } = tileRange(bbox, z) - if (coords.length + (maxX - minX + 1) * (maxY - minY + 1) > MAX_TILES) break + if (coords.length + (maxX - minX + 1) * (maxY - minY + 1) > budget) break for (let x = minX; x <= maxX; x++) { for (let y = minY; y <= maxY; y++) coords.push([z, x, y]) @@ -274,12 +293,7 @@ function enumerateTiles( /** Open the tile cache, or null where Cache Storage isn't available. */ async function openTileCache(): Promise { - try { - if (typeof caches === 'undefined') return null - return await caches.open(TILE_CACHE) - } catch { - return null - } + return openCacheStorage(TILE_CACHE) } /** @@ -345,6 +359,49 @@ export async function prefetchTiles( return fetched } +const TRIM_KEY = 'trek_tile_trim_at' +const TRIM_EVERY_MS = 24 * 60 * 60 * 1000 + +/** + * Brings a tile cache on an iPhone or iPad back within IOS_MAX_TILES, oldest + * tiles first (Cache Storage lists keys in the order they were stored). The + * service worker's own limit is the same on every platform, so a cache filled + * before this budget, or by browsing, still grows past it there (#3008). + * + * Reading the keys of a large cache is itself slow on iOS, so this runs at most + * once a day and only when called after the app is up. Returns how many tiles + * it removed. + */ +export async function trimTileCacheForIos(now = Date.now()): Promise { + if (!isIosDevice() || isNativeIos()) return 0 + try { + const last = Number(localStorage.getItem(TRIM_KEY) || 0) + if (now - last < TRIM_EVERY_MS) return 0 + localStorage.setItem(TRIM_KEY, String(now)) + } catch { + return 0 + } + try { + const cache = await openTileCache() + if (!cache) return 0 + const keys = await cache.keys() + const surplus = keys.slice(0, Math.max(0, keys.length - IOS_MAX_TILES)) + for (const request of surplus) await cache.delete(request) + return surplus.length + } catch { + // Cache Storage refused: the tiles stay as they are and tomorrow tries again. + return 0 + } +} + +/** Trims the iOS tile cache once the app has started, never in the way of its first screens. */ +export function scheduleTileCacheTrim(delayMs = 15_000): void { + if (!isIosDevice() || isNativeIos()) return + window.setTimeout(() => { + void trimTileCacheForIos() + }, delayMs) +} + /** * Drop the pre-downloaded map-tile cache. Called when the user turns off * "store map tiles offline" (#1135 ask 2) so the bulk tile storage — the real @@ -385,6 +442,28 @@ function sameBbox(a: [number, number, number, number], b: TileBbox): boolean { ) } +/** The OpenFreeMap styles the offline fallback draws; they share one tile set. */ +const OFFLINE_BASEMAPS: readonly string[] = [OFM_POSITRON, OFM_DARK] + +/** + * The offline basemap is a best-effort extra: a failed request leaves its tile + * uncached and the next sync tries again, so it stops neither the raster run + * nor the sync. + */ +function basemapFailed(): void {} + +/** + * The trip's region of the offline basemap: the light style's tiles, style, + * sprite and glyphs, and the dark style's own style, sprite and glyphs on top, + * whose tiles are the same ones. + */ +async function prefetchOfflineBasemap(places: Place[], template: string, cancelled: () => boolean): Promise { + const light = template === OFM_DARK ? OFM_DARK : OFM_POSITRON + const other = light === OFM_DARK ? OFM_POSITRON : OFM_DARK + await prefetchVectorForPlaces(places, light, cancelled).catch(basemapFailed) + if (!cancelled()) await prefetchStyleAssets(other, computeBbox(places)).catch(basemapFailed) +} + /** * Full pipeline: compute bbox → guard → prefetch → update syncMeta. * Designed to be called fire-and-forget from tripSyncManager. @@ -415,8 +494,16 @@ export async function prefetchTilesForTrip( // The default basemap is a vector style, and walking a {z}/{x}/{y} template // over one would fetch nothing the map ever asks for. A user who configured // their own raster template keeps the path below unchanged. + const cancelled = () => !navigator.onLine || !isAuthed() + // Whatever the map is set to, the trip's region of the offline basemap goes + // along: offline, a Mapbox map or one the device cannot serve switches to it + // (components/Map/offlineBasemap.ts). + await prefetchOfflineBasemap(places, template, cancelled) + if (isVectorStyle(template)) { - const { tiles } = await prefetchVectorForPlaces(places, template, () => !navigator.onLine || !isAuthed()) + const { tiles } = OFFLINE_BASEMAPS.includes(template) + ? { tiles: 0 } + : await prefetchVectorForPlaces(places, template, cancelled) const meta = await offlineDb.syncMeta.get(tripId) if (meta) { await upsertSyncMeta({ @@ -447,7 +534,12 @@ export async function prefetchTilesForTrip( // dozen tiles (#2180); the deep ones are the volume, and they are what the // user loses rather than the ability to start the app at all (#2228). const maxZoom = isStoragePersisted() ? 16 : UNPERSISTED_MAX_ZOOM - const fetched = await prefetchTiles(bbox, template, 0, maxZoom, cartoKey) + // Not for a host whose tiles may not be stored (OSM's tile usage policy), and + // not inside the iOS app, whose WebView runs no service worker to serve them: + // the offline basemap above stands in there. + const fetched = isOfflineForbiddenTemplate(template) || isNativeIos() + ? 0 + : await prefetchTiles(bbox, template, 0, maxZoom, cartoKey) // Update syncMeta with bbox and tile count const meta = await offlineDb.syncMeta.get(tripId) diff --git a/client/src/sync/tripSyncManager.ts b/client/src/sync/tripSyncManager.ts index a9abc1ae1..6ed327632 100644 --- a/client/src/sync/tripSyncManager.ts +++ b/client/src/sync/tripSyncManager.ts @@ -1,5 +1,6 @@ import { roadtripPreferencesRepo } from '../repo/roadtripPreferencesRepo' import { tourRepo } from '../repo/tourRepo' +import { tripTagRepo } from '../repo/tripTagRepo' /** * Trip sync manager — seeds Dexie with trip data for offline use. * @@ -155,6 +156,14 @@ async function syncTrip(tripId: number): Promise { await roadtripPreferencesRepo.read(tripId).catch(() => { /* optional cache */ }) } + // The trip's own tags, which the repo keeps as it reads them. Never fatal either. + try { + await tripTagRepo.list(tripId) + } catch { + // An optional cache: the places carry the tags they have, so without this + // list only the unused ones are missing offline, until the next sync. + } + // Tours, the same way: optional, and never fatal. Without them every Tour // reads as a plain place offline. Asked only while the addon is on, so a // sync of many trips does not spend a refused request on each. diff --git a/client/src/theme/README.md b/client/src/theme/README.md index d68b1d52f..c4b9c15bc 100644 --- a/client/src/theme/README.md +++ b/client/src/theme/README.md @@ -27,7 +27,7 @@ free **if they follow the contract below**. | Text | `--text-primary/secondary/muted/faint` · `text-content*` | | Borders | `--border-primary/secondary/faint` · `border-edge*` | | Accent | `--accent` (fill) · `--accent-text` (on fill) · `--accent-on` (on surface) · `--accent-hover` · `--accent-subtle` · `bg-accent` / `text-accent-on` / `bg-accent-subtle` | -| Status | `--success/-soft`, `--danger/-soft`, `--warning/-soft`, `--info/-soft` · `bg-danger-soft text-danger` etc. | +| Status | `--success/-soft`, `--danger/-soft`, `--warning/-soft`, `--info/-soft` · `bg-danger-soft text-danger` etc.; `--danger-text` for text on a solid `bg-danger` | | Elevation | `--shadow-sm/md/lg/card/elevated/modal/dropdown/popover` · `shadow-modal` etc. | | Overlay / inverse | `--overlay` · `--bg-inverse` / `--text-inverse` · `bg-inverse text-inverse-text` | | Type tiers | `text-title` / `text-subtitle` / `text-body` / `text-caption` (scale with the user's per-tier multipliers) | diff --git a/client/src/types.ts b/client/src/types.ts index c0538bf64..a0673c430 100644 --- a/client/src/types.ts +++ b/client/src/types.ts @@ -250,6 +250,8 @@ export interface Settings { maplibre_style?: string mapbox_3d_enabled?: boolean mapbox_quality_mode?: boolean + /** Leaves out the points of interest Mapbox Standard labels on its own (#1761); absent shows them. */ + map_hide_basemap_pois?: boolean // Dashboard widget prefs — persisted server-side so a (docker) upgrade keeps them (#1311). dashboard_fx_from?: string dashboard_fx_to?: string @@ -447,6 +449,8 @@ export interface AppConfig { password_registration?: boolean oidc_login?: boolean oidc_registration?: boolean + /** Whether an instance without password login sends visitors straight to the IdP */ + oidc_auto_redirect?: boolean env_override_oidc_only?: boolean } diff --git a/client/src/utils/colorSpace.test.ts b/client/src/utils/colorSpace.test.ts new file mode 100644 index 000000000..928907f0a --- /dev/null +++ b/client/src/utils/colorSpace.test.ts @@ -0,0 +1,32 @@ +// FE-UTIL-COLORSPACE-001 to FE-UTIL-COLORSPACE-003 +import { describe, expect, it } from 'vitest'; + +import { hexToHsv, hsvToHex, hueHex, normalizeHex } from './colorSpace'; + +describe('colorSpace', () => { + it('FE-UTIL-COLORSPACE-001: reads a typed colour in the forms people type it, and nothing else', () => { + expect(normalizeHex('#ABCDEF')).toBe('#abcdef'); + expect(normalizeHex('abcdef')).toBe('#abcdef'); + expect(normalizeHex(' #f0a ')).toBe('#ff00aa'); + expect(normalizeHex('#abcd')).toBeNull(); + expect(normalizeHex('red')).toBeNull(); + expect(normalizeHex('')).toBeNull(); + }); + + it('FE-UTIL-COLORSPACE-002: hue, saturation and value of the primaries, grey and black', () => { + expect(hexToHsv('#ff0000')).toEqual({ h: 0, s: 1, v: 1 }); + expect(hexToHsv('#00ff00')).toEqual({ h: 120, s: 1, v: 1 }); + expect(hexToHsv('#0000ff')).toEqual({ h: 240, s: 1, v: 1 }); + expect(hexToHsv('#808080')).toEqual({ h: 0, s: 0, v: 128 / 255 }); + expect(hexToHsv('#000000')).toEqual({ h: 0, s: 0, v: 0 }); + }); + + it('FE-UTIL-COLORSPACE-003: a colour survives the way there and back, and the hue alone is the pure one', () => { + for (const hex of ['#6366f1', '#ec4899', '#f97316', '#10b981', '#64748b', '#ffffff', '#000000']) { + expect(hsvToHex(hexToHsv(hex))).toBe(hex); + } + expect(hueHex(0)).toBe('#ff0000'); + expect(hueHex(120)).toBe('#00ff00'); + expect(hueHex(240)).toBe('#0000ff'); + }); +}); diff --git a/client/src/utils/colorSpace.ts b/client/src/utils/colorSpace.ts new file mode 100644 index 000000000..541e422f0 --- /dev/null +++ b/client/src/utils/colorSpace.ts @@ -0,0 +1,52 @@ +/** + * Hex colours to hue, saturation and value and back, for the colour field of + * the tag palette: the field picks saturation and value, the slider the hue. + */ +export interface Hsv { + /** 0 to 360. */ + h: number; + /** 0 to 1. */ + s: number; + /** 0 to 1. */ + v: number; +} + +const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i; + +/** A typed colour as lowercase #rrggbb, or null when it is not one. Accepts the short #rgb form and a missing #. */ +export function normalizeHex(raw: string): string | null { + const m = HEX.exec(raw.trim()); + if (!m) return null; + const digits = m[1].length === 3 ? [...m[1]].map((c) => c + c).join('') : m[1]; + return `#${digits.toLowerCase()}`; +} + +export function hexToHsv(hex: string): Hsv { + const norm = normalizeHex(hex) ?? '#000000'; + const [r, g, b] = [1, 3, 5].map((i) => parseInt(norm.slice(i, i + 2), 16) / 255); + const max = Math.max(r, g, b); + const d = max - Math.min(r, g, b); + let h = 0; + if (d) { + if (max === r) h = ((g - b) / d) % 6; + else if (max === g) h = (b - r) / d + 2; + else h = (r - g) / d + 4; + } + return { h: (h * 60 + 360) % 360, s: max ? d / max : 0, v: max }; +} + +export function hsvToHex({ h, s, v }: Hsv): string { + const f = (n: number) => { + const k = (n + h / 60) % 6; + const c = v - v * s * Math.max(0, Math.min(k, 4 - k, 1)); + return Math.round(c * 255) + .toString(16) + .padStart(2, '0'); + }; + return `#${f(5)}${f(3)}${f(1)}`; +} + +/** The pure hue at full saturation and value, the colour the field fades from. */ +export function hueHex(h: number): string { + return hsvToHex({ h, s: 1, v: 1 }); +} diff --git a/client/src/utils/dateFormat.test.ts b/client/src/utils/dateFormat.test.ts index 881debc1a..d6b40fee7 100644 --- a/client/src/utils/dateFormat.test.ts +++ b/client/src/utils/dateFormat.test.ts @@ -1,10 +1,9 @@ -// FE-UTIL-DATEFMT-001 to FE-UTIL-DATEFMT-020 +// FE-UTIL-DATEFMT-001 to FE-UTIL-DATEFMT-023 import { describe, expect, it } from 'vitest'; import { dateFieldOrder, dateFormatOptions, dateLayout, - displayDateFormatter, formatDisplayDate, formatDisplayDateTime, isNumericDate, @@ -78,13 +77,27 @@ describe('dateFormat (#2971)', () => { { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }, { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' }, { month: 'long', year: 'numeric', timeZone: 'UTC' }, - { dateStyle: 'medium', timeZone: 'UTC' }, + { dateStyle: 'long', timeZone: 'UTC' }, + { dateStyle: 'full', timeZone: 'UTC' }, ]; for (const opts of named) { expect(formatDisplayDate(NYE, 'de-DE', opts, 'YYYY-MM-DD')).toBe(NYE.toLocaleDateString('de-DE', opts)); } }); + it('FE-UTIL-DATEFMT-022: dateStyle medium follows the format where the language writes it in numbers', () => { + const opts: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeZone: 'UTC' }; + // German "31.12.2026", Japanese "2026/12/31", Czech "31. 12. 2026", Korean "2026. 12. 31.". + for (const locale of ['de-DE', 'ja-JP', 'cs-CZ', 'ko-KR']) { + expect(formatDisplayDate(NYE, locale, opts, 'YYYY-MM-DD')).toBe('2026-12-31'); + } + // English and French name the month, Chinese writes words between the numbers. + for (const locale of ['en-US', 'fr-FR', 'zh-CN']) { + expect(formatDisplayDate(NYE, locale, opts, 'YYYY-MM-DD')).toBe(NYE.toLocaleDateString(locale, opts)); + } + expect(formatDisplayDate(NYE, 'de-DE', opts, 'auto')).toBe(NYE.toLocaleDateString('de-DE', opts)); + }); + it('FE-UTIL-DATEFMT-021: a weekday beside a numeric date keeps the language, the date takes the format', () => { const opts: Intl.DateTimeFormatOptions = { weekday: 'short', @@ -157,30 +170,12 @@ describe('dateFormat (#2971)', () => { }; expect(formatDisplayDateTime(NYE, 'en-US', named, 'YYYY-MM-DD')).toBe(NYE.toLocaleString('en-US', named)); }); - }); - describe('displayDateFormatter', () => { - it('FE-UTIL-DATEFMT-015: auto behaves like Intl.DateTimeFormat', () => { - const intl = new Intl.DateTimeFormat('en-US', NUMERIC); - expect(displayDateFormatter('en-US', NUMERIC, 'auto').format(NYE)).toBe(intl.format(NYE)); - expect(displayDateFormatter('en-US', NUMERIC).format(NYE.getTime())).toBe(intl.format(NYE)); - }); - - it('FE-UTIL-DATEFMT-016: numeric dates follow the format, for Date and timestamp alike', () => { - const f = displayDateFormatter('en-US', NUMERIC, 'DD.MM.YYYY'); - expect(f.format(NYE)).toBe('31.12.2026'); - expect(f.format(NYE.getTime())).toBe('31.12.2026'); - const withTime = displayDateFormatter('en-US', { ...NUMERIC, hour: '2-digit', minute: '2-digit' }, 'YYYY-MM-DD'); - expect(withTime.format(NYE)).toBe( - `2026-12-31 ${NYE.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' })}` - ); - }); - - it('FE-UTIL-DATEFMT-017: a named month is left to Intl', () => { - const opts: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'long', timeZone: 'UTC' }; - expect(displayDateFormatter('de-DE', opts, 'YYYY-MM-DD').format(NYE)).toBe( - new Intl.DateTimeFormat('de-DE', opts).format(NYE) - ); + it('FE-UTIL-DATEFMT-023: dateStyle medium with a time puts the numeric date in the format', () => { + const opts: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }; + const time = NYE.toLocaleTimeString('de-DE', { timeStyle: 'short', timeZone: 'UTC' }); + expect(formatDisplayDateTime(NYE, 'de-DE', opts, 'DD/MM/YYYY')).toBe(`31/12/2026 ${time}`); + expect(formatDisplayDateTime(NYE, 'en-US', opts, 'DD/MM/YYYY')).toBe(NYE.toLocaleString('en-US', opts)); }); }); @@ -206,6 +201,10 @@ describe('dateFormat (#2971)', () => { expect(isNumericDate({ era: 'short' })).toBe(false); expect(isNumericDate({ dateStyle: 'short' })).toBe(true); expect(isNumericDate({ dateStyle: 'long' })).toBe(false); + expect(isNumericDate({ dateStyle: 'medium' }, 'de-DE')).toBe(true); + expect(isNumericDate({ dateStyle: 'medium' }, 'ja-JP')).toBe(true); + expect(isNumericDate({ dateStyle: 'medium' }, 'en-US')).toBe(false); + expect(isNumericDate({ dateStyle: 'long' }, 'de-DE')).toBe(false); }); }); diff --git a/client/src/utils/dateFormat.ts b/client/src/utils/dateFormat.ts index ce562d38f..a803ba18d 100644 --- a/client/src/utils/dateFormat.ts +++ b/client/src/utils/dateFormat.ts @@ -35,20 +35,53 @@ export function dateLayout(format: string | null | undefined): DateLayout | null return LAYOUTS[format as keyof typeof LAYOUTS] ?? null; } +/** 31 December: no day of it reads as a month, so every example and probe of a layout is unambiguous. */ +const SAMPLE = new Date(Date.UTC(2026, 11, 31)); + const DATE_KEYS = ['day', 'month', 'year'] as const; const TIME_KEYS = ['hour', 'minute', 'second', 'dayPeriod', 'fractionalSecondDigits'] as const; /** * Whether these options write the date in numbers only: no weekday, no month - * name, no era. `dateStyle: 'short'` is numeric in every language; the longer - * styles name the month. + * name, no era. `dateStyle: 'short'` is numeric in every language. The longer + * styles depend on the language: 'medium' names the month in English or French + * but is all numbers in German ("31.12.2026"), Czech or Japanese ("2026/12/31"), + * so those are asked of `Intl` for the given locale. */ -export function isNumericDate(opts: Intl.DateTimeFormatOptions = {}): boolean { +export function isNumericDate(opts: Intl.DateTimeFormatOptions = {}, locale?: string): boolean { if (opts.weekday || opts.era) return false; - if (opts.dateStyle) return opts.dateStyle === 'short'; + if (opts.dateStyle) return opts.dateStyle === 'short' || isNumericStyle(opts.dateStyle, locale); return !opts.month || opts.month === 'numeric' || opts.month === '2-digit'; } +const numericStyles = new Map(); + +/** + * Whether a language writes this dateStyle as digits and punctuation alone. A + * month name, a weekday or a word between the numbers ("2026年12月31日") keeps + * it with the language, the same as a month name in explicit options would. + */ +function isNumericStyle(dateStyle: NonNullable, locale?: string): boolean { + const key = `${locale ?? ''}|${dateStyle}`; + let numeric = numericStyles.get(key); + if (numeric === undefined) { + // Separators may carry the bidi marks Arabic puts around them (\p{Cf}). + try { + numeric = new Intl.DateTimeFormat(locale, { dateStyle, timeZone: 'UTC' }) + .formatToParts(SAMPLE) + .every((part) => + part.type === 'literal' + ? /^[\s\p{P}\p{Cf}]*$/u.test(part.value) + : (part.type === 'day' || part.type === 'month' || part.type === 'year') && /^\p{Nd}+$/u.test(part.value) + ); + } catch { + numeric = false; + } + numericStyles.set(key, numeric); + } + return numeric; +} + const hasAny = (opts: Intl.DateTimeFormatOptions, keys: readonly string[]) => keys.some((key) => (opts as Record)[key] !== undefined); @@ -98,7 +131,7 @@ export function formatDisplayDate( const weekday = date.toLocaleDateString(locale, { weekday: opts.weekday, timeZone: opts.timeZone }); return `${weekday}, ${numericDate(date, opts, layout)}`; } - if (!isNumericDate(opts)) return date.toLocaleDateString(locale, opts); + if (!isNumericDate(opts, locale)) return date.toLocaleDateString(locale, opts); return numericDate(date, opts, layout); } @@ -122,7 +155,7 @@ export function formatDisplayDateTime( const layout = dateLayout(format); const named = hasAny(opts, DATE_KEYS) || !!opts.dateStyle; const timed = hasAny(opts, TIME_KEYS) || !!opts.timeStyle; - if (!layout || !isNumericDate(opts) || Number.isNaN(date.getTime())) return date.toLocaleString(locale, opts); + if (!layout || !isNumericDate(opts, locale) || Number.isNaN(date.getTime())) return date.toLocaleString(locale, opts); if (!named && timed) return date.toLocaleString(locale, opts); const day = numericDate(date, opts, layout); if (named && !timed) return day; @@ -130,28 +163,6 @@ export function formatDisplayDateTime( return `${day} ${time}`; } -/** - * A drop-in for `new Intl.DateTimeFormat(locale, opts)` where only `.format()` - * is used: numeric dates in the chosen format, the rest by `Intl`. - */ -export function displayDateFormatter( - locale: string | undefined, - opts: Intl.DateTimeFormatOptions = {}, - format?: string | null -): { format: (date: Date | number) => string } { - const intl = new Intl.DateTimeFormat(locale, opts); - const layout = dateLayout(format); - if (!layout || !isNumericDate(opts)) return { format: (date) => intl.format(date) }; - return { - format: (date) => { - const value = typeof date === 'number' ? new Date(date) : date; - return hasAny(opts, TIME_KEYS) || opts.timeStyle - ? formatDisplayDateTime(value, locale, opts, format) - : formatDisplayDate(value, locale, opts, format); - }, - }; -} - /** The order the fields of a typed date are read in: the chosen format's, or the language's. */ export function dateFieldOrder(locale: string | undefined, format?: string | null): DateField[] { const layout = dateLayout(format); @@ -162,9 +173,6 @@ export function dateFieldOrder(locale: string | undefined, format?: string | nul .map((part) => part.type as DateField); } -/** 31 December: no day of it reads as a month, so every option's example is unambiguous. */ -const SAMPLE = new Date(Date.UTC(2026, 11, 31)); - /** * The choices of the setting, each labelled by how it writes 31 December, and * 'auto' by `autoLabel` with the language's own way in brackets. diff --git a/client/src/utils/dayMerge.test.ts b/client/src/utils/dayMerge.test.ts index b62be0286..3925d604b 100644 --- a/client/src/utils/dayMerge.test.ts +++ b/client/src/utils/dayMerge.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { parseTimeToMinutes, getSpanPhase, hidesOnMiddleDay, getTransportRouteEndpoints, getDisplayTimeForDay, getTransportForDay, getAssignmentReservations, pinnedAway, stopDayIds, getPlaceBookings, getMergedItems, chronoKeyOf, nightRowsOf, rideSeatKey, seatTimedDrop, stayStartingOn, storedRideSlot, timedSlot, type MergedItem } from './dayMerge' +import { parseTimeToMinutes, getSpanPhase, hidesOnMiddleDay, getTransportRouteEndpoints, getDisplayTimeForDay, getTransportForDay, getAssignmentReservations, pinnedAway, stopDayIds, getPlaceBookings, getMergedItems, chronoKeyOf, nightRowsOf, rideSeatKey, seatTimedDrop, yieldTimedBookings, stayStartingOn, storedRideSlot, timedSlot, type MergedItem } from './dayMerge' import { planMergedOrder, withTransportPositions } from './mergedOrder' describe('parseTimeToMinutes', () => { @@ -646,6 +646,52 @@ describe('seatTimedDrop', () => { const order = draw(setup()) expect(seatTimedDrop(order, 1, DAY)).toEqual(order) }) + + // #2983: a flight listed below the day's untimed stops held every slot among them. + const untimedDay = (rides: ReturnType[]): Day => ({ + stops: [stop(1, 'Hotel'), stop(2, 'Shrine'), stop(3, 'Crossing'), stop(4, 'Tower')].map((a, i) => ({ ...a, order_index: i })), + rides, + notes: [], + }) + + it('a ride dropped among untimed stops stays there, and an earlier booking below them makes room ahead of it', () => { + const day = untimedDay([ride(101, '06:30', 3.5), ride(102, '13:00', 3.6)]) + expect(draw(day).map(label)).toEqual(['Hotel', 'Shrine', 'Crossing', 'Tower', 'ride 06:30', 'ride 13:00']) + const { seated, drawn } = drop(day, isRide(102), isStop('Shrine')) + expect(drawn).toEqual(seated) + expect(drawn).toEqual(['Hotel', 'Shrine', 'ride 06:30', 'ride 13:00', 'Crossing', 'Tower']) + }) + + it('a later booking ahead of the drop moves behind it, and the stops keep their order', () => { + const day = untimedDay([ride(101, '09:00', -0.5), ride(102, '18:00', 1.5)]) + expect(draw(day).map(label)).toEqual(['ride 09:00', 'Hotel', 'Shrine', 'ride 18:00', 'Crossing', 'Tower']) + const { seated, drawn } = drop(day, isRide(101), isStop('Tower')) + expect(drawn).toEqual(seated) + expect(drawn).toEqual(['Hotel', 'Shrine', 'Crossing', 'Tower', 'ride 09:00', 'ride 18:00']) + }) + + it('a timed stop in the way still sends the ride back to its time, the bookings stay put', () => { + const day = untimedDay([ride(101, '06:30', 3.5), ride(102, '13:00', 3.6)]) + day.stops[2] = { ...day.stops[2], place: { name: 'Crossing', place_time: '12:00' } } + expect(draw(day).map(label)).toEqual(['Hotel', 'Shrine', 'ride 06:30', 'Crossing', 'Tower', 'ride 13:00']) + const { seated, drawn } = drop(day, isRide(102), isStop('Shrine')) + expect(drawn).toEqual(seated) + expect(drawn).toEqual(['Hotel', 'Shrine', 'ride 06:30', 'Crossing', 'ride 13:00', 'Tower']) + }) +}) + +describe('yieldTimedBookings', () => { + const DAY = 1 + const row = (type: MergedItem['type'], data: Record): MergedItem => ({ type, sortKey: 0, data }) + const place = (id: number) => row('place', { id, place: { place_time: null } }) + const booking = (id: number, time: string | null) => row('transport', { id, day_id: DAY, reservation_time: time }) + + it('leaves an untimed row, a stop and an order without a booking out of place to the caller', () => { + const order = [place(1), booking(2, null), booking(3, '2026-11-20T08:00')] + expect(yieldTimedBookings(order, 1, DAY)).toBeNull() + expect(yieldTimedBookings(order, 0, DAY)).toBeNull() + expect(yieldTimedBookings(order, 2, DAY)).toBeNull() + }) }) @@ -670,14 +716,63 @@ describe('getMergedItems: bookings in different time zones (#2929)', () => { } }) - it('keeps the stops of the day where their clock puts them', () => { + it('keeps a stop with no location, and a note, where their clock puts them', () => { const dayAssignments = [ { id: 10, order_index: 0, place: { place_time: '09:00' } }, { id: 11, order_index: 1, place: { place_time: '18:00' } }, ] - const result = getMergedItems({ dayAssignments, dayNotes: [], dayTransports: [toSeattle, toLA], dayId: DAY }) - // The flights swap the slots they hold between them (17:00 and 20:20); the stops stay put. - expect(result.map(i => `${i.type}:${i.data.id}`)).toEqual(['place:10', 'transport:1', 'place:11', 'transport:2']) + const dayNotes = [{ id: 30, sort_order: 2, time: '18:30' }] + const result = getMergedItems({ dayAssignments, dayNotes, dayTransports: [toSeattle, toLA], dayId: DAY }) + // The flights swap the slots they hold between them (17:00 and 20:20). Without + // coordinates there is no zone to read 18:00 or 18:30 in, so those keep their clock. + expect(result.map(i => `${i.type}:${i.data.id}`)).toEqual(['place:10', 'transport:1', 'place:11', 'note:30', 'transport:2']) + }) + + describe('a stop near an endpoint reads the zone of that endpoint', () => { + const AKL = { lat: -37.0, lng: 174.8, timezone: 'Pacific/Auckland' } + const LAX = { lat: 33.9, lng: -118.4, timezone: 'America/Los_Angeles' } + const SEA = { lat: 47.4, lng: -122.3, timezone: 'America/Los_Angeles' } + const ends = (from: typeof AKL, to: typeof AKL) => [ + { role: 'from', sequence: 0, name: 'A', code: null, local_time: null, local_date: null, ...from }, + { role: 'to', sequence: 1, name: 'B', code: null, local_time: null, local_date: null, ...to }, + ] + const aklLax = { ...toLA, endpoints: ends(AKL, LAX) } + const laxSea = { ...toSeattle, endpoints: ends(LAX, SEA) } + const stopAt = (id: number, time: string, lat: number, lng: number) => + ({ id, order_index: id, place: { place_time: time, lat, lng } }) + const drawn = (dayAssignments: Parameters[0]['dayAssignments'], dayTransports: Parameters[0]['dayTransports']) => + getMergedItems({ dayAssignments, dayNotes: [], dayTransports, dayId: DAY }) + const labels = (items: MergedItem[]) => items.map(i => `${i.type}:${i.data.id}`) + + it('draws a Seattle dinner after the flight to Seattle, and an Auckland breakfast first', () => { + const stops = [stopAt(10, '09:00', -36.85, 174.76), stopAt(12, '19:45', 47.61, -122.33)] + const items = drawn(stops, [laxSea, aklLax]) + expect(labels(items)).toEqual(['place:10', 'transport:1', 'transport:2', 'place:12']) + // The move checks read the same keys, so the drawn order reads as in order. + const keys = items.map(chronoKeyOf(items, DAY, getDisplayTimeForDay)) + expect(keys).toEqual([9 * 60, 17 * 60, 19 * 60 + 45, 20 * 60 + 20]) + }) + + it('draws a dinner in Auckland at the same clock ahead of the flight out', () => { + expect(labels(drawn([stopAt(11, '19:45', -36.85, 174.76)], [laxSea, aklLax]))) + .toEqual(['place:11', 'transport:1', 'transport:2']) + }) + + it('draws a lunch in Los Angeles after the Auckland flight that lands there', () => { + expect(labels(drawn([stopAt(13, '13:00', 34.05, -118.24)], [aklLax]))).toEqual(['transport:1', 'place:13']) + }) + + it('leaves a stop far from every endpoint on its clock', () => { + // Hawaii is no day out from Auckland, Los Angeles or Seattle, so its 19:45 reads no zone. + expect(labels(drawn([stopAt(14, '19:45', 21.3, -157.85)], [laxSea, aklLax]))) + .toEqual(['transport:1', 'place:14', 'transport:2']) + }) + + it('changes nothing on a day whose stops and bookings share one zone', () => { + const hop = { ...laxSea, id: 4, reservation_time: '2026-11-20T08:00', endpoints: ends(LAX, SEA) } + const stops = [stopAt(15, '07:00', 34.05, -118.24), stopAt(16, '12:00', 47.61, -122.33), stopAt(17, '18:00', 47.61, -122.33)] + expect(labels(drawn(stops, [laxSea, hop]))).toEqual(['place:15', 'transport:4', 'place:16', 'transport:2', 'place:17']) + }) }) it('reads the zone from the endpoints when the metadata names none', () => { diff --git a/client/src/utils/dayMerge.ts b/client/src/utils/dayMerge.ts index 83a8036c4..d6a110681 100644 --- a/client/src/utils/dayMerge.ts +++ b/client/src/utils/dayMerge.ts @@ -4,6 +4,7 @@ import { nightVisits, rideSeatAfter, sameDayRide, type CarrierBooking, type Seat // that documents the multi-leg model. Sorting endpoints a second time here is how // the two drift. import { orderedEndpoints, parseReservationMetadata } from './flightLegs' +import { haversineKm, MAX_DAY_TRIP_KM } from './geo' import { zonedInstant } from './zonedTime' export const TRANSPORT_TYPES = new Set(['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'cable_car', 'transit', 'transport_other']) @@ -361,9 +362,10 @@ function applyChronoOrder( /** * The minutes the day orders an item by: its own clock, or for a booking in a known - * zone the clock slot it takes among the day's zoned bookings (#2929). The checks - * that ask whether a move keeps the day in order read the same key, or a day whose - * flights were put in the order they happen would read as out of order on every move. + * zone and a stop near one of its endpoints the clock slot it takes among the day's + * zoned items (#2929, see zonedClockSlots). The checks that ask whether a move keeps the + * day in order read the same key, or a day whose flights and stops were put in the order + * they happen would read as out of order on every move. */ export function chronoKeyOf( items: readonly MergedItem[], @@ -399,13 +401,22 @@ function transportTimeZone(r: MergedItem['data'], dayId: number): string | null } /** - * The clock slots of the day's bookings whose time names an instant: a dated time in a - * known zone. Each local time reads in its own zone, so across zones the clock can run - * backwards: a flight leaving Auckland at 20:20 lands in Los Angeles at 12:25 the same - * date, and the 17:00 flight on from there sorted ahead of it (#2929). Such bookings - * keep the clock slots they hold between them and take them in the order they happen, - * so stops, notes and bookings without a zone stay where the clock puts them. With fewer - * than two the map is empty and the day orders by the clock as before. + * The clock slots of the day's items whose time names an instant: a booking's dated time + * in a known zone, and a stop near one of those bookings' endpoints. Each local time reads + * in its own zone, so across zones the clock can run backwards: a flight leaving Auckland + * at 20:20 lands in Los Angeles at 12:25 the same date, and the 17:00 flight on from there + * sorted ahead of it (#2929). Such items keep the clock slots they hold between them and + * take them in the order they happen. + * + * A stop has to join them, or swapping the flights' slots moves every stop timed between + * the two clocks to the wrong side of the flight it belongs after: a 19:45 dinner in + * Seattle was drawn above the flight to Seattle. A stop carries no zone of its own, so it + * reads the zone of the nearest endpoint within a day's reach, which tells the 19:45 + * dinner in Seattle from a 19:45 dinner in Auckland before the flight out. Notes, stops + * without coordinates or far from every endpoint, and bookings without a zone stay where + * their clock puts them. With fewer than two such items the map is empty and the day + * orders by the clock as before. Where every zone is the same, the order by instant is + * the order by clock and nothing moves. */ function zonedClockSlots( items: MergedItem[], @@ -413,12 +424,14 @@ function zonedClockSlots( getDisplayTime: DisplayTimeOf, clockOf: (it: MergedItem) => number | null ): Map { - const zoned = items.flatMap((it, index) => { + const bookings = items.flatMap((it, index) => { if (it.type !== 'transport') return [] const clock = clockOf(it) - const instant = zonedInstant(getDisplayTime(it.data, dayId), transportTimeZone(it.data, dayId)) - return clock === null || instant === null ? [] : [{ it, index, clock, instant }] + const time = getDisplayTime(it.data, dayId) + const instant = zonedInstant(time, transportTimeZone(it.data, dayId)) + return clock === null || instant === null ? [] : [{ it, index, clock, instant, date: (time as string).slice(0, 10) }] }) + const zoned = [...bookings, ...stopsInZone(items, bookings, clockOf)] const slots = new Map() if (zoned.length < 2) return slots const clocks = zoned.map(z => z.clock).sort((a, b) => a - b) @@ -428,20 +441,100 @@ function zonedClockSlots( return slots } +/** Whether the list draws `order` as it stands. */ +function drawnAsIs(order: readonly MergedItem[], dayId: number, getDisplayTime: DisplayTimeOf): boolean { + return applyChronoOrder([...order], dayId, getDisplayTime).every((it, i) => it === order[i]) +} + +/** + * A day order with the row at `index` kept where it is, and the other timed bookings it + * puts out of time order moved next to it: the ones due earlier right ahead of it, the + * later ones right behind it, each group in the order it had. Stops and notes never move. + * Null when the row has no time, when no booking is out of order, or when the result is + * still not the order the list draws, which is when a timed stop or note stands against it. + * + * A booking nobody can drag otherwise blocks every slot on its far side: with a 06:30 + * flight listed below the day's untimed stops, a 13:00 transit dropped between two of + * them went back behind the flight on every drop (#2983). + */ +export function yieldTimedBookings( + order: readonly MergedItem[], + index: number, + dayId: number, + getDisplayTime: DisplayTimeOf = getDisplayTimeForDay +): MergedItem[] | null { + const moved = order[index] + if (!moved || moved.type === 'place') return null + const keyOf = chronoKeyOf(order, dayId, getDisplayTime) + const own = keyOf(moved) + if (own === null) return null + const ahead: MergedItem[] = [] + const behind: MergedItem[] = [] + order.forEach((it, i) => { + if (it === moved || it.type !== 'transport') return + const key = keyOf(it) + if (key === null) return + if (i > index && key < own) ahead.push(it) + else if (i < index && key > own) behind.push(it) + }) + if (!ahead.length && !behind.length) return null + const yielding = new Set([...ahead, ...behind]) + const kept = order.filter(it => !yielding.has(it)) + const at = kept.indexOf(moved) + const result = [...kept.slice(0, at), ...ahead, moved, ...behind, ...kept.slice(at + 1)] + return drawnAsIs(result, dayId, getDisplayTime) ? result : null +} + +/** + * The timed stops of the day that sit within a day's reach of an endpoint of the zoned + * bookings, with the instant their clock names in that endpoint's zone. The date is the + * one the bookings' times carry on this day; bookings that disagree on it leave every + * stop on its clock. + */ +function stopsInZone( + items: MergedItem[], + bookings: readonly { it: MergedItem; date: string }[], + clockOf: (it: MergedItem) => number | null +): { it: MergedItem; index: number; clock: number; instant: number }[] { + const dates = new Set(bookings.map(b => b.date)) + if (dates.size !== 1) return [] + const [date] = dates + const anchors = bookings.flatMap(b => orderedEndpoints(b.it.data)) + .filter(e => Number.isFinite(e.lat) && Number.isFinite(e.lng) && !!e.timezone) + if (anchors.length === 0) return [] + return items.flatMap((it, index) => { + if (it.type !== 'place') return [] + const clock = clockOf(it) + const place = it.data?.place + if (clock === null || !Number.isFinite(place?.lat) || !Number.isFinite(place?.lng)) return [] + let zone: string | null = null + let nearest = MAX_DAY_TRIP_KM + for (const e of anchors) { + const km = haversineKm({ lat: place.lat, lng: place.lng }, { lat: e.lat, lng: e.lng }) + if (km <= nearest) { nearest = km; zone = e.timezone as string } + } + const hh = String(Math.floor(clock / 60)).padStart(2, '0') + const mm = String(clock % 60).padStart(2, '0') + const instant = zone ? zonedInstant(`${date}T${hh}:${mm}`, zone) : null + return instant === null ? [] : [{ it, index, clock, instant }] + }) +} + /** * A day order with a dragged booking or note at `index`, moved to the nearest slot the * list draws it in. A row with a time is drawn by it, and the untimed rows behind it * take that time too. Dropped against its time, a train went back to its time on the * next render and took every untimed stop behind the drop with it, and the next drag - * stored that order (#2631). So it lands as close to the drop as its time allows and - * nothing else moves. A row without a time, or one the list draws where it was - * dropped, is returned as it came. + * stored that order (#2631). So it stays where it was dropped when only other bookings + * stand against its time, and they make room (`yieldTimedBookings`); against a timed + * stop or note it lands as close to the drop as its time allows and nothing else moves. + * A row without a time, or one the list draws where it was dropped, is returned as it came. */ export function seatTimedDrop( order: readonly MergedItem[], index: number, dayId: number, - getDisplayTime: (r: MergedItem['data'], dayId: number) => string | null = getDisplayTimeForDay + getDisplayTime: DisplayTimeOf = getDisplayTimeForDay ): MergedItem[] { const moved = order[index] if (!moved || moved.type === 'place') return [...order] @@ -449,16 +542,18 @@ export function seatTimedDrop( ? parseTimeToMinutes(moved.data?.time) : parseTimeToMinutes(getDisplayTime(moved.data, dayId)) if (minutes === null) return [...order] + if (drawnAsIs(order, dayId, getDisplayTime)) return [...order] + const yielded = yieldTimedBookings(order, index, dayId, getDisplayTime) + if (yielded) return yielded const rest = order.filter((_, i) => i !== index) - const drawnAsIs = (at: number): MergedItem[] | null => { + const seatAt = (at: number): MergedItem[] | null => { const candidate = [...rest.slice(0, at), moved, ...rest.slice(at)] - const drawn = applyChronoOrder(candidate, dayId, getDisplayTime) - return drawn.every((it, i) => it === candidate[i]) ? candidate : null + return drawnAsIs(candidate, dayId, getDisplayTime) ? candidate : null } - for (let dist = 0; dist <= rest.length; dist++) { - for (const at of dist === 0 ? [index] : [index - dist, index + dist]) { + for (let dist = 1; dist <= rest.length; dist++) { + for (const at of [index - dist, index + dist]) { if (at < 0 || at > rest.length) continue - const seated = drawnAsIs(at) + const seated = seatAt(at) if (seated) return seated } } diff --git a/client/src/utils/donations.test.ts b/client/src/utils/donations.test.ts new file mode 100644 index 000000000..612b428b8 --- /dev/null +++ b/client/src/utils/donations.test.ts @@ -0,0 +1,51 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { isNativeApp } from '../native/platform'; +import { donationsShown, isDonationLink, noticeAsksForDonation, withoutDonationsInApp } from './donations'; + +vi.mock('../native/platform', () => ({ isNativeApp: vi.fn() })); + +const links = [{ href: 'https://ko-fi.com/mauriceboe' }, { href: 'https://discord.gg/x' }]; + +beforeEach(() => { + vi.mocked(isNativeApp).mockReturnValue(false); +}); + +describe('isDonationLink', () => { + it('knows the donation pages, their subdomains too', () => { + expect(isDonationLink('https://ko-fi.com/mauriceboe')).toBe(true); + expect(isDonationLink('https://www.BuyMeACoffee.com/mauriceboe')).toBe(true); + }); + + it('is false for anything else, a missing href or one that is no URL', () => { + expect(isDonationLink('https://github.com/liketrek/TREK')).toBe(false); + expect(isDonationLink('https://notko-fi.com/x')).toBe(false); + expect(isDonationLink(undefined)).toBe(false); + expect(isDonationLink('not a url')).toBe(false); + }); +}); + +describe('in a browser', () => { + it('keeps every link and every notice', () => { + expect(donationsShown()).toBe(true); + expect(withoutDonationsInApp(links)).toEqual(links); + }); +}); + +describe('in the native app', () => { + it('drops the donation links', () => { + vi.mocked(isNativeApp).mockReturnValue(true); + expect(donationsShown()).toBe(false); + expect(withoutDonationsInApp(links)).toEqual([{ href: 'https://discord.gg/x' }]); + }); +}); + +describe('noticeAsksForDonation', () => { + it('looks at both buttons', () => { + expect(noticeAsksForDonation({ cta: { kind: 'link', href: 'https://ko-fi.com/x' } })).toBe(true); + expect(noticeAsksForDonation({ secondaryCta: { kind: 'link', href: 'https://buymeacoffee.com/x' } })).toBe(true); + expect(noticeAsksForDonation({ cta: { kind: 'nav', href: '/settings' }, secondaryCta: null })).toBe(false); + expect(noticeAsksForDonation({ cta: { kind: 'action' } })).toBe(false); + expect(noticeAsksForDonation({})).toBe(false); + }); +}); diff --git a/client/src/utils/donations.ts b/client/src/utils/donations.ts new file mode 100644 index 000000000..41da203ff --- /dev/null +++ b/client/src/utils/donations.ts @@ -0,0 +1,38 @@ +import { isNativeApp } from '../native/platform'; + +/** Where the project takes donations. */ +const DONATION_HOSTS = ['ko-fi.com', 'buymeacoffee.com']; + +/** Whether `href` points at one of the project's donation pages. */ +export function isDonationLink(href: string | undefined): boolean { + if (!href) return false; + let host: string; + try { + host = new URL(href).hostname.toLowerCase(); + } catch { + return false; + } + return DONATION_HOSTS.some((d) => host === d || host.endsWith(`.${d}`)); +} + +/** + * Whether the donation links may show. Not inside the iOS and Android apps: + * the store rules on payments (Apple 3.1.1, Google Play's Payments policy) + * allow no link to an outside payment page there. A browser keeps them. + */ +export function donationsShown(): boolean { + return !isNativeApp(); +} + +/** `links` without the donation pages inside the native apps, unchanged anywhere else. */ +export function withoutDonationsInApp(links: T[]): T[] { + return donationsShown() ? links : links.filter((link) => !isDonationLink(link.href)); +} + +/** A notice button: a link or a navigation carries an href, an action does not. */ +type NoticeButton = { kind: string; href?: string } | null | undefined; + +/** Whether a system notice asks for a donation through one of its buttons. */ +export function noticeAsksForDonation(notice: { cta?: NoticeButton; secondaryCta?: NoticeButton }): boolean { + return isDonationLink(notice.cta?.href) || isDonationLink(notice.secondaryCta?.href); +} diff --git a/client/src/utils/fileDownload.ts b/client/src/utils/fileDownload.ts index 48c1fab70..b9ca0bb6e 100644 --- a/client/src/utils/fileDownload.ts +++ b/client/src/utils/fileDownload.ts @@ -1,6 +1,9 @@ import { getCachedBlob } from '../db/offlineDb' import { isEffectivelyOffline } from '../sync/networkMode' import { isIosStandalone } from './iosDevice' +import { isNativeApp } from '../native/platform' +import { fileNameFromUrl, openNativeFile, shareFile } from '../native/nativeFiles' +import { reportNativeFailure } from '../native/reportFailure' // MIME types safe to open inline (will not execute script in any browser). // Everything else (text/html, image/svg+xml, text/javascript, …) is forced to @@ -74,6 +77,10 @@ async function getFileBlob(url: string): Promise { * in the same tick can abort the download in other browsers. */ export function downloadBlob(blob: Blob, filename: string): void { + if (isNativeApp()) { + shareFile(blob, filename).catch(reportNativeFailure) + return + } const blobUrl = URL.createObjectURL(blob) triggerAnchorDownload(blobUrl, filename) } @@ -87,6 +94,7 @@ export function downloadBlob(blob: Blob, filename: string): void { */ export async function downloadFile(url: string, filename?: string): Promise { const blob = await getFileBlob(url) + if (isNativeApp()) return shareFile(blob, filename ?? fileNameFromUrl(url)) const blobUrl = URL.createObjectURL(blob) triggerAnchorDownload(blobUrl, filename) } @@ -110,6 +118,9 @@ export async function downloadFile(url: string, filename?: string): Promise { const blob = await getFileBlob(url) + // A blob tab has nowhere to open inside the app: the system's viewer shows it, + // or the share sheet where the app has none. + if (isNativeApp()) return openNativeFile(blob, filename ?? fileNameFromUrl(url)) const blobUrl = URL.createObjectURL(blob) // Force download for MIME types that can execute script when rendered inline diff --git a/client/src/utils/flightLiveModel.test.ts b/client/src/utils/flightLiveModel.test.ts new file mode 100644 index 000000000..6afe0d429 --- /dev/null +++ b/client/src/utils/flightLiveModel.test.ts @@ -0,0 +1,127 @@ +// FE-FLIGHTLIVE-MODEL-001 to FE-FLIGHTLIVE-MODEL-012 (011 retired with the great-circle helper) +import type { FlightLiveLeg } from '@trek/shared'; +import { describe, expect, it } from 'vitest'; + +import { airportTime, currentLeg, delayTone, flightLiveView, splitDuration, toMs } from './flightLiveModel'; + +const DEP = Date.parse('2026-06-11T11:50:00Z'); +const ARR = Date.parse('2026-06-11T20:35:00Z'); +const H = 3_600_000; + +function leg(over: Partial = {}): FlightLiveLeg { + return { + reservation_id: 6, + leg_index: 0, + callsign: 'DLH400', + flight_number: 'LH 400', + service_date: '2026-06-11', + origin: { code: 'FRA', name: 'Frankfurt', lat: 50.03, lng: 8.57, timezone: 'Europe/Berlin' }, + destination: { code: 'JFK', name: 'New York JFK', lat: 40.64, lng: -73.78, timezone: 'America/New_York' }, + phase: 'scheduled', + scheduled_departure: new Date(DEP).toISOString(), + scheduled_arrival: new Date(ARR).toISOString(), + departed_at: null, + landed_at: null, + estimated_arrival: null, + departure_delay_min: null, + arrival_delay_min: null, + progress: null, + distance_total_km: 6200, + distance_remaining_km: null, + position: null, + aircraft: null, + last_seen_at: null, + fetched_at: null, + stale: false, + source: null, + ...over, + }; +} + +describe('flightLiveView', () => { + it('FE-FLIGHTLIVE-MODEL-001: counts down to departure while it is more than three hours away', () => { + const view = flightLiveView(leg(), DEP - 5 * H); + expect(view.stage).toBe('upcoming'); + expect(view.countdownMs).toBe(5 * H); + expect(view.progress).toBe(0); + }); + + it('FE-FLIGHTLIVE-MODEL-002: turns to soon within three hours of departure', () => { + expect(flightLiveView(leg(), DEP - 2 * H).stage).toBe('soon'); + }); + + it('FE-FLIGHTLIVE-MODEL-003: reads progress, the estimate and the countdown to landing in the air', () => { + const view = flightLiveView( + leg({ + phase: 'airborne', + departed_at: new Date(DEP + 24 * 60_000).toISOString(), + estimated_arrival: new Date(ARR + 16 * 60_000).toISOString(), + progress: 0.42, + departure_delay_min: 24, + arrival_delay_min: 16, + }), + DEP + 3 * H + ); + expect(view.stage).toBe('airborne'); + expect(view.progress).toBe(0.42); + expect(view.arrExpected).toBe(ARR + 16 * 60_000); + expect(view.arrIsEstimate).toBe(true); + expect(view.countdownMs).toBe(ARR + 16 * 60_000 - (DEP + 3 * H)); + }); + + it('FE-FLIGHTLIVE-MODEL-004: places a stale aircraft by the clock when the feed gave no progress', () => { + const view = flightLiveView(leg({ phase: 'airborne', stale: true }), DEP + (ARR - DEP) / 2); + expect(view.progress).toBeCloseTo(0.5, 5); + expect(view.stale).toBe(true); + }); + + it('FE-FLIGHTLIVE-MODEL-005: a landed flight is full and its arrival is no longer an estimate', () => { + const view = flightLiveView(leg({ phase: 'landed', landed_at: new Date(ARR + 5 * 60_000).toISOString() }), ARR + H); + expect(view.stage).toBe('landed'); + expect(view.progress).toBe(1); + expect(view.arrIsEstimate).toBe(false); + expect(view.countdownMs).toBeNull(); + }); + + it('FE-FLIGHTLIVE-MODEL-006: a schedule long over without any sighting reads as past', () => { + expect(flightLiveView(leg(), ARR + 2 * H).stage).toBe('past'); + }); + + it('FE-FLIGHTLIVE-MODEL-007: passes unknown through, a callsign the feed never heard', () => { + expect(flightLiveView(leg({ phase: 'unknown' }), DEP + H).stage).toBe('unknown'); + }); +}); + +describe('helpers', () => { + it('FE-FLIGHTLIVE-MODEL-008: grades delays as on time, minor and major', () => { + expect(delayTone(null)).toBe('ok'); + expect(delayTone(5)).toBe('ok'); + expect(delayTone(12)).toBe('minor'); + expect(delayTone(30)).toBe('major'); + }); + + it('FE-FLIGHTLIVE-MODEL-009: rounds a duration up to the next minute and splits it', () => { + expect(splitDuration(61_000)).toEqual({ days: 0, hours: 0, minutes: 2 }); + expect(splitDuration(26 * H + 5 * 60_000)).toEqual({ days: 1, hours: 2, minutes: 5 }); + }); + + it('FE-FLIGHTLIVE-MODEL-010: tells the clock at the airport, in 24 or 12 hours, and survives a bad zone', () => { + expect(airportTime(DEP, 'Europe/Berlin', 'en-GB', '24h')).toBe('13:50'); + expect(airportTime(DEP, 'America/New_York', 'en-US', '12h')).toMatch(/7:50\s?AM/); + expect(() => airportTime(DEP, 'Not/AZone', 'en-GB', '24h')).not.toThrow(); + expect(toMs('nonsense')).toBeNull(); + }); + + it('FE-FLIGHTLIVE-MODEL-012: picks the leg a summary speaks for', () => { + const first = leg({ leg_index: 0, phase: 'landed', landed_at: new Date(ARR).toISOString() }); + const second = leg({ + leg_index: 1, + scheduled_departure: new Date(ARR + 2 * H).toISOString(), + scheduled_arrival: new Date(ARR + 4 * H).toISOString(), + }); + expect(currentLeg([], ARR)).toBeNull(); + expect(currentLeg([first, second], ARR + H)?.leg_index).toBe(1); + expect(currentLeg([first, { ...second, phase: 'airborne' }], ARR + 3 * H)?.leg_index).toBe(1); + expect(currentLeg([first], ARR + H)?.leg_index).toBe(0); + }); +}); diff --git a/client/src/utils/flightLiveModel.ts b/client/src/utils/flightLiveModel.ts new file mode 100644 index 000000000..4f2669798 --- /dev/null +++ b/client/src/utils/flightLiveModel.ts @@ -0,0 +1,161 @@ +import type { FlightLiveLeg } from '@trek/shared'; + +/** + * What a live flight card shows, worked out from one leg's state and the clock. + * Pure on purpose: the desktop dialog, the mobile sheet, the plan rows and the + * home-screen widget snapshot all read the same view, so a flight never says + * "in the air" in one place and "departs in 5 min" in another. + */ + +/** + * - upcoming: departure more than three hours away. + * - soon: within three hours of departure, nothing seen yet. + * - taxiing: seen on the ground at the departure airport. + * - airborne: in the air. + * - landed: on the ground at the destination. + * - past: the schedule is over and the feed never confirmed the flight. + * - unknown: the departure time has passed and the callsign never showed up. + */ +export type FlightStage = 'upcoming' | 'soon' | 'taxiing' | 'airborne' | 'landed' | 'past' | 'unknown'; + +/** ok: on time or early; minor: up to half an hour; major: more. */ +export type DelayTone = 'ok' | 'minor' | 'major'; + +export interface FlightLiveView { + stage: FlightStage; + /** Share of the way flown, 0 to 1, for placing the aircraft on the arc. */ + progress: number; + depPlanned: number | null; + /** Observed wheels-up. */ + depActual: number | null; + arrPlanned: number | null; + /** Touchdown once landed, the estimate while flying, else null. */ + arrExpected: number | null; + arrIsEstimate: boolean; + depDelay: number | null; + arrDelay: number | null; + /** Milliseconds to departure (before take-off) or to arrival (in the air). */ + countdownMs: number | null; + /** The feed has heard this aircraft at least once. */ + heard: boolean; + stale: boolean; +} + +const SOON_MS = 3 * 60 * 60 * 1000; +const PAST_MS = 60 * 60 * 1000; +const KEEP_LANDED_MS = 6 * 60 * 60 * 1000; + +export const toMs = (iso: string | null | undefined): number | null => { + if (!iso) return null; + const ms = Date.parse(iso); + return Number.isFinite(ms) ? ms : null; +}; + +const clamp01 = (n: number): number => Math.min(1, Math.max(0, n)); + +export function delayTone(minutes: number | null): DelayTone { + if (minutes == null || minutes <= 5) return 'ok'; + return minutes < 30 ? 'minor' : 'major'; +} + +function stageOf(leg: FlightLiveLeg, now: number, depPlanned: number | null, arrPlanned: number | null): FlightStage { + // A landing, or a flight never heard, says nothing anymore hours after its arrival. + const end = toMs(leg.landed_at) ?? arrPlanned; + if ((leg.phase === 'landed' || leg.phase === 'unknown') && end != null && now > end + KEEP_LANDED_MS) return 'past'; + switch (leg.phase) { + case 'taxiing': + case 'airborne': + case 'landed': + case 'unknown': + return leg.phase; + case 'scheduled': + if (arrPlanned != null && now > arrPlanned + PAST_MS) return 'past'; + if (depPlanned != null && depPlanned - now <= SOON_MS) return 'soon'; + return 'upcoming'; + } +} + +export function flightLiveView(leg: FlightLiveLeg, now: number): FlightLiveView { + const depPlanned = toMs(leg.scheduled_departure); + const arrPlanned = toMs(leg.scheduled_arrival); + const depActual = toMs(leg.departed_at); + const landedAt = toMs(leg.landed_at); + const estimate = toMs(leg.estimated_arrival); + const stage = stageOf(leg, now, depPlanned, arrPlanned); + + const arrExpected = landedAt ?? (stage === 'airborne' ? estimate : null); + const arrIsEstimate = landedAt == null && arrExpected != null; + + let progress = 0; + if (stage === 'landed' || stage === 'past') progress = 1; + else if (stage === 'airborne') { + if (leg.progress != null) progress = leg.progress; + else { + // No position to measure by (stale over an ocean): place it by the clock. + const start = depActual ?? depPlanned; + const end = arrExpected ?? arrPlanned; + if (start != null && end != null && end > start) progress = clamp01((now - start) / (end - start)); + } + } + + let countdownMs: number | null = null; + if ((stage === 'upcoming' || stage === 'soon') && depPlanned != null) countdownMs = Math.max(0, depPlanned - now); + if (stage === 'airborne') { + const end = arrExpected ?? arrPlanned; + if (end != null) countdownMs = Math.max(0, end - now); + } + + return { + stage, + progress: clamp01(progress), + depPlanned, + depActual, + arrPlanned, + arrExpected, + arrIsEstimate, + depDelay: leg.departure_delay_min, + arrDelay: leg.arrival_delay_min, + countdownMs, + heard: leg.last_seen_at != null, + stale: leg.stale, + }; +} + +/** Whole hours and minutes of a duration, rounded up to the next minute. */ +export function splitDuration(ms: number): { days: number; hours: number; minutes: number } { + const total = Math.ceil(ms / 60_000); + return { days: Math.floor(total / 1440), hours: Math.floor((total % 1440) / 60), minutes: total % 60 }; +} + +/** Clock time at an airport, in the user's 12/24 h preference. */ +export function airportTime(ms: number, timezone: string | null, locale: string, timeFormat: string): string { + try { + return new Intl.DateTimeFormat(locale, { + hour: 'numeric', + minute: '2-digit', + hour12: timeFormat === '12h', + timeZone: timezone || undefined, + }).format(ms); + } catch { + // An unknown zone name from an old booking: the device zone is a better answer than none. + return new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: '2-digit', hour12: timeFormat === '12h' }).format( + ms + ); + } +} + +/** + * The leg of a multi-leg booking a one-line summary should speak for: the one + * in the air or on the ground about to leave, else the next one ahead, else + * the last one. Null when nothing is followed. + */ +export function currentLeg(legs: FlightLiveLeg[], now: number): FlightLiveLeg | null { + if (legs.length === 0) return null; + const moving = legs.find((leg) => leg.phase === 'airborne' || leg.phase === 'taxiing'); + if (moving) return moving; + const ahead = legs.find((leg) => { + const arr = toMs(leg.landed_at) ?? toMs(leg.scheduled_arrival); + return leg.phase !== 'landed' && (arr == null || arr > now); + }); + return ahead ?? legs[legs.length - 1]; +} diff --git a/client/src/utils/flightRoute.test.ts b/client/src/utils/flightRoute.test.ts new file mode 100644 index 000000000..0e84f90e8 --- /dev/null +++ b/client/src/utils/flightRoute.test.ts @@ -0,0 +1,43 @@ +// FE-UTIL-FLIGHTROUTE-001 to FE-UTIL-FLIGHTROUTE-004 +import { describe, expect, it } from 'vitest'; +import { bearing, greatCircle, splitRoute } from './flightRoute'; + +const FRA = { lat: 50.03, lng: 8.57 }; +const YYZ = { lat: 43.68, lng: -79.63 }; +const NRT = { lat: 35.77, lng: 140.39 }; +const SFO = { lat: 37.62, lng: -122.38 }; + +describe('flightRoute', () => { + it('FE-UTIL-FLIGHTROUTE-001: runs from end to end and bows towards the pole', () => { + const route = greatCircle(FRA, YYZ, 32); + expect(route).toHaveLength(33); + expect(route[0].lat).toBeCloseTo(FRA.lat, 6); + expect(route[32].lng).toBeCloseTo(YYZ.lng, 6); + // Frankfurt to Toronto passes well north of both, over the North Atlantic towards Greenland. + expect(Math.max(...route.map((p) => p.lat))).toBeGreaterThan(55); + }); + + it('FE-UTIL-FLIGHTROUTE-002: stays one line across the date line', () => { + const route = greatCircle(NRT, SFO, 32); + for (let i = 1; i < route.length; i++) expect(Math.abs(route[i].lng - route[i - 1].lng)).toBeLessThan(20); + // Continued past 180 rather than jumping to -180. + expect(route[32].lng).toBeCloseTo(SFO.lng + 360, 6); + }); + + it('FE-UTIL-FLIGHTROUTE-003: gives the heading at the start', () => { + expect(bearing({ lat: 0, lng: 0 }, { lat: 10, lng: 0 })).toBeCloseTo(0, 6); + expect(bearing({ lat: 0, lng: 0 }, { lat: 0, lng: 10 })).toBeCloseTo(90, 6); + // Westbound across the Atlantic leaves Frankfurt heading north west. + expect(bearing(FRA, YYZ)).toBeGreaterThan(270); + }); + + it('FE-UTIL-FLIGHTROUTE-004: cuts the route where the aircraft is, clamped to its ends', () => { + const route = greatCircle(FRA, YYZ, 10); + const half = splitRoute(route, 0.5); + expect(half.flown[half.flown.length - 1]).toEqual(half.at); + expect(half.ahead[0]).toEqual(half.at); + expect(half.flown.length + half.ahead.length).toBe(route.length + 2); + expect(splitRoute(route, -1).at).toEqual(route[0]); + expect(splitRoute(route, 2).at.lng).toBeCloseTo(route[10].lng, 6); + }); +}); diff --git a/client/src/utils/flightRoute.ts b/client/src/utils/flightRoute.ts new file mode 100644 index 000000000..364525b35 --- /dev/null +++ b/client/src/utils/flightRoute.ts @@ -0,0 +1,69 @@ +/** A point on the globe, degrees. */ +export interface LatLng { + lat: number; + lng: number; +} + +const RAD = Math.PI / 180; + +function toVector({ lat, lng }: LatLng): [number, number, number] { + const φ = lat * RAD; + const λ = lng * RAD; + return [Math.cos(φ) * Math.cos(λ), Math.cos(φ) * Math.sin(λ), Math.sin(φ)]; +} + +/** + * The great circle from `a` to `b` in `steps` equal pieces: the line an + * airliner roughly flies, which on a flat map bows towards the pole. The + * longitudes run on without a jump, so a route across the date line stays one + * line (Leaflet draws 190° as just past 180°) instead of wrapping round the map. + */ +export function greatCircle(a: LatLng, b: LatLng, steps = 64): LatLng[] { + const va = toVector(a); + const vb = toVector(b); + const dot = Math.min(1, Math.max(-1, va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2])); + const ω = Math.acos(dot); + if (ω < 1e-9) return [a, b]; + const points: LatLng[] = []; + let lastLng = a.lng; + for (let i = 0; i <= steps; i++) { + const t = i / steps; + const ka = Math.sin((1 - t) * ω) / Math.sin(ω); + const kb = Math.sin(t * ω) / Math.sin(ω); + const x = ka * va[0] + kb * vb[0]; + const y = ka * va[1] + kb * vb[1]; + const z = ka * va[2] + kb * vb[2]; + const lat = Math.atan2(z, Math.hypot(x, y)) / RAD; + let lng = Math.atan2(y, x) / RAD; + while (lng - lastLng > 180) lng -= 360; + while (lng - lastLng < -180) lng += 360; + lastLng = lng; + points.push({ lat, lng }); + } + return points; +} + +/** Initial bearing from `a` towards `b`, degrees clockwise from north. */ +export function bearing(a: LatLng, b: LatLng): number { + const φ1 = a.lat * RAD; + const φ2 = b.lat * RAD; + const Δλ = (b.lng - a.lng) * RAD; + const y = Math.sin(Δλ) * Math.cos(φ2); + const x = Math.cos(φ1) * Math.sin(φ2) - Math.sin(φ1) * Math.cos(φ2) * Math.cos(Δλ); + return (Math.atan2(y, x) / RAD + 360) % 360; +} + +/** The route cut at `progress` (0 to 1): what is flown, what is left, and the point and heading in between. */ +export function splitRoute( + route: LatLng[], + progress: number +): { flown: LatLng[]; ahead: LatLng[]; at: LatLng; heading: number } { + const last = route.length - 1; + const exact = Math.min(1, Math.max(0, progress)) * last; + const i = Math.min(last - 1, Math.floor(exact)); + const f = exact - i; + const p = route[i]; + const q = route[i + 1]; + const at = { lat: p.lat + (q.lat - p.lat) * f, lng: p.lng + (q.lng - p.lng) * f }; + return { flown: [...route.slice(0, i + 1), at], ahead: [at, ...route.slice(i + 1)], at, heading: bearing(p, q) }; +} diff --git a/client/src/utils/flowText.test.ts b/client/src/utils/flowText.test.ts new file mode 100644 index 000000000..d826dbdba --- /dev/null +++ b/client/src/utils/flowText.test.ts @@ -0,0 +1,34 @@ +/** + * FE-UTIL-FLOW-001 to FE-UTIL-FLOW-003 + * + * "A → B" as one string that reads in the direction of the UI. + */ +import { afterEach, describe, expect, it } from 'vitest'; + +import { flowText, isRtlDocument } from './flowText'; + +const FSI = '\u2068'; +const PDI = '\u2069'; + +describe('flowText', () => { + afterEach(() => { + document.documentElement.dir = ''; + }); + + it('FE-UTIL-FLOW-001: a left-to-right UI gets the plain arrow between the names', () => { + expect(flowText(['Sam Carter', 'Ada'], false)).toBe('Sam Carter → Ada'); + expect(flowText(['Kyoto', 'Osaka', 'Nara'], false)).toBe('Kyoto → Osaka → Nara'); + }); + + it('FE-UTIL-FLOW-002: in Arabic each name is isolated and the arrow points left, from the first to the second', () => { + expect(flowText(['Sam Carter', 'أنت'], true)).toBe(`${FSI}Sam Carter${PDI} ← ${FSI}أنت${PDI}`); + }); + + it('FE-UTIL-FLOW-003: without an explicit direction it follows the document', () => { + expect(isRtlDocument()).toBe(false); + expect(flowText(['A', 'B'])).toBe('A → B'); + document.documentElement.dir = 'rtl'; + expect(isRtlDocument()).toBe(true); + expect(flowText(['A', 'B'])).toBe(`${FSI}A${PDI} ← ${FSI}B${PDI}`); + }); +}); diff --git a/client/src/utils/flowText.ts b/client/src/utils/flowText.ts new file mode 100644 index 000000000..354157ea9 --- /dev/null +++ b/client/src/utils/flowText.ts @@ -0,0 +1,22 @@ +/** + * "Sam → Ada", "Kyoto → Osaka": two names with an arrow from the first to the + * second, as one string (a row's label, an aria-label). + * + * In an Arabic UI the plain form reads backwards. A Latin name and an Arabic one + * reorder around the arrow, and the arrow itself never turns, so "Sam Carter → + * أنت" shows the arrow pointing back at Sam. There each name goes into its own + * isolate (U+2068 … U+2069), so the pair lines up in reading order whatever + * script the names are in, and the arrow points left, from the first name to + * the second. A left-to-right UI gets the plain string. + */ +const FSI = '\u2068'; +const PDI = '\u2069'; + +export function isRtlDocument(): boolean { + return typeof document !== 'undefined' && document.documentElement.dir === 'rtl'; +} + +export function flowText(parts: readonly string[], rtl: boolean = isRtlDocument()): string { + if (!rtl) return parts.join(' → '); + return parts.map((part) => `${FSI}${part}${PDI}`).join(' ← '); +} diff --git a/client/src/utils/heroTrip.test.ts b/client/src/utils/heroTrip.test.ts new file mode 100644 index 000000000..7353bf052 --- /dev/null +++ b/client/src/utils/heroTrip.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest'; +import { heroTrip, sortTripsByRelevance } from './heroTrip'; + +const trip = (id: number, start_date: string | null, end_date: string | null) => ({ id, start_date, end_date }); + +describe('heroTrip', () => { + const today = '2026-11-06'; + const trips = [ + trip(1, '2026-01-01', '2026-01-05'), + trip(2, '2026-12-01', '2026-12-05'), + trip(3, '2026-11-04', '2026-11-12'), + trip(4, '2026-10-20', '2026-11-18'), + trip(5, null, null), + ]; + + it('orders running trips first, then the ones coming up, then the rest, latest first', () => { + expect(sortTripsByRelevance(trips, today).map((t) => t.id)).toEqual([4, 3, 2, 1, 5]); + }); + + it('features the running trip that started first, else the next to come', () => { + expect(heroTrip(sortTripsByRelevance(trips, today), today)?.id).toBe(4); + expect(heroTrip(sortTripsByRelevance([trips[0], trips[1]], today), today)?.id).toBe(2); + expect(heroTrip(sortTripsByRelevance([trips[0], trips[4]], today), today)).toBeNull(); + }); +}); diff --git a/client/src/utils/heroTrip.ts b/client/src/utils/heroTrip.ts new file mode 100644 index 000000000..6f25217b3 --- /dev/null +++ b/client/src/utils/heroTrip.ts @@ -0,0 +1,37 @@ +/** + * Which trip the dashboard features, in one place: the dashboard's hero and + * the iOS widgets (native/widgets.ts) both ask here, so the trip on the home + * screen is always the one the app opens on. + */ +interface DatedTrip { + start_date?: string | null; + end_date?: string | null; +} + +/** 0 running, 1 coming up, 2 past or undated. */ +function rank(trip: DatedTrip, today: string): number { + if (trip.start_date && trip.end_date && trip.start_date <= today && trip.end_date >= today) return 0; + if (trip.start_date && trip.start_date >= today) return 1; + return 2; +} + +/** Running trips first, then the ones coming up, both soonest first; the rest latest first. */ +export function sortTripsByRelevance(trips: T[], today: string): T[] { + return [...trips].sort((a, b) => { + const ra = rank(a, today); + const rb = rank(b, today); + if (ra !== rb) return ra - rb; + const ad = a.start_date || ''; + const bd = b.start_date || ''; + if (ra <= 1) return ad.localeCompare(bd); + return bd.localeCompare(ad); + }); +} + +/** + * The trip the hero features on its own merit: the first running one in that + * order, else the first coming up; null when every trip is past or undated. + */ +export function heroTrip(sorted: T[], today: string): T | null { + return sorted.find((t) => rank(t, today) === 0) || sorted.find((t) => rank(t, today) === 1) || null; +} diff --git a/client/src/utils/lngFrame.test.ts b/client/src/utils/lngFrame.test.ts index 205a6a5ce..a9c992d8a 100644 --- a/client/src/utils/lngFrame.test.ts +++ b/client/src/utils/lngFrame.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { frameLine, frameLng, tripLngFrame } from './lngFrame'; +import { frameLine, frameLng, tripLngFrame, viewLngFrame } from './lngFrame'; const LA = -118.4; const AUCKLAND = 174.8; @@ -83,3 +83,32 @@ describe('frameLine', () => { expect(drawn.map(([, lng]) => lng)).toEqual([30, 20]); }); }); + +describe('viewLngFrame', () => { + it('keeps the plain world while the view looks at the real world', () => { + expect(viewLngFrame(null, 0)).toBeNull(); + expect(viewLngFrame(null, 10)).toBeNull(); + expect(viewLngFrame(null, -90)).toBeNull(); + }); + + it('keeps the frame in use while the view stays near its middle, so a pan redraws nothing', () => { + const frame = { seam: 28.4 }; + expect(viewLngFrame(frame, 208.4)).toBe(frame); + expect(viewLngFrame(frame, 130)).toBe(frame); + }); + + it('centres the frame on a view outside the trip frame, so places found there are drawn there', () => { + // A trip from Los Angeles to Auckland, seamed at 28.4, with the user looking at Europe. + const frame = viewLngFrame({ seam: 28.4 }, 10); + expect(frame).toEqual({ seam: -170 }); + expect(frameLng(frame, 12)).toBeCloseTo(12, 6); + expect(frameLng(frame, 23.7)).toBeCloseTo(23.7, 6); + expect(frameLng(frame, -5)).toBeCloseTo(-5, 6); + }); + + it('centres the frame on a view of a world copy', () => { + const frame = viewLngFrame(null, 495); + expect(frame).toEqual({ seam: 315 }); + expect(frameLng(frame, 139.7)).toBeCloseTo(499.7, 6); + }); +}); diff --git a/client/src/utils/lngFrame.ts b/client/src/utils/lngFrame.ts index 855d4608a..e34d4398b 100644 --- a/client/src/utils/lngFrame.ts +++ b/client/src/utils/lngFrame.ts @@ -106,3 +106,19 @@ export function frameLine( } return out; } + +/** + * A frame for layers fetched for the visible area rather than drawn with the trip, + * such as the POIs the explore pill finds: those come back at their real longitudes + * and belong on the copy the user is looking at, even outside the trip's frame. + * + * The frame in use is kept while the view's centre stays within a quarter world of + * its middle, so a pan does not redraw every marker; past that it is centred on the + * view. Either way a view up to half a world wide lies inside it. `null` is the + * plain world, whose middle is 0, and is kept as null while it fits. + */ +export function viewLngFrame(current: LngFrame | null, centerLng: number): LngFrame | null { + const middle = current ? current.seam + 180 : 0; + if (Math.abs(centerLng - middle) <= 90) return current; + return { seam: centerLng - 180 }; +} diff --git a/client/src/utils/mergedOrder.test.ts b/client/src/utils/mergedOrder.test.ts index f66433582..a5d5050af 100644 --- a/client/src/utils/mergedOrder.test.ts +++ b/client/src/utils/mergedOrder.test.ts @@ -2,11 +2,13 @@ // phone's plan timeline both derive from a day's new timeline order. import { describe, expect, it } from 'vitest'; +import { getMergedItems } from './dayMerge'; import { keepDayPositions, metadataWithLegPositions, moveRow, planMergedOrder, + withHiddenRows, withTransportPositions, } from './mergedOrder'; @@ -106,3 +108,38 @@ describe('keepDayPositions', () => { expect(keepDayPositions({ id: 1 }, undefined)).toEqual({ id: 1 }); }); }); + +describe('planMergedOrder over a day with hidden rows (#3100)', () => { + it('FE-UTIL-MERGEDORDER-010: hidden rows keep their slots and the shown rows fill the rest in their new order', () => { + expect(withHiddenRows([10, 1, 2, 11], [2, 1])).toEqual([10, 2, 1, 11]); + expect(withHiddenRows([1, 2], [2, 1])).toEqual([2, 1]); + }); + + it('FE-UTIL-MERGEDORDER-011: bookings and notes are positioned in the full day the places are stored in', () => { + const plan = planMergedOrder([transport(8), place(1), note(7), transport(9), place(2)], [10, 1, 2]); + expect(plan.assignmentIds).toEqual([1, 2]); + expect(plan.transportUpdates).toEqual([ + { id: 8, day_plan_position: 0.5 }, + { id: 9, day_plan_position: 1 + 2 / 3 }, + ]); + expect(plan.noteUpdates).toEqual([{ id: 7, sort_order: 1 + 1 / 3 }]); + }); + + it('FE-UTIL-MERGEDORDER-012: an untimed stop dropped between two timed bookings stays there behind a hidden hotel row', () => { + const dayId = 5; + const tour = { id: 8, day_id: dayId, reservation_time: '2026-11-25T12:00' }; + const flight = { id: 9, day_id: dayId, reservation_time: '2026-11-25T19:15' }; + const newOrder = [transport(8), place(1), transport(9), place(2)]; + const plan = planMergedOrder(newOrder, [10, 2, 1]); + const stored = withHiddenRows([10, 2, 1], plan.assignmentIds); + const dayAssignments = stored + .filter((id) => id !== 10) + .map((id) => ({ id, order_index: stored.indexOf(id), place: { place_time: null } })); + const positioned = [tour, flight].map((r) => { + const update = plan.transportUpdates.find((u) => u.id === r.id); + return { ...r, day_positions: { [dayId]: update?.day_plan_position } }; + }); + const drawn = getMergedItems({ dayAssignments, dayNotes: [], dayTransports: positioned, dayId }); + expect(drawn.map((it) => `${it.type}:${it.data.id}`)).toEqual(['transport:8', 'place:1', 'transport:9', 'place:2']); + }); +}); diff --git a/client/src/utils/mergedOrder.ts b/client/src/utils/mergedOrder.ts index 99e388ee8..da32cb596 100644 --- a/client/src/utils/mergedOrder.ts +++ b/client/src/utils/mergedOrder.ts @@ -42,24 +42,49 @@ export function moveRow( return { order: moved, index }; } -export function planMergedOrder(newOrder: readonly MergedOrderItem[]): MergedOrderPlan { +/** + * The day's full stored order once the rows on screen take the order given: a row the + * list does not show keeps its slot, and the shown rows fill the remaining slots in + * their new order. + */ +export function withHiddenRows(storedIds: readonly number[], visibleIds: readonly number[]): number[] { + const visible = new Set(visibleIds); + let next = 0; + return storedIds.map((id) => (visible.has(id) ? visibleIds[next++] : id)); +} + +/** + * `storedIds` is the day's full stored order when the timeline leaves rows out (the + * desktop list hides the stop a lodging booking puts on the day). The places are stored + * across that full day, so a booking or note has to be positioned in the same count, or + * every hidden row ahead of a place pushed that place one slot behind the booking it was + * dropped above (#3100). Without it the timeline is taken to show the whole day. + */ +export function planMergedOrder(newOrder: readonly MergedOrderItem[], storedIds?: readonly number[]): MergedOrderPlan { const plan: MergedOrderPlan = { assignmentIds: [], noteUpdates: [], transportUpdates: [], legPosUpdates: {} }; - let placeCount = 0; + for (const item of newOrder) if (item.type === 'place') plan.assignmentIds.push(item.data.id); + const full = storedIds ? withHiddenRows(storedIds, plan.assignmentIds) : plan.assignmentIds; + const slotOf = (id: number): number => { + const at = full.indexOf(id); + return at === -1 ? plan.assignmentIds.indexOf(id) : at; + }; + let lastPlaceId: number | null = null; let i = 0; while (i < newOrder.length) { if (newOrder[i].type === 'place') { - plan.assignmentIds.push(newOrder[i].data.id); - placeCount++; + lastPlaceId = newOrder[i].data.id; i++; continue; } - // Consecutive non-place items share the gap after the place before them. + // Consecutive non-place items share the gap after the place before them, or the + // gap ahead of the first place when they open the day. const group: MergedOrderItem[] = []; while (i < newOrder.length && newOrder[i].type !== 'place') { group.push(newOrder[i]); i++; } - const base = placeCount > 0 ? placeCount - 1 : -1; + const nextPlace = newOrder.slice(i).find((it) => it.type === 'place'); + const base = lastPlaceId !== null ? slotOf(lastPlaceId) : nextPlace ? slotOf(nextPlace.data.id) - 1 : -1; group.forEach((g, idx) => { const pos = base + (idx + 1) / (group.length + 1); if (g.type === 'note') plan.noteUpdates.push({ id: g.data.id, sort_order: pos }); diff --git a/client/src/utils/pdfSwitch.test.ts b/client/src/utils/pdfSwitch.test.ts index 09707c99e..45931c832 100644 --- a/client/src/utils/pdfSwitch.test.ts +++ b/client/src/utils/pdfSwitch.test.ts @@ -1,4 +1,4 @@ -// FE-UTIL-PDFSWITCH-001 to FE-UTIL-PDFSWITCH-002 +// FE-UTIL-PDFSWITCH-001 to FE-UTIL-PDFSWITCH-003 import { afterEach, describe, expect, it, vi } from 'vitest'; import { pdfSwitchOn, rememberPdfSwitch } from './pdfSwitch'; @@ -28,6 +28,15 @@ describe('pdfSwitch', () => { throw new Error('blocked'); }); expect(pdfSwitchOn(KEY)).toBe(true); + expect(pdfSwitchOn(KEY, false)).toBe(false); expect(() => rememberPdfSwitch(KEY, false)).not.toThrow(); }); + + it('FE-UTIL-PDFSWITCH-003: a switch that defaults to off stays off until it is turned on', () => { + expect(pdfSwitchOn(KEY, false)).toBe(false); + rememberPdfSwitch(KEY, true); + expect(pdfSwitchOn(KEY, false)).toBe(true); + rememberPdfSwitch(KEY, false); + expect(pdfSwitchOn(KEY, false)).toBe(false); + }); }); diff --git a/client/src/utils/pdfSwitch.ts b/client/src/utils/pdfSwitch.ts index 2954de87c..de92b8cec 100644 --- a/client/src/utils/pdfSwitch.ts +++ b/client/src/utils/pdfSwitch.ts @@ -1,14 +1,15 @@ /* - * The two switches of the trip PDF preview (a new page for every day, and the notes - * of the transports), remembered in this browser. + * The switches of the trip PDF preview (a new page for every day, the notes of + * the transports, large text), remembered in this browser. */ -/** A preview switch that is on unless it was turned off; both default to on. */ -export function pdfSwitchOn(key: string): boolean { +/** A preview switch as it was last left; `defaultOn` until it is first touched, or when storage is blocked. */ +export function pdfSwitchOn(key: string, defaultOn = true): boolean { try { - return localStorage.getItem(key) !== '0'; + const stored = localStorage.getItem(key); + return stored === null ? defaultOn : stored !== '0'; } catch { - return true; + return defaultOn; } } diff --git a/client/src/utils/placeSearch.test.ts b/client/src/utils/placeSearch.test.ts index 01677361f..fab74f70f 100644 --- a/client/src/utils/placeSearch.test.ts +++ b/client/src/utils/placeSearch.test.ts @@ -1,6 +1,6 @@ // FE-UTIL-PLACESEARCH-001 to FE-UTIL-PLACESEARCH-004 import { describe, it, expect } from 'vitest' -import { placeMatchesSearch } from './placeSearch' +import { foldForSearch, placeMatchesSearch, textMatchesSearch } from './placeSearch' const place = { name: 'Café Central', @@ -32,3 +32,25 @@ describe('placeMatchesSearch', () => { expect(placeMatchesSearch(place, 'pizza')).toBe(false) }) }) + +describe('search without accents (#3075)', () => { + it('FE-UTIL-PLACESEARCH-005: a query without accents finds the accented name, and the other way round', () => { + for (const [query, name] of [['Obidos', 'Óbidos'], ['Evora', 'Évora'], ['Sao Bras', 'São Brás'], ['Loule', 'Loulé']]) { + expect(placeMatchesSearch({ name, address: null, description: null, notes: null }, query)).toBe(true) + expect(placeMatchesSearch({ name: query, address: null, description: null, notes: null }, name)).toBe(true) + } + }) + + it('FE-UTIL-PLACESEARCH-006: letters with the mark built in fold to their plain spelling', () => { + expect(foldForSearch('Straße')).toBe('strasse') + expect(foldForSearch('Łódź')).toBe('lodz') + expect(foldForSearch('Ærø')).toBe('aero') + expect(textMatchesSearch(['Kraków'], 'krakow')).toBe(true) + }) + + it('FE-UTIL-PLACESEARCH-007: marks that change a word outside Latin script stay, so が is not か', () => { + expect(foldForSearch('が')).toBe('が') + expect(textMatchesSearch(['かき'], 'がき')).toBe(false) + expect(foldForSearch('한국')).toBe('한국') + }) +}) diff --git a/client/src/utils/placeSearch.ts b/client/src/utils/placeSearch.ts index caecc18ea..885e8c9da 100644 --- a/client/src/utils/placeSearch.ts +++ b/client/src/utils/placeSearch.ts @@ -10,9 +10,33 @@ type Searchable = Pick * can never disagree about what a search finds. */ export function placeMatchesSearch(place: Searchable, query: string): boolean { - const q = query.trim().toLowerCase() - if (!q) return true - return [place.name, place.address, place.description, place.notes].some( - field => !!field && field.toLowerCase().includes(q), - ) + return textMatchesSearch([place.name, place.address, place.description, place.notes], query) +} + +/** The combining accents of Latin script (U+0300 to U+036F), the marks NFD splits off a letter. */ +const LATIN_MARKS = new RegExp(`[${String.fromCharCode(0x300)}-${String.fromCharCode(0x36f)}]`, 'g') + +/** Letters that carry their mark in the letter itself, so taking the marks off leaves them as they are. */ +const FOLDED_LETTERS: Record = { ß: 'ss', ø: 'o', æ: 'ae', œ: 'oe', ł: 'l', đ: 'd', ð: 'd', þ: 'th', ı: 'i' } + +/** + * Text as a search compares it: lower case and without accents, so "Obidos" finds + * "Óbidos", "Sao Bras" finds "São Brás" and the other way round (#3075). Only + * Latin marks go: a kana's voicing mark or a Hangul syllable stays whole, since + * there it changes the word. + */ +export function foldForSearch(text: string): string { + return text + .toLocaleLowerCase() + .normalize('NFD') + .replace(LATIN_MARKS, '') + .replace(/[ßøæœłđðþı]/g, ch => FOLDED_LETTERS[ch] ?? ch) + .normalize('NFC') +} + +/** Whether any of the fields holds the query, accents and case aside. An empty query matches everything. */ +export function textMatchesSearch(fields: readonly (string | null | undefined)[], query: string): boolean { + const q = foldForSearch(query.trim()) + if (!q) return true + return fields.some(field => !!field && foldForSearch(field).includes(q)) } diff --git a/client/src/utils/placeTags.test.ts b/client/src/utils/placeTags.test.ts new file mode 100644 index 000000000..b55f8b85c --- /dev/null +++ b/client/src/utils/placeTags.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from 'vitest'; + +import { buildPlace, buildTag } from '../../tests/helpers/factories'; +import { + TAG_COLORS, + nextTagColor, + placeTagIds, + tagChanges, + tagChoices, + withTagChanges, + withTripTag, +} from './placeTags'; + +describe('placeTags', () => { + it('FE-UTIL-PLTAGS-001: offers each tag once and by name, as the first list that has it says', () => { + const zone = buildTag({ id: 2, name: 'Zone', color: '#10b981' }); + const monument = buildTag({ id: 1, name: 'Monument', color: '#6366f1' }); + const carried = [ + { id: 2, name: 'Zone (old name)', color: '#000000' }, + { id: 9, name: 'Hidden gem', color: '#f97316' }, + ]; + expect(tagChoices([zone, monument], carried, undefined)).toEqual([ + { id: 9, name: 'Hidden gem', color: '#f97316' }, + { id: 1, name: 'Monument', color: '#6366f1' }, + { id: 2, name: 'Zone', color: '#10b981' }, + ]); + expect(tagChoices()).toEqual([]); + expect(tagChoices(undefined)).toEqual([]); + }); + + it('FE-UTIL-PLTAGS-002: leaves out a copy that cannot be shown and a colour that is no plain hex value', () => { + const choices = tagChoices([ + { name: 'No id' }, + { id: 3 }, + { id: 4, name: 'Painted', color: 'url(https://example.test/pixel)' }, + { id: 5, name: 'Plain' }, + ]); + expect(choices).toEqual([ + { id: 4, name: 'Painted', color: undefined }, + { id: 5, name: 'Plain', color: undefined }, + ]); + expect(choices[0].color).toBeUndefined(); + }); + + it('FE-UTIL-PLTAGS-003: names the tags of a place by id, each once, whatever else the copy lacks', () => { + expect(placeTagIds([{ id: 4, name: 'A' }, { id: 5 }, { name: 'No id' }, { id: 4, name: 'A' }])).toEqual([4, 5]); + expect(placeTagIds(undefined)).toEqual([]); + }); + + it('FE-UTIL-PLTAGS-004: colours new tags by turn', () => { + const first = nextTagColor([]); + const second = nextTagColor([buildTag()]); + expect(first).toMatch(/^#[0-9a-f]{6}$/); + expect(second).toMatch(/^#[0-9a-f]{6}$/); + expect(second).not.toBe(first); + // Past the last colour it starts over. + expect(nextTagColor(Array.from({ length: TAG_COLORS.length }, () => buildTag()))).toBe(first); + }); + + it('FE-UTIL-PLTAGS-005: adds a tag to the list by name, and replaces the one of the same id', () => { + const monument = buildTag({ id: 1, name: 'Monument' }); + const zone = buildTag({ id: 2, name: 'Zone' }); + const added = withTripTag([zone], monument); + expect(added.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + const renamed = withTripTag(added, { ...zone, name: 'Area' }); + expect(renamed.map((tag) => [tag.id, tag.name])).toEqual([ + [2, 'Area'], + [1, 'Monument'], + ]); + }); + + it('FE-UTIL-PLTAGS-006: tells which tags were renamed, recoloured or deleted between two readings', () => { + const monument = buildTag({ id: 1, name: 'Monument', color: '#6366f1' }); + const zone = buildTag({ id: 2, name: 'Zone', color: '#10b981' }); + const walk = buildTag({ id: 3, name: 'Walk', color: '#f97316' }); + expect(tagChanges([monument, zone], [monument, zone])).toBeNull(); + // A new tag is on no place yet, so it changes nothing there. + expect(tagChanges([monument], [monument, zone])).toBeNull(); + const changes = tagChanges( + [monument, zone, walk], + [ + { ...monument, name: 'Landmark' }, + { ...walk, color: '#ef4444' }, + ] + ); + expect([...(changes?.removed ?? [])]).toEqual([2]); + expect([...(changes?.renamed.keys() ?? [])]).toEqual([1, 3]); + }); + + it('FE-UTIL-PLTAGS-007: takes the changes into the copies a place carries, and leaves an untouched place alone', () => { + const monument = buildTag({ id: 1, name: 'Monument', color: '#6366f1' }); + const zone = buildTag({ id: 2, name: 'Zone', color: '#10b981' }); + const changes = tagChanges([monument, zone], [{ ...monument, name: 'Landmark', color: '#ef4444' }]); + if (!changes) throw new Error('expected changes'); + const place = buildPlace({ + tags: [ + { id: 1, name: 'Monument', color: '#6366f1', created_at: '2026-01-01' }, + { id: 2, name: 'Zone' }, + { id: 9, name: 'Own' }, + { name: 'No id' }, + ], + }); + expect(withTagChanges(place, changes).tags).toEqual([ + { id: 1, name: 'Landmark', color: '#ef4444', created_at: '2026-01-01' }, + { id: 9, name: 'Own' }, + { name: 'No id' }, + ]); + const untouched = buildPlace({ tags: [{ id: 9, name: 'Own' }] }); + expect(withTagChanges(untouched, changes)).toBe(untouched); + const untagged = buildPlace(); + expect(withTagChanges(untagged, changes)).toBe(untagged); + }); +}); diff --git a/client/src/utils/placeTags.ts b/client/src/utils/placeTags.ts new file mode 100644 index 000000000..2b5d85749 --- /dev/null +++ b/client/src/utils/placeTags.ts @@ -0,0 +1,91 @@ +import type { Place, Tag } from '@trek/shared'; + +import { safeHexColor } from './safeColor'; + +/** A tag as a place carries it: the compact row of a place list, where every field is optional. */ +type PlaceTag = NonNullable[number]; + +/** A tag as a picker, a filter row and a chip show it. */ +export interface TagChoice { + id: number; + name: string; + /** Absent for a colour that is no plain hex value: the chip then keeps the colour of its text. */ + color?: string; +} + +/** + * The tags of the given lists, each once and by name, as far as they can be shown. A tag + * reads as the first list that has it says, so with the trip's own tags ahead of the + * copies a place carries, the name and the colour are the current ones. + */ +export function tagChoices(...lists: (readonly PlaceTag[] | undefined)[]): TagChoice[] { + const choices = new Map(); + for (const tag of lists.flatMap((list) => list ?? [])) { + if (tag.id == null || !tag.name || choices.has(tag.id)) continue; + choices.set(tag.id, { id: tag.id, name: tag.name, color: safeHexColor(tag.color, '') || undefined }); + } + return [...choices.values()].sort((a, b) => a.name.localeCompare(b.name)); +} + +/** The ids of the tags a place carries, as a write names them. */ +export function placeTagIds(carried: readonly PlaceTag[] | undefined): number[] { + return [...new Set((carried ?? []).flatMap((tag) => (tag.id == null ? [] : [tag.id])))]; +} + +// What a new tag is coloured with, one after the other, so the tags of a trip tell apart at a glance. +export const TAG_COLORS = [ + '#6366f1', + '#ec4899', + '#f97316', + '#10b981', + '#06b6d4', + '#8b5cf6', + '#ef4444', + '#f59e0b', + '#84cc16', + '#64748b', +]; + +/** The colour the next new tag of a trip gets. */ +export function nextTagColor(tripTags: readonly unknown[]): string { + return TAG_COLORS[tripTags.length % TAG_COLORS.length]; +} + +/** The trip's tags with one more, or with the one of that id as it is now, by name as the server lists them. */ +export function withTripTag(tripTags: readonly Tag[], tag: Tag): Tag[] { + return [...tripTags.filter((other) => other.id !== tag.id), tag].sort((a, b) => a.name.localeCompare(b.name)); +} + +/** What changed between two readings of a trip's tags, as far as the copies on its places go. */ +interface TagChanges { + /** The tags that are gone. */ + removed: ReadonlySet; + /** The tags with another name or colour, as they are now. */ + renamed: ReadonlyMap; +} + +/** Null when no tag was renamed, recoloured or deleted between the two readings. */ +export function tagChanges(before: readonly Tag[], after: readonly Tag[]): TagChanges | null { + const now = new Map(after.map((tag) => [tag.id, tag])); + const removed = new Set(); + const renamed = new Map(); + for (const old of before) { + const tag = now.get(old.id); + if (!tag) removed.add(old.id); + else if (tag.name !== old.name || tag.color !== old.color) renamed.set(tag.id, tag); + } + return removed.size > 0 || renamed.size > 0 ? { removed, renamed } : null; +} + +/** A place with its tags as the trip has them now; the same object when none of its tags changed. */ +export function withTagChanges

    (place: P, changes: TagChanges): P { + const touched = (tag: PlaceTag) => tag.id != null && (changes.removed.has(tag.id) || changes.renamed.has(tag.id)); + if (!place.tags?.some(touched)) return place; + const tags = place.tags + .filter((tag) => tag.id == null || !changes.removed.has(tag.id)) + .map((tag) => { + const now = tag.id == null ? undefined : changes.renamed.get(tag.id); + return now ? { ...tag, name: now.name, color: now.color } : tag; + }); + return { ...place, tags }; +} diff --git a/client/src/utils/placesFilter.test.ts b/client/src/utils/placesFilter.test.ts index 741f65e78..ab659e421 100644 --- a/client/src/utils/placesFilter.test.ts +++ b/client/src/utils/placesFilter.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest' import { buildPlace } from '../../tests/helpers/factories' import { RATING_FLOORS, countActivePlacesFilters, matchesCategoryFilter, matchesPlacesFilter, - matchesPoolFilter, matchesRatingFloor, + matchesPoolFilter, matchesRatingFloor, tagFilterKey, withoutTagFilters, } from './placesFilter' const NONE = new Set() @@ -67,4 +67,44 @@ describe('placesFilter', () => { expect(countActivePlacesFilters({ filter: 'all', categoryFilters: new Set(['1', '2']), ratingFilter: 'all' })).toBe(1) expect(countActivePlacesFilters({ filter: 'tracks', categoryFilters: new Set(['1']), ratingFilter: 3 })).toBe(3) }) + + it('FE-UTIL-PLFILTER-008: a ticked tag keeps the places that carry it, whatever their category', () => { + const monument = buildPlace({ category_id: 4, tags: [{ id: 7, name: 'Monument' }, { id: 8, name: 'Zone' }] }) + const plain = buildPlace({ category_id: 4 }) + const bare = buildPlace({ category_id: null, tags: [{ id: 8, name: 'Zone' }] }) + expect(tagFilterKey(7)).toBe('tag:7') + expect(matchesCategoryFilter(monument, new Set(['tag:7']))).toBe(true) + expect(matchesCategoryFilter(plain, new Set(['tag:7']))).toBe(false) + expect(matchesCategoryFilter(bare, new Set(['tag:7']))).toBe(false) + // Several ticked tags: carrying one of them is enough. + expect(matchesCategoryFilter(bare, new Set(['tag:7', 'tag:8']))).toBe(true) + // A copy without an id (a row still being written) matches no tag. + expect(matchesCategoryFilter(buildPlace({ tags: [{ name: 'Zone' }] }), new Set(['tag:8']))).toBe(false) + }) + + it('FE-UTIL-PLFILTER-009: categories and tags ticked together both have to hold', () => { + const monument = buildPlace({ category_id: 4, tags: [{ id: 7, name: 'Monument' }] }) + const other = buildPlace({ category_id: 5, tags: [{ id: 7, name: 'Monument' }] }) + const untagged = buildPlace({ category_id: 4 }) + const bare = buildPlace({ category_id: null, tags: [{ id: 7, name: 'Monument' }] }) + const both = new Set(['4', 'tag:7']) + expect(matchesCategoryFilter(monument, both)).toBe(true) + expect(matchesCategoryFilter(other, both)).toBe(false) + expect(matchesCategoryFilter(untagged, both)).toBe(false) + expect(matchesCategoryFilter(bare, both)).toBe(false) + expect(matchesCategoryFilter(bare, new Set(['uncategorized', 'tag:7']))).toBe(true) + // The whole filter follows: the tag narrows the list and the map alike. + const state = { filter: 'all', categoryFilters: both, ratingFilter: 'all' as const } + expect(matchesPlacesFilter(monument, state, { plannedIds: null })).toBe(true) + expect(matchesPlacesFilter(untagged, state, { plannedIds: null })).toBe(false) + expect(countActivePlacesFilters(state)).toBe(1) + }) + + it('FE-UTIL-PLFILTER-010: a tag that is gone leaves the filter, and a filter without it stays the same set', () => { + const filters = new Set(['4', 'tag:7', 'tag:8']) + expect([...withoutTagFilters(filters, [7])]).toEqual(['4', 'tag:8']) + expect([...withoutTagFilters(filters, new Set([7, 8, 9]))]).toEqual(['4']) + expect(withoutTagFilters(filters, [9])).toBe(filters) + expect(withoutTagFilters(filters, [])).toBe(filters) + }) }) diff --git a/client/src/utils/placesFilter.ts b/client/src/utils/placesFilter.ts index a4fce60c9..c91993bbc 100644 --- a/client/src/utils/placesFilter.ts +++ b/client/src/utils/placesFilter.ts @@ -2,12 +2,12 @@ import type { Place } from '../types' /** * The trip's places filter, in one place: the pool (all / unplanned / planned / - * tracks), the category set and the minimum rating. The desktop list, the phone - * list and the map markers of both shells apply this same predicate to the same - * values, held in the trip store (#1541). The map keeps two deliberate - * differences of its own: with a day open, "planned" shows that day's plan only - * (#2024), and the stops of collapsed days are left off the map (except under - * "planned"). + * tracks), the category set, which the tags filter through as well, and the + * minimum rating. The desktop list, the phone list and the map markers of both + * shells apply this same predicate to the same values, held in the trip store + * (#1541). The map keeps two deliberate differences of its own: with a day + * open, "planned" shows that day's plan only (#2024), and the stops of + * collapsed days are left off the map (except under "planned"). */ /** A minimum of average stars: 'all', or a floor that unrated places fall through. */ @@ -19,12 +19,36 @@ export const RATING_FLOORS = ['all', 5, 4, 3, 2, 1] as const /** The pseudo category id that stands for "no category". */ export const UNCATEGORIZED = 'uncategorized' +const TAG_KEY = 'tag:' + +/** A tag's entry in the category filter set, which holds category ids, UNCATEGORIZED and these. */ +export const tagFilterKey = (tagId: number): string => `${TAG_KEY}${tagId}` + +/** + * The ticked categories and the ticked tags are two questions with one answer each: + * a place passes when it is in one of the ticked categories, if any is ticked, and + * carries one of the ticked tags, if any is ticked. + */ export function matchesCategoryFilter(place: Place, categoryFilters: ReadonlySet): boolean { if (categoryFilters.size === 0) return true + const tagsTicked = [...categoryFilters].filter(key => key.startsWith(TAG_KEY)).length + if (tagsTicked > 0 && !carriesTickedTag(place, categoryFilters)) return false + if (tagsTicked === categoryFilters.size) return true if (place.category_id == null) return categoryFilters.has(UNCATEGORIZED) return categoryFilters.has(String(place.category_id)) } +function carriesTickedTag(place: Place, ticked: ReadonlySet): boolean { + return (place.tags ?? []).some(tag => tag.id != null && ticked.has(tagFilterKey(tag.id))) +} + +/** The filter set without the entries of tags that are gone; the same set when it held none of them. */ +export function withoutTagFilters(categoryFilters: Set, goneTagIds: Iterable): Set { + const gone = [...goneTagIds].map(tagFilterKey).filter(key => categoryFilters.has(key)) + if (gone.length === 0) return categoryFilters + return new Set([...categoryFilters].filter(key => !gone.includes(key))) +} + export function matchesRatingFloor(place: Place, floor: PlacesRatingFloor): boolean { if (floor === 'all') return true return place.rating_avg != null && place.rating_avg >= floor diff --git a/client/src/utils/tileUrl.ts b/client/src/utils/tileUrl.ts index 5e464e489..9fbc2c5b2 100644 --- a/client/src/utils/tileUrl.ts +++ b/client/src/utils/tileUrl.ts @@ -132,3 +132,16 @@ export function resolveBasemap( if (isVectorStyle(chosen)) return { kind: 'vector', style: chosen } return { kind: 'raster', url: chosen } } + +/** Hosts whose tiles may not be stored for offline use at all (OSM tile usage policy). */ +const NO_OFFLINE_HOSTS = ['tile.openstreetmap.org']; + +/** Whether a raster template's host forbids storing its tiles (the offline basemap stands in). */ +export function isOfflineForbiddenTemplate(template: string): boolean { + try { + const host = new URL(template.replace(/\{s\}/g, 'a')).hostname; + return NO_OFFLINE_HOSTS.some((h) => host === h || host.endsWith(`.${h}`)); + } catch { + return false; + } +} diff --git a/client/src/utils/versionHandover.test.ts b/client/src/utils/versionHandover.test.ts index 61e2c8bf6..2cf25b3f2 100644 --- a/client/src/utils/versionHandover.test.ts +++ b/client/src/utils/versionHandover.test.ts @@ -447,6 +447,30 @@ describe('reconcileAppVersion: a page loaded past an older worker', () => { }) }) +describe("reconcileAppVersion: during the app's sign-in in the browser", () => { + it('FE-UTIL-VERSION-058: leaves version and page alone while the sign-in runs, and acts again after it', async () => { + const { container } = installWorker(null) + container.getRegistration.mockResolvedValue(undefined) + const { reconcileAppVersion } = await loadModule() + localStorage.setItem('trek_app_version', '4.3.0') + // public/native-handoff.js marks the sign-in; a reload now could land on an + // older worker that a tab still open on the old version keeps alive. + localStorage.setItem('trek_native_signin', String(Date.now())) + + await reconcileAppVersion('4.3.1') + + expect(marker()).toBe('4.3.0') + expect(reload).not.toHaveBeenCalled() + expect(container.getRegistration).not.toHaveBeenCalled() + + // A mark older than any sign-in takes counts for nothing. + localStorage.setItem('trek_native_signin', String(Date.now() - 16 * 60 * 1000)) + await reconcileAppVersion('4.3.1') + expect(marker()).toBe('4.3.1') + expect(reload).toHaveBeenCalledTimes(1) + }) +}) + describe('reconcileAppVersion: the reload guard', () => { it('FE-UTIL-VERSION-030: a marker that cannot be written does not turn into a reload loop', async () => { const { reconcileAppVersion } = await loadModule() diff --git a/client/src/utils/versionHandover.ts b/client/src/utils/versionHandover.ts index 22e70eae0..96b709e2f 100644 --- a/client/src/utils/versionHandover.ts +++ b/client/src/utils/versionHandover.ts @@ -17,6 +17,7 @@ * version and session. */ +import { browserSignInRunning } from '../native/browserSignInFlag' import { reloadFresh } from './chunkReload' import { currentController, servingWorker } from './serviceWorkerShell' @@ -198,6 +199,9 @@ function waitForTakeover(reg: ServiceWorkerRegistration, version: string): Promi export async function reconcileAppVersion(reported: unknown): Promise { const version = asReleaseTag(reported) if (!version) return + // The app's sign-in runs in this browser: a reload now could land on an older + // version's worker that a tab still open keeps alive (native/browserSignInFlag). + if (browserSignInRunning()) return let storedVersion: string | null try { diff --git a/client/tailwind.config.js b/client/tailwind.config.js index 59c1e8aff..124599788 100644 --- a/client/tailwind.config.js +++ b/client/tailwind.config.js @@ -116,8 +116,25 @@ export default { subtitle: ['calc(18px * var(--fs-scale-subtitle, 1))', '1.35'], body: ['calc(14px * var(--fs-scale-body, 1))', '1.5'], caption: ['calc(12px * var(--fs-scale-caption, 1))', '1.4'], + // Buttons and segmented controls on the settings pages: between caption and body. + control: ['calc(13px * var(--fs-scale-body, 1))', '1.3'], }, }, }, - plugins: [], + plugins: [ + // The touch shell's size classes (src/hooks/sizeClass.ts) as the `wide:` and + // `split:` variants. They key on the class MobileShell writes to the shell's + // root (data-size), not on media queries of their own, so the CSS follows the + // hooks exactly: compact in a browser, and unmoved by Android's soft keyboard. + // Asked from , so a sheet portalled outside the shell follows too, and + // inside :where() so a variant weighs what a media query did. + ({ addVariant }) => { + addVariant('wide', ':where(html:has(.m-shell[data-size="wide"], .m-shell[data-size="split"])) &') + addVariant('split', ':where(html:has(.m-shell[data-size="split"])) &') + // A window as short as a phone on its side, where a form sheet takes the full + // height (MSheet's `form`). A media query on purpose: a soft keyboard that + // shrinks the window below it changes only CSS, so nothing remounts. + addVariant('short', '@media (max-height: 500px)') + }, + ], } diff --git a/client/tests/helpers/collectionCards.ts b/client/tests/helpers/collectionCards.ts index e3206616a..11d46c378 100644 --- a/client/tests/helpers/collectionCards.ts +++ b/client/tests/helpers/collectionCards.ts @@ -30,7 +30,7 @@ export function savedPlace(over: Partial = {}): CollectionC export function placesCard(over: Partial = {}): CollectionPlacesCard { return { kind: 'collectionPlaces', - list: { ...LIST, counts: { idea: 3, want: 5, visited: 4 } }, + list: { ...LIST, counts: { idea: 3, want: 5, visited: 4, revisit: 0 } }, places: [savedPlace()], more: 0, labels: [ diff --git a/client/tests/helpers/mobileAdmin.ts b/client/tests/helpers/mobileAdmin.ts index c0fd21e4d..00c2e821d 100644 --- a/client/tests/helpers/mobileAdmin.ts +++ b/client/tests/helpers/mobileAdmin.ts @@ -107,6 +107,8 @@ export function buildAdminHook(overrides: Record = {}): AdminHo setOidcLogin: vi.fn(), oidcRegistration: false, setOidcRegistration: vi.fn(), + oidcAutoRedirect: true, + setOidcAutoRedirect: vi.fn(), envOverrideOidcOnly: false, setEnvOverrideOidcOnly: vi.fn(), oidcConfigured: false, diff --git a/client/tests/helpers/mobileSelect.ts b/client/tests/helpers/mobileSelect.ts new file mode 100644 index 000000000..60faf9515 --- /dev/null +++ b/client/tests/helpers/mobileSelect.ts @@ -0,0 +1,22 @@ +import { screen, within } from '@testing-library/react'; +import type { UserEvent } from '@testing-library/user-event'; + +/** + * Picks an option of the phone's own select (MAdminSelect): taps the combobox + * named `name`, then the option labelled `option` in the picker sheet it opens. + */ +export async function pickMobileOption(user: UserEvent, name: string, option: string): Promise { + await user.click(screen.getByRole('combobox', { name })); + const sheet = await screen.findByRole('dialog', { name }); + await user.click(within(sheet).getByRole('button', { name: option })); +} + +/** The labels a phone select offers, read from its open picker sheet. */ +export async function mobileOptionLabels(user: UserEvent, name: string): Promise { + await user.click(screen.getByRole('combobox', { name })); + const sheet = await screen.findByRole('dialog', { name }); + return within(sheet) + .getAllByRole('button') + .filter((button) => button.getAttribute('aria-label') === null) + .map((button) => button.textContent ?? ''); +} diff --git a/client/tests/helpers/mobileTrip.ts b/client/tests/helpers/mobileTrip.ts index c19b91686..6b656578d 100644 --- a/client/tests/helpers/mobileTrip.ts +++ b/client/tests/helpers/mobileTrip.ts @@ -232,6 +232,14 @@ export function buildPlanner(overrides: Partial = {}): TripPlanner totalDistance: 0, totalDuration: 0, totalStops: 0, loading: false, }, + // Following an imported track, closed. The sheets mount the track sheet on every + // render, so its closed shape belongs in the base. + followTrack: { + dayId: null, open: vi.fn(), close: vi.fn(), tracks: [], busy: false, round: 0, error: null, + outcome: null, apply: vi.fn(async () => {}), clear: vi.fn(async () => {}), viaCount: 0, + current: null, namesByDay: {}, available: false, + }, + // The corridor search, idle. Both the search bar over the stage and the search // sheet read it on every render of the road trip tab, addon on or off, so the // empty-but-valid shape belongs here rather than in one suite's overrides. @@ -315,7 +323,7 @@ export function buildPlanner(overrides: Partial = {}): TripPlanner mapTileUrl: 'https://tile.example/{z}/{x}/{y}.png', fontStyle: {}, - splashDone: true, + slowOpen: false, }; const planner = { ...base, ...overrides } as unknown as TripPlanner; @@ -327,6 +335,7 @@ export function buildShell(overrides: Partial = {}): MTripShellAp view: 'plan', rtView: 'list', mapFront: false, + paneOpen: false, toggleRtView: vi.fn(), rtReach: 'ahead', setRtReach: vi.fn(), diff --git a/client/tests/helpers/msw/handlers/tags.ts b/client/tests/helpers/msw/handlers/tags.ts index c57238e0d..e51782329 100644 --- a/client/tests/helpers/msw/handlers/tags.ts +++ b/client/tests/helpers/msw/handlers/tags.ts @@ -5,6 +5,9 @@ import { createTagRequestSchema, tagListResponseSchema, tagSchema, + tripTagCreateRequestSchema, + tripTagListResponseSchema, + tripTagResponseSchema, } from '@trek/shared'; import { z } from 'zod'; import { buildCategory, buildTag } from '../../factories'; @@ -22,6 +25,16 @@ export const tagsHandlers = [ }) ), + // The tags a trip owns: none unless a test serves its own. + contractHandler('get', '/api/trips/:tripId/tags', { response: tripTagListResponseSchema }, () => ({ tags: [] })), + + contractHandler( + 'post', + '/api/trips/:tripId/tags', + { request: tripTagCreateRequestSchema, response: tripTagResponseSchema }, + ({ body, params }) => ({ tag: buildTag({ ...body, trip_id: Number(params.tripId) }) }) + ), + contractHandler('get', '/api/categories', { response: categoryListResponseSchema }, () => ({ categories: [buildCategory(), buildCategory()], })), diff --git a/client/tests/helpers/sizeClass.ts b/client/tests/helpers/sizeClass.ts new file mode 100644 index 000000000..ec2441f6c --- /dev/null +++ b/client/tests/helpers/sizeClass.ts @@ -0,0 +1,30 @@ +import { act } from '@testing-library/react'; +import { afterEach } from 'vitest'; +import { _pinSizeClass, _resetSizeClass } from '../../src/hooks/sizeClass'; + +/** + * The touch shell's size class in tests (src/hooks/sizeClass.ts). + * + * jsdom is a browser, where the class is always compact, so a test of the + * large-screen layout pins the class it wants instead of faking the app and a + * window size. Importing this helper also hands the class back to the window + * after each test of the file. + * + * Not imported by tests/setup.ts on purpose: sizeClass.ts reads native/platform, + * and a module a setup file imports is cached before a test file's vi.mock of it + * can take effect. + */ +export type TestSizeClass = 'compact' | 'wide' | 'split'; + +/** Switches the size class; the hooks follow as they would a rotation or a fold. */ +export function setSizeClass(next: TestSizeClass): void { + act(() => _pinSizeClass(next)); +} + +/** Back to what the window says (compact in jsdom). */ +export function resetSizeClass(): void { + _pinSizeClass(null); + _resetSizeClass(); +} + +afterEach(() => resetSizeClass()); diff --git a/client/tests/helpers/storeRegistry.ts b/client/tests/helpers/storeRegistry.ts index f740b6fa1..e66af459c 100644 --- a/client/tests/helpers/storeRegistry.ts +++ b/client/tests/helpers/storeRegistry.ts @@ -1,8 +1,12 @@ import type { StoreApi } from 'zustand'; +import { useDayPreviewStore } from '../../src/mobile/dayPreviewStore'; +import { useSharedImportStore } from '../../src/native/sharedFiles'; import { useAddonStore } from '../../src/store/addonStore'; import { useAssistantHintsStore } from '../../src/store/assistantHintsStore'; import { useAuthStore } from '../../src/store/authStore'; +import { useFlightLiveStore } from '../../src/store/flightLiveStore'; import { useInAppNotificationStore } from '../../src/store/inAppNotificationStore'; +import { useMailIngestStore } from '../../src/store/mailIngestStore'; import { usePaddleObstacleStore } from '../../src/store/paddleObstacleStore'; import { usePermissionsStore } from '../../src/store/permissionsStore'; import { useSettingsStore } from '../../src/store/settingsStore'; @@ -33,6 +37,8 @@ type ResettableStore = Pick, 'getState' | 'setState'>; export const RESET_STORES: Record = { useAuthStore, + useDayPreviewStore, + useSharedImportStore, useTripStore, useSettingsStore, useVacayStore, @@ -44,6 +50,10 @@ export const RESET_STORES: Record = { usePaddleObstacleStore, useTrackMarkToolStore, useAssistantHintsStore, + // Live flight states are per test: a leg seeded by one test must not show up in the next. + useFlightLiveStore, + // The mail inbox and its pending count, which the menus of every shell read. + useMailIngestStore, }; /** Not reset so far; moving one into RESET_STORES changes what every file that resets starts from. */ diff --git a/client/tests/integration/hooks/useResizablePanels.test.ts b/client/tests/integration/hooks/useResizablePanels.test.ts index 989afbfa4..9357349ad 100644 --- a/client/tests/integration/hooks/useResizablePanels.test.ts +++ b/client/tests/integration/hooks/useResizablePanels.test.ts @@ -50,6 +50,8 @@ describe('useResizablePanels', () => { }); it('FE-HOOK-PANELS-004: rightWidth loaded from localStorage when set', () => { + // Wide enough that the map's share leaves the stored width alone. + setViewport(1440, false); localStorage.setItem('sidebarRightWidth', '350'); const { result } = renderHook(() => useResizablePanels()); expect(result.current.rightWidth).toBe(350); @@ -78,7 +80,7 @@ describe('useResizablePanels', () => { result.current.startResizeLeft(); }); - // mousemove with clientX=350 → w = max(200, min(520, 350-10)) = 340 + // mousemove with clientX=350 → w = 350 - 10 = 340, well inside the room the window leaves act(() => { fireEvent.mouseMove(document, { clientX: 350 }); }); @@ -103,7 +105,7 @@ describe('useResizablePanels', () => { result.current.startResizeRight(); }); - // mousemove with clientX=800 → w = max(200, min(520, 1200-800-10)) = max(200, min(520, 390)) = 390 + // mousemove with clientX=800 → w = 1200 - 800 - 10 = 390 act(() => { fireEvent.mouseMove(document, { clientX: 800 }); }); @@ -125,7 +127,7 @@ describe('useResizablePanels', () => { result.current.startResizeLeft(); }); - // clientX=50 → w = max(200, min(520, 50-10)) = max(200, 40) = 200 + // clientX=50 → w = 40, held at the 200 minimum act(() => { fireEvent.mouseMove(document, { clientX: 50 }); }); @@ -133,19 +135,78 @@ describe('useResizablePanels', () => { expect(result.current.leftWidth).toBe(200); }); - it('FE-HOOK-PANELS-010: max width constraint (520) is enforced for left panel', () => { + it('FE-HOOK-PANELS-010: the left panel stops where the map would drop below 35% of the window next to the places list', () => { + setViewport(1200, false); const { result } = renderHook(() => useResizablePanels()); act(() => { result.current.startResizeLeft(); }); - // clientX=600 → w = max(200, min(520, 600-10)) = min(520, 590) = 520 + // 1200 - 420 map (35%) - 20 margins - 300 places list = 460 act(() => { - fireEvent.mouseMove(document, { clientX: 600 }); + fireEvent.mouseMove(document, { clientX: 1100 }); }); - expect(result.current.leftWidth).toBe(520); + expect(result.current.leftWidth).toBe(460); + expect(result.current.resizeMaxLeft).toBe(460); + }); + + it('FE-HOOK-PANELS-010b: a wide screen lets the day plan grow well past the old 520px ceiling', () => { + setViewport(1920, false); + const { result } = renderHook(() => useResizablePanels()); + + act(() => { + result.current.startResizeLeft(); + }); + act(() => { + fireEvent.mouseMove(document, { clientX: 910 }); + }); + + expect(result.current.leftWidth).toBe(900); + expect(localStorage.getItem('sidebarLeftWidth')).toBe('900'); + }); + + it('FE-HOOK-PANELS-010c: with the places list collapsed the day plan may take its room too', () => { + setViewport(1920, false); + const { result } = renderHook(() => useResizablePanels()); + + act(() => { result.current.toggleRight(); }); + act(() => { + result.current.nudgeLeft(10_000); + }); + + // 1920 - 672 map (35%) - 20 margins + expect(result.current.leftWidth).toBe(1228); + }); + + it('FE-HOOK-PANELS-010d: a window too small for both stored widths squeezes the places list, not the day plan', () => { + localStorage.setItem('sidebarLeftWidth', '700'); + localStorage.setItem('sidebarRightWidth', '600'); + setViewport(1600, false); + const { result } = renderHook(() => useResizablePanels()); + + // room 1600 - 560 map (35%) - 20 = 1020: the day plan keeps 700, the list gets 320 + expect(result.current.leftWidth).toBe(700); + expect(result.current.rightWidth).toBe(320); + expect(localStorage.getItem('sidebarRightWidth')).toBe('600'); + }); + + it('FE-HOOK-PANELS-010e: shrinking the window shrinks the ceiling with it', () => { + localStorage.setItem('sidebarLeftWidth', '900'); + setViewport(1920, false); + const { result } = renderHook(() => useResizablePanels()); + expect(result.current.leftWidth).toBe(900); + + act(() => { + Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1200 }); + window.dispatchEvent(new Event('resize')); + }); + + // room 1200 - 420 map (35%) - 20 = 760: the places list is held at its 200 minimum, the day plan gets 560 + expect(result.current.leftWidth).toBe(560); + expect(result.current.rightWidth).toBe(200); + expect(localStorage.getItem('sidebarLeftWidth')).toBe('900'); }); it('FE-HOOK-PANELS-011: mousemove without prior startResize does nothing', () => { @@ -201,7 +262,7 @@ describe('useResizablePanels', () => { act(() => { result.current.nudgeRight(10_000); }); - expect(result.current.rightWidth).toBe(result.current.resizeMax); + expect(result.current.rightWidth).toBe(result.current.resizeMaxRight); }); it('FE-HOOK-PANELS-012: body userSelect set to none during resize, cleared on mouseup', () => { @@ -220,6 +281,21 @@ describe('useResizablePanels', () => { expect(document.body.style.userSelect).toBe(''); }); + it('FE-HOOK-PANELS-012b: a drag reports itself, so the panel can drop its width animation while it follows the pointer', () => { + const { result } = renderHook(() => useResizablePanels()); + expect(result.current.resizing).toBe(false); + + act(() => { + result.current.startResizeRight(); + }); + expect(result.current.resizing).toBe(true); + + act(() => { + fireEvent.mouseUp(document); + }); + expect(result.current.resizing).toBe(false); + }); + it('FE-HOOK-PANELS-013: leftCollapsed and rightCollapsed default to false', () => { const { result } = renderHook(() => useResizablePanels()); expect(result.current.leftCollapsed).toBe(false); @@ -308,7 +384,7 @@ describe('useResizablePanels', () => { it('FE-HOOK-PANELS-022: a wide layout leaves the stored widths alone', () => { localStorage.setItem('sidebarLeftWidth', '520'); - setViewport(1100, false); + setViewport(1440, false); const { result } = renderHook(() => useResizablePanels()); expect(result.current.leftWidth).toBe(520); }); diff --git a/client/tests/unit/api/client.interceptor.test.ts b/client/tests/unit/api/client.interceptor.test.ts index a28e3d21c..666a82ef2 100644 --- a/client/tests/unit/api/client.interceptor.test.ts +++ b/client/tests/unit/api/client.interceptor.test.ts @@ -1,4 +1,4 @@ -// FE-CLIENT-INTERCEPTOR-001 to FE-CLIENT-INTERCEPTOR-012 +// FE-CLIENT-INTERCEPTOR-001 to FE-CLIENT-INTERCEPTOR-015 import { describe, it, expect } from 'vitest' import { isAuthPublicPath } from '../../../src/api/client' @@ -19,6 +19,10 @@ describe('FE-CLIENT-INTERCEPTOR: 401 AUTH_REQUIRED redirect allowlist', () => { it('FE-CLIENT-INTERCEPTOR-004: /reset-password', () => { expect(isAuthPublicPath('/reset-password')).toBe(true) }) + + it('FE-CLIENT-INTERCEPTOR-015: /native-handoff, which signs in by itself', () => { + expect(isAuthPublicPath('/native-handoff')).toBe(true) + }) }) describe('prefix-match public paths — no redirect', () => { diff --git a/client/tests/unit/db/offlineDb.upgrade.test.ts b/client/tests/unit/db/offlineDb.upgrade.test.ts index b569ed482..f46b1b4a9 100644 --- a/client/tests/unit/db/offlineDb.upgrade.test.ts +++ b/client/tests/unit/db/offlineDb.upgrade.test.ts @@ -57,6 +57,7 @@ const HISTORY: Record = { 12: { tourStationVisits: '[assignment_id+station_key], trip_id, assignment_id' }, 13: { tourDrafts: 'tripId' }, 14: { routeCache: 'key, savedAt' }, + 15: { tripTags: 'tripId' }, }; const HISTORY_VERSIONS = Object.keys(HISTORY) @@ -138,6 +139,7 @@ function rowsAt(version: number): Record> { tourStationVisits: { assignment_id: 71, station_key: 'stop-01', status: 'visited', trip_id: 1 }, tourDrafts: { tripId: 1, draft: { payload: '{"version":11}', updated_at: '2026-10-22 09:00:00' } }, routeCache: { key: 'driving:km:11.5,48.1;11.6,48.2', route: { coordinates: [], legs: [] }, savedAt: 13 }, + tripTags: { tripId: 1, tags: [{ id: 91, trip_id: 1, name: 'Viewpoint', color: '#10b981' }] }, }; const tables = schemaAt(version); return Object.fromEntries(Object.entries(all).filter(([table]) => table in tables)); @@ -364,6 +366,28 @@ const UPGRADE_CASES: Record = { ]); }, }, + 15: { + intent: 'adds the tags a trip owns, one list per trip, and keeps the road routes kept on the device', + check: async (db) => { + expect((await db.routeCache.get('driving:km:11.5,48.1;11.6,48.2'))?.savedAt).toBe(13); + await db.table('tripTags').bulkPut([ + { tripId: 1, tags: [{ id: 91, name: 'Viewpoint' }] }, + { tripId: 2, tags: [] }, + ]); + // One row per trip: the list read again replaces the one kept before. + await db.table('tripTags').put({ + tripId: 1, + tags: [ + { id: 91, name: 'Lookout' }, + { id: 92, name: 'Zone' }, + ], + }); + expect(await db.tripTags.count()).toBe(2); + expect((await db.tripTags.get(1))?.tags.map((tag) => tag.name)).toEqual(['Lookout', 'Zone']); + // The user's personal tags stay in their own table, as they were. + expect(await db.tags.count()).toBe(1); + }, + }, }; describe('offlineDb upgrades', () => { diff --git a/client/tests/unit/mobile/MBottomNav.test.tsx b/client/tests/unit/mobile/MBottomNav.test.tsx index c2cd945e6..cfcc2dee3 100644 --- a/client/tests/unit/mobile/MBottomNav.test.tsx +++ b/client/tests/unit/mobile/MBottomNav.test.tsx @@ -259,4 +259,25 @@ describe('MBottomNav', () => { }); expect([placeholder.left.children.length, placeholder.right.children.length]).toEqual(groups); }); + + it("FE-MOB-NAV-020: More is marked for its screens with a ring, not the centre button's fill", () => { + seedAddons(['vacay', 'atlas', 'journey', 'collections']); + nav('/atlas'); + const more = screen.getByRole('button', { name: 'More' }); + expect(more).toHaveAttribute('aria-current', 'page'); + expect(more.className).toContain('ring-[color:var(--m-act)]'); + expect(more.className).not.toContain('bg-m-act'); + }); + + it('FE-MOB-NAV-021: a list fades out under the dock, a map runs to the edge', () => { + seedAddons(['atlas', 'journey']); + const dashboard = nav('/dashboard'); + expect(dashboard.container.querySelector('.m-dock-scrim')).toBeInTheDocument(); + dashboard.unmount(); + for (const path of ['/atlas', '/journey/3']) { + const screenOverMap = nav(path); + expect([path, screenOverMap.container.querySelector('.m-dock-scrim')]).toEqual([path, null]); + screenOverMap.unmount(); + } + }); }); diff --git a/client/tests/unit/mobile/MHintLabel.test.tsx b/client/tests/unit/mobile/MHintLabel.test.tsx new file mode 100644 index 000000000..978413151 --- /dev/null +++ b/client/tests/unit/mobile/MHintLabel.test.tsx @@ -0,0 +1,37 @@ +// FE-MOB-HINT-001 to FE-MOB-HINT-004 +import userEvent from '@testing-library/user-event'; +import { describe, expect, it } from 'vitest'; +import MHintLabel from '../../../src/mobile/components/MHintLabel'; +import { render, screen } from '../../helpers/render'; + +describe('MHintLabel', () => { + it('FE-MOB-HINT-001: without a hint it is the label alone, with no mark', () => { + render(); + expect(screen.getByText('Password Login')).toBeInTheDocument(); + expect(screen.queryByTestId('m-hint-mark')).not.toBeInTheDocument(); + }); + + it('FE-MOB-HINT-002: the hint stays in the page for a screen reader while the mark is closed', () => { + render(); + const hint = screen.getByText('Allow sign in with email and password'); + expect(hint).toHaveClass('sr-only'); + expect(screen.getByTestId('m-hint-mark')).toHaveAttribute('aria-hidden', 'true'); + }); + + it('FE-MOB-HINT-003: a tap on the mark shows the hint and a second one folds it again', async () => { + const user = userEvent.setup(); + render(); + const mark = screen.getByTestId('m-hint-mark'); + + await user.click(mark); + expect(screen.getByText('Allow sign in with email and password')).not.toHaveClass('sr-only'); + + await user.click(mark); + expect(screen.getByText('Allow sign in with email and password')).toHaveClass('sr-only'); + }); + + it('FE-MOB-HINT-004: the label takes the class it is given', () => { + render(); + expect(screen.getByText('Files')).toHaveClass('uppercase'); + }); +}); diff --git a/client/tests/unit/mobile/MNavRail.test.tsx b/client/tests/unit/mobile/MNavRail.test.tsx new file mode 100644 index 000000000..eb8bc6001 --- /dev/null +++ b/client/tests/unit/mobile/MNavRail.test.tsx @@ -0,0 +1,275 @@ +import { FolderOpen, Map as MapIcon, PenLine } from 'lucide-react'; +import { useLocation } from 'react-router'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import MNavRail from '../../../src/mobile/components/MNavRail'; +import { useScreenRailAction } from '../../../src/mobile/components/railAction'; +import MobileShell from '../../../src/mobile/MobileShell'; +import MTripRail from '../../../src/mobile/screens/trip/MTripRail'; +import { useAddonStore } from '../../../src/store/addonStore'; +import { useAuthStore } from '../../../src/store/authStore'; +import { usePluginStore } from '../../../src/store/pluginStore'; +import { buildUser } from '../../helpers/factories'; +import { act, fireEvent, render, screen, within } from '../../helpers/render'; +import { setSizeClass } from '../../helpers/sizeClass'; + +// FE-MOB-RAIL-001 onwards + +function LocationEcho() { + const location = useLocation(); + return {location.pathname + location.search}; +} + +function seedAddons(ids: string[]) { + useAddonStore.setState({ + addons: ids.map((id) => ({ id, name: id, type: 'global', icon: 'globe', enabled: true })), + loaded: true, + }); +} + +const rail = () => screen.getByRole('navigation', { name: 'Navigation' }); + +describe('MNavRail', () => { + beforeEach(() => { + useAddonStore.setState({ addons: [], loaded: true }); + usePluginStore.setState({ plugins: [], loaded: true }); + useAuthStore.setState({ user: buildUser({ role: 'user' }) }); + }); + + it('FE-MOB-RAIL-001: holds every destination at once, the ones the dock keeps under More included', () => { + seedAddons(['vacay', 'journey', 'atlas', 'collections']); + render(, { initialEntries: ['/dashboard'] }); + + for (const name of ['My Trips', 'Vacay', 'Journey', 'Atlas', 'Collections', 'Settings']) { + expect(within(rail()).getByRole('button', { name })).toBeInTheDocument(); + } + expect(within(rail()).queryByRole('button', { name: 'More' })).not.toBeInTheDocument(); + expect(within(rail()).queryByRole('button', { name: 'Admin Settings' })).not.toBeInTheDocument(); + }); + + it('FE-MOB-RAIL-002: marks the current section and navigates on a tap', () => { + seedAddons(['atlas']); + render( + <> + + + , + { initialEntries: ['/atlas'] } + ); + + expect(within(rail()).getByRole('button', { name: 'Atlas' })).toHaveAttribute('aria-current', 'page'); + fireEvent.click(within(rail()).getByRole('button', { name: 'My Trips' })); + expect(screen.getByTestId('loc').textContent).toBe('/dashboard'); + fireEvent.click(within(rail()).getByRole('button', { name: 'Settings' })); + expect(screen.getByTestId('loc').textContent).toBe('/settings'); + }); + + it('FE-MOB-RAIL-003: administration sits at the foot for an admin, under its short name', () => { + useAuthStore.setState({ user: buildUser({ role: 'admin' }) }); + render(, { initialEntries: ['/dashboard'] }); + // The rail names it "Admin" (nav.admin): the avatar menu's "Admin Settings" + // ran to two lines in English and was cut in German. + expect(within(rail()).getByRole('button', { name: 'Admin' })).toBeInTheDocument(); + }); + + it('FE-MOB-RAIL-012: settings and administration, and their sub pages, mark their own entry in the rail', () => { + useAuthStore.setState({ user: buildUser({ role: 'admin' }) }); + const { unmount } = render(, { initialEntries: ['/settings'] }); + expect(within(rail()).getByRole('button', { name: 'Settings' })).toHaveAttribute('aria-current', 'page'); + expect(within(rail()).getByRole('button', { name: 'Admin' })).not.toHaveAttribute('aria-current'); + unmount(); + + render(, { initialEntries: ['/admin/users'] }); + expect(within(rail()).getByRole('button', { name: 'Admin' })).toHaveAttribute('aria-current', 'page'); + expect(within(rail()).getByRole('button', { name: 'Settings' })).not.toHaveAttribute('aria-current'); + expect(within(rail()).getByRole('button', { name: 'My Trips' })).not.toHaveAttribute('aria-current'); + }); + + it('FE-MOB-RAIL-013: on a window too short for every entry the list fades at the edge that has more behind it', () => { + useAuthStore.setState({ user: buildUser({ role: 'admin' }) }); + render(, { initialEntries: ['/dashboard'] }); + const list = rail().querySelector('.overflow-y-auto') as HTMLElement; + expect(list.className).not.toMatch(/m-fade-/); + Object.defineProperty(list, 'scrollHeight', { configurable: true, value: 800 }); + Object.defineProperty(list, 'clientHeight', { configurable: true, value: 400 }); + act(() => { + list.dispatchEvent(new Event('scroll')); + }); + expect(list).toHaveClass('m-fade-b'); + list.scrollTop = 400; + act(() => { + list.dispatchEvent(new Event('scroll')); + }); + expect(list).toHaveClass('m-fade-t'); + }); + + it("FE-MOB-RAIL-004: the create button keeps the dock's meaning and its exceptions", () => { + const { unmount } = render( + <> + + + , + { initialEntries: ['/dashboard'] } + ); + const create = within(rail()).getAllByRole('button')[0]; + fireEvent.click(create); + expect(screen.getByTestId('loc').textContent).toContain('create'); + unmount(); + + render(, { initialEntries: ['/settings'] }); + expect(within(rail()).getAllByRole('button')[0]).toHaveAccessibleName('My Trips'); + }); + + it('FE-MOB-RAIL-009: the head is the same 56px circle on every top-level page, so no entry moves', () => { + const head = () => rail().firstElementChild?.firstElementChild as HTMLElement; + for (const path of ['/dashboard', '/atlas', '/settings', '/admin', '/vacay']) { + const { unmount } = render(, { initialEntries: [path] }); + expect([path, head().className]).toEqual([path, expect.stringContaining('h-14 w-14')]); + unmount(); + } + }); + + it("FE-MOB-RAIL-010: on the vacation calendar the head is the screen's own switch", () => { + const toggle = vi.fn(); + function Vacay({ editing }: { editing: boolean }) { + useScreenRailAction({ label: editing ? 'Year' : 'Edit calendar', icon: PenLine, pressed: editing, run: toggle }); + return null; + } + const { rerender } = render( + <> + + + , + { initialEntries: ['/vacay'] } + ); + const first = within(rail()).getAllByRole('button')[0]; + expect(first).toHaveAccessibleName('Edit calendar'); + fireEvent.click(first); + expect(toggle).toHaveBeenCalledOnce(); + + rerender( + <> + + + + ); + expect(within(rail()).getAllByRole('button')[0]).toHaveAccessibleName('Year'); + expect(within(rail()).getAllByRole('button')[0].className).toContain('border-2'); + }); +}); + +describe('MTripRail', () => { + const tabs = [ + { id: 'plan', label: 'Plan' }, + { id: 'transports', label: 'Transport' }, + { id: 'dateien', label: 'Files', icon: FolderOpen }, + { id: 'plugin:x', label: 'Plugin', icon: MapIcon }, + ]; + + it('FE-MOB-RAIL-005: every section is in the rail with its name, More keeps the actions', () => { + const onSelect = vi.fn(); + const onMore = vi.fn(); + render( + tabs.find((x) => x.id === id)?.label ?? id} + /> + ); + const nav = screen.getByRole('navigation', { name: 'Trip sections' }); + expect( + within(nav) + .getAllByRole('button') + .map((b) => b.getAttribute('title')) + ).toEqual(['Plan', 'Transport', 'Files', 'Plugin', 'More']); + expect(within(nav).getByRole('button', { name: 'Transport' })).toHaveAttribute('aria-current', 'page'); + + fireEvent.click(within(nav).getByRole('button', { name: 'Files' })); + expect(onSelect).toHaveBeenCalledWith('dateien'); + fireEvent.click(within(nav).getByRole('button', { name: 'More' })); + expect(onMore).toHaveBeenCalledOnce(); + }); + + it('FE-MOB-RAIL-014: More wears a ring while its sheet is open, and says it is expanded', () => { + const props = { + tabs, + active: 'plan', + onSelect: vi.fn(), + onMore: vi.fn(), + labelOf: (id: string) => tabs.find((x) => x.id === id)?.label ?? id, + }; + const { rerender } = render(); + const more = () => screen.getByRole('button', { name: 'More' }); + expect(more()).toHaveAttribute('aria-expanded', 'false'); + expect(more().firstElementChild?.className).not.toContain('ring-'); + rerender(); + expect(more()).toHaveAttribute('aria-expanded', 'true'); + expect(more().firstElementChild?.className).toContain('ring-[color:var(--m-act)]'); + expect(more()).not.toHaveAttribute('aria-current'); + }); +}); + +describe('MobileShell on a wide window', () => { + beforeEach(() => { + useAddonStore.setState({ addons: [], loaded: true }); + usePluginStore.setState({ plugins: [], loaded: true }); + }); + + it("FE-MOB-RAIL-006: the rail takes the dock's place and the page column starts after it", () => { + setSizeClass('wide'); + const { container } = render( + +

    page body

    + , + { initialEntries: ['/dashboard'] } + ); + + expect(rail()).toBeInTheDocument(); + expect(container.querySelector('.m-dock-vt')?.tagName).toBe('NAV'); + expect(container.querySelector('.m-shell')).toBeInTheDocument(); + expect(screen.getByText('page body').parentElement?.className).toContain('wide:ps-[var(--m-rail-w)]'); + }); + + it('FE-MOB-RAIL-007: folding back to compact brings the dock back, the page stays mounted', () => { + setSizeClass('wide'); + render( + + + , + { initialEntries: ['/dashboard'] } + ); + const field = screen.getByLabelText('note') as HTMLInputElement; + fireEvent.change(field, { target: { value: 'typed before the fold' } }); + + setSizeClass('compact'); + expect(screen.queryByRole('navigation', { name: 'Navigation' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'My Trips' })).toBeInTheDocument(); + expect((screen.getByLabelText('note') as HTMLInputElement).value).toBe('typed before the fold'); + expect(screen.getByLabelText('note')).toBe(field); + }); + + it('FE-MOB-RAIL-011: the rail comes before the page, so a keyboard reaches the navigation first', () => { + setSizeClass('wide'); + const { container } = render( + + + , + { initialEntries: ['/dashboard'] } + ); + const page = screen.getByRole('button', { name: 'in the page' }); + expect(rail().compareDocumentPosition(page) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(container.querySelector('.m-shell')?.getAttribute('data-size')).toBe('wide'); + }); + + it('FE-MOB-RAIL-008: no rail inside a trip, which brings its own', () => { + setSizeClass('wide'); + render( + +

    page body

    +
    , + { initialEntries: ['/trips/7'] } + ); + expect(screen.queryByRole('navigation', { name: 'Navigation' })).not.toBeInTheDocument(); + }); +}); diff --git a/client/tests/unit/mobile/MSheet.test.tsx b/client/tests/unit/mobile/MSheet.test.tsx index 66b777b8e..2eece0357 100644 --- a/client/tests/unit/mobile/MSheet.test.tsx +++ b/client/tests/unit/mobile/MSheet.test.tsx @@ -2,6 +2,7 @@ import React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, fireEvent, act } from '@testing-library/react'; import MSheet from '../../../src/mobile/components/MSheet'; +import { closeTopOverlay } from '../../../src/mobile/overlayStack'; // FE-MOB-SHEET-001 onwards @@ -42,7 +43,7 @@ describe('MSheet', () => { expect(onClose).not.toHaveBeenCalled(); const dialog = screen.getByRole('dialog'); - const backdrop = dialog.parentElement!.parentElement!; + const backdrop = dialog.closest('[role="presentation"]') as HTMLElement; fireEvent.click(backdrop); expect(onClose).toHaveBeenCalledTimes(1); }); @@ -293,6 +294,149 @@ describe('MSheet', () => { expect(baseCalls).toEqual([]); }); + it('FE-MOB-SHEET-030: a way back (edge swipe, Android back) closes the open sheet first', () => { + const onClose = vi.fn(); + const { rerender } = render( + + Sheet content + , + ); + expect(closeTopOverlay()).toBe(true); + expect(onClose).toHaveBeenCalledTimes(1); + rerender( + + Sheet content + , + ); + expect(closeTopOverlay()).toBe(false); + }); + + describe('dragging the docked sheet', () => { + const touch = (y: number, x = 100) => ({ touches: [{ clientX: x, clientY: y }], changedTouches: [{ clientX: x, clientY: y }] }); + + function renderBottom(onClose = vi.fn(), content: React.ReactNode =
    Sheet content
    ) { + HTMLElement.prototype.setPointerCapture = vi.fn(); + render( + + {content} + , + ); + const dialog = screen.getByRole('dialog'); + Object.defineProperty(dialog, 'offsetHeight', { configurable: true, value: 400 }); + return { dialog, onClose }; + } + + it('FE-MOB-SHEET-022: a pull down on the content carries the sheet and throws it off past a third', () => { + const { dialog, onClose } = renderBottom(); + const content = screen.getByText('Sheet content'); + + fireEvent.touchStart(content, touch(100)); + fireEvent.touchMove(content, touch(140)); + fireEvent.touchMove(content, touch(300)); + expect(dialog.style.transform).toBe('translateY(160px)'); + + fireEvent.touchEnd(content, touch(300)); + expect(onClose).toHaveBeenCalledTimes(1); + // Thrown from where the finger let go, not replayed from the rest position. + expect(dialog.style.transform).toMatch(/translateY\(\d+px\)/); + expect(dialog.className).not.toContain('m-sheet-down'); + }); + + it('FE-MOB-SHEET-023: content scrolled down keeps its own scroll, and a sideways pan is let go', () => { + const { dialog, onClose } = renderBottom(vi.fn(), ( +
    + row +
    + )); + const list = screen.getByTestId('list'); + Object.defineProperty(list, 'scrollHeight', { configurable: true, value: 900 }); + Object.defineProperty(list, 'clientHeight', { configurable: true, value: 300 }); + Object.defineProperty(list, 'scrollTop', { configurable: true, writable: true, value: 120 }); + + fireEvent.touchStart(screen.getByText('row'), touch(100)); + fireEvent.touchMove(screen.getByText('row'), touch(200)); + fireEvent.touchEnd(screen.getByText('row'), touch(200)); + + list.scrollTop = 0; + fireEvent.touchStart(list, touch(100, 100)); + fireEvent.touchMove(list, touch(110, 160)); + fireEvent.touchEnd(list, touch(110, 160)); + + expect(dialog.style.transform).toBe(''); + expect(onClose).not.toHaveBeenCalled(); + }); + + it('FE-MOB-SHEET-024: pulling up past the rest position only stretches a little', () => { + const { dialog } = renderBottom(); + const strip = dialog.querySelector('.cursor-grab') as HTMLElement; + + fireEvent.pointerDown(strip, { pointerId: 1, clientY: 300 }); + fireEvent.pointerMove(strip, { pointerId: 1, clientY: 0 }); + + expect(dialog.style.transform).toBe('translateY(-20px)'); + }); + + it('FE-MOB-SHEET-025: with unsaved changes a flick springs back and asks', () => { + HTMLElement.prototype.setPointerCapture = vi.fn(); + const onClose = vi.fn(); + function Form() { + const [name, setName] = React.useState(''); + return ( + + setName(e.target.value)} /> + + ); + } + render(
    ); + const input = screen.getByRole('textbox', { name: 'Name' }); + fireEvent.pointerDown(input); + fireEvent.change(input, { target: { value: 'Porto' } }); + const dialog = screen.getByRole('dialog', { name: 'Form' }); + const strip = dialog.querySelector('.cursor-grab') as HTMLElement; + + fireEvent.pointerDown(strip, { pointerId: 1, clientY: 100 }); + fireEvent.pointerMove(strip, { pointerId: 1, clientY: 160 }); + fireEvent.pointerUp(strip, { pointerId: 1, clientY: 160 }); + + expect(onClose).not.toHaveBeenCalled(); + expect(screen.getByRole('alertdialog')).toBeInTheDocument(); + expect(dialog.style.transform).toBe('translateY(0px)'); + }); + + it('FE-MOB-SHEET-027: a mouse pull that starts on a button carries the sheet and does not press it', () => { + const pressed = vi.fn(); + const { dialog, onClose } = renderBottom(vi.fn(), ); + const button = screen.getByRole('button', { name: 'Go' }); + + fireEvent.pointerDown(button, { pointerType: 'mouse', button: 0, clientX: 100, clientY: 100 }); + fireEvent.pointerMove(window, { pointerType: 'mouse', clientX: 100, clientY: 140 }); + fireEvent.pointerMove(window, { pointerType: 'mouse', clientX: 100, clientY: 300 }); + expect(dialog.style.transform).toBe('translateY(160px)'); + fireEvent.pointerUp(window, { pointerType: 'mouse', clientX: 100, clientY: 300 }); + fireEvent.click(button); + + expect(onClose).toHaveBeenCalledTimes(1); + expect(pressed).not.toHaveBeenCalled(); + }); + + it('FE-MOB-SHEET-028: a plain click on a button in the sheet still presses it', () => { + const pressed = vi.fn(); + renderBottom(vi.fn(), ); + const button = screen.getByRole('button', { name: 'Go' }); + + fireEvent.pointerDown(button, { pointerType: 'mouse', button: 0, clientX: 100, clientY: 100 }); + fireEvent.pointerUp(window, { pointerType: 'mouse', clientX: 100, clientY: 101 }); + fireEvent.click(button); + + expect(pressed).toHaveBeenCalledTimes(1); + }); + + it('FE-MOB-SHEET-026: the docked sheet rises from below, the card pops in place', () => { + const { dialog } = renderBottom(); + expect(dialog.className).toContain('m-sheet-up'); + }); + }); + describe('the unsaved-changes question', () => { function Form({ open, onClose }: { open: boolean; onClose: () => void }) { const [name, setName] = React.useState(''); @@ -302,7 +446,7 @@ describe('MSheet', () => { ); } - const backdrop = () => screen.getByRole('dialog', { name: 'Form' }).parentElement!.parentElement!; + const backdrop = () => screen.getByRole('dialog', { name: 'Form' }).closest('[role="presentation"]') as HTMLElement; it('FE-MOB-SHEET-020: a tap on the scrim asks before throwing a change away, and keep editing stays', () => { const onClose = vi.fn(); @@ -338,5 +482,99 @@ describe('MSheet', () => { expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(); }); }); -}); + describe('presentation', () => { + const panel = (name = 'Sheet') => screen.getByRole('dialog', { name }); + const region = (name = 'Sheet') => panel(name).parentElement!.parentElement as HTMLElement; + it('FE-MOB-SHEET-031: every sheet stands on the one opaque surface, whatever material it names', () => { + for (const material of ['glass', 'bar-glass', 'opaque'] as const) { + const { unmount } = render( + {}} material={material} ariaLabel="Sheet"> + body + , + ); + expect(panel().className).toContain('bg-[color:var(--m-sheetop)]'); + expect(panel().className).not.toContain('backdrop-blur'); + expect(panel().className).not.toContain('var(--m-sheet)'); + expect(panel().className).not.toContain('var(--m-glass)'); + unmount(); + } + }); + + it('FE-MOB-SHEET-032: on a phone the card stands between the status bar and the dock, never across the dock', () => { + render( + {}} ariaLabel="Sheet"> + body + , + ); + expect(region().className).toContain('top-[var(--m-safe-top,12px)]'); + expect(region().className).toContain('bottom-[calc(var(--bottom-nav-h,84px)+12px)]'); + expect(panel().className).toContain('max-h-full'); + }); + + it('FE-MOB-SHEET-033: a form fills the height of a short window and lays its actions beside the title', () => { + const { unmount } = render( + {}} form ariaLabel="Sheet"> + body + , + ); + expect(panel().className).toContain('m-form-sheet'); + expect(panel().className).toContain('short:flex-1'); + expect(region().className).toContain('short:bottom-0'); + unmount(); + + render( + {}} ariaLabel="Sheet"> + body + , + ); + expect(panel().className).not.toContain('m-form-sheet'); + expect(region().className).not.toContain('short:bottom-0'); + }); + + it('FE-MOB-SHEET-034: a transparent scrim still dims a short window, where the sheet takes most of the height', () => { + render( + {}} variant="bottom" dimTransparent ariaLabel="Sheet"> + body + , + ); + const root = panel().closest('[role="presentation"]') as HTMLElement; + const scrim = root.querySelector('[data-m-scrim]') as HTMLElement; + expect(scrim.className).toContain('bg-transparent'); + expect(scrim.className).toContain('short:bg-[color:var(--m-dim)]'); + }); + + it('FE-MOB-SHEET-036: the dim fades beside the sheet, never around it, so the opaque sheet is never see-through', () => { + const { rerender } = render( + {}} ariaLabel="Sheet"> + body + , + ); + const root = panel().closest('[role="presentation"]') as HTMLElement; + const scrim = root.querySelector('[data-m-scrim]') as HTMLElement; + expect(scrim.className).toContain('m-fade-in'); + expect(scrim.className).toContain('pointer-events-none'); + expect(scrim.contains(panel())).toBe(false); + // No ancestor of the sheet animates its opacity. + for (let el: HTMLElement | null = panel().parentElement; el; el = el.parentElement) { + expect(el.className || '').not.toMatch(/\bm-fade-(in|out)\b/); + } + rerender( + {}} ariaLabel="Sheet"> + body + , + ); + expect(scrim.className).toContain('m-fade-out'); + }); + + it('FE-MOB-SHEET-035: the region lets taps through to the scrim, the sheet itself takes them', () => { + render( + {}} ariaLabel="Sheet"> + body + , + ); + expect(region().className).toContain('pointer-events-none'); + expect(panel().parentElement!.className).toContain('pointer-events-auto'); + }); + }); +}); diff --git a/client/tests/unit/mobile/MobileShell.test.tsx b/client/tests/unit/mobile/MobileShell.test.tsx index a996752b6..ba9ac3462 100644 --- a/client/tests/unit/mobile/MobileShell.test.tsx +++ b/client/tests/unit/mobile/MobileShell.test.tsx @@ -7,7 +7,11 @@ import { usePluginStore } from '../../../src/store/pluginStore'; // FE-MOB-MSHELL-001 onwards +const fold = vi.hoisted(() => ({ current: null as null | { start: number; end: number } })); +vi.mock('../../../src/native/windowFold', () => ({ useWindowFold: () => fold.current })); + beforeEach(() => { + fold.current = null; useAddonStore.setState({ addons: [], loaded: true }); usePluginStore.setState({ plugins: [], loaded: true }); }); @@ -117,4 +121,20 @@ describe('MobileShell', () => { expect(content.className).toContain('overflow-y-auto'); expect(content.className).toContain('md:overflow-visible'); }); + + it('FE-MOB-MSHELL-008: a fold the Android app reports is where the panes meet', () => { + const { container, rerender } = render( +

    page body

    , + { initialEntries: ['/dashboard'] }, + ); + const root = () => container.querySelector('.m-root') as HTMLElement; + expect(root().dataset.fold).toBeUndefined(); + expect(root().style.getPropertyValue('--m-fold-start')).toBe(''); + + fold.current = { start: 420, end: 421 }; + rerender(

    page body

    ); + expect(root().dataset.fold).toBe('vertical'); + expect(root().style.getPropertyValue('--m-fold-start')).toBe('420px'); + expect(root().style.getPropertyValue('--m-fold-end')).toBe('421px'); + }); }); diff --git a/client/tests/unit/mobile/admin/MAdmin.managed.test.tsx b/client/tests/unit/mobile/admin/MAdmin.managed.test.tsx new file mode 100644 index 000000000..79a4fa542 --- /dev/null +++ b/client/tests/unit/mobile/admin/MAdmin.managed.test.tsx @@ -0,0 +1,83 @@ +import { http, HttpResponse } from 'msw'; +import { Route, Routes } from 'react-router'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import MAdmin from '../../../../src/mobile/screens/admin/MAdmin'; +import { useAuthStore } from '../../../../src/store/authStore'; +import { buildAdmin } from '../../../helpers/factories'; +import { server } from '../../../helpers/msw/server'; +import { fireEvent, render, screen, waitFor } from '../../../helpers/render'; +import { resetAllStores, seedStore } from '../../../helpers/store'; + +// An install that fills the admin-tab attachment point (managed/index.tsx): one tab +// with a phone layout of its own, one without. +vi.mock('../../../../src/managed', async () => { + // vi.mock is hoisted above the imports, so the factory brings its own. + const { createElement } = await import('react'); + const { CreditCard, LifeBuoy } = await import('lucide-react'); + return { + managedRoutes: [], + managedNavItems: [], + visibleManagedNavItems: () => [], + managedAdminTabs: [ + { + id: 'subscription', + label: 'Subscription', + Icon: CreditCard, + group: 'maintenance', + element: createElement('div', { 'data-testid': 'desktop-subscription' }), + mobileElement: createElement('div', { 'data-testid': 'phone-subscription' }), + }, + { + id: 'support', + label: 'Help and support', + Icon: LifeBuoy, + group: 'maintenance', + element: createElement('div', { 'data-testid': 'desktop-support' }), + }, + ], + }; +}); + +function renderAdmin() { + return render( + + } /> + , + { initialEntries: ['/admin'] } + ); +} + +beforeEach(() => { + resetAllStores(); + seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() }); + server.use( + http.get('/api/admin/collab-features', () => + HttpResponse.json({ chat: true, notes: true, polls: true, whatsnext: true }) + ), + http.get('/api/admin/places-photos', () => HttpResponse.json({ enabled: false })), + http.get('/api/admin/places-autocomplete', () => HttpResponse.json({ enabled: false })), + http.get('/api/admin/places-details', () => HttpResponse.json({ enabled: false })), + http.get('/api/admin/invites/trips', () => HttpResponse.json({ trips: [] })) + ); +}); + +afterEach(() => { + server.resetHandlers(); +}); + +describe('MAdmin with an install’s own tabs', () => { + it('FE-MOB-ADMIN-MANAGED-001: lists them in the section picker and shows their phone layout', async () => { + renderAdmin(); + fireEvent.click(screen.getByRole('button', { name: 'Administration' })); + fireEvent.click(screen.getByRole('button', { name: 'Subscription' })); + await waitFor(() => expect(screen.getByTestId('phone-subscription')).toBeInTheDocument()); + expect(screen.queryByTestId('desktop-subscription')).not.toBeInTheDocument(); + }); + + it('FE-MOB-ADMIN-MANAGED-002: a tab without a phone layout shows its desktop element', async () => { + renderAdmin(); + fireEvent.click(screen.getByRole('button', { name: 'Administration' })); + fireEvent.click(screen.getByRole('button', { name: 'Help and support' })); + await waitFor(() => expect(screen.getByTestId('desktop-support')).toBeInTheDocument()); + }); +}); diff --git a/client/tests/unit/mobile/admin/MAdmin.test.tsx b/client/tests/unit/mobile/admin/MAdmin.test.tsx index 05596fea4..aa6db949f 100644 --- a/client/tests/unit/mobile/admin/MAdmin.test.tsx +++ b/client/tests/unit/mobile/admin/MAdmin.test.tsx @@ -2,7 +2,8 @@ import React from 'react'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { Route, Routes } from 'react-router'; import { http, HttpResponse } from 'msw'; -import { fireEvent, render, screen, waitFor } from '../../../helpers/render'; +import { fireEvent, render, screen, waitFor, within } from '../../../helpers/render'; +import { setSizeClass } from '../../../helpers/sizeClass'; import { server } from '../../../helpers/msw/server'; import { resetAllStores, seedStore } from '../../../helpers/store'; import { buildAdmin } from '../../../helpers/factories'; @@ -136,7 +137,7 @@ describe('MAdmin', () => { expect(screen.getByText('8')).toBeInTheDocument(); }); - it('FE-MOB-ADMIN-002: the section dropdown switches to the settings section', async () => { + it('FE-MOB-ADMIN-002: the section dropdown switches to the security section', async () => { render(); await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument()); @@ -144,17 +145,29 @@ describe('MAdmin', () => { fireEvent.click(screen.getByRole('button', { name: 'Administration' })); // All standard sections are listed - expect(screen.getByRole('button', { name: 'User Defaults' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Defaults' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Backup' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Audit' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Services' })).toBeInTheDocument(); + // Under the desktop sidebar's group headings + expect(screen.getByText('Configuration')).toBeInTheDocument(); + expect(screen.getByText('Maintenance')).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Settings' })); + fireEvent.click(screen.getByRole('button', { name: 'Security' })); - // Settings section renders the auth methods card, user list is gone + // Security renders the auth methods card, user list is gone await waitFor(() => expect(screen.getByText('Authentication Methods')).toBeInTheDocument()); expect(screen.queryByText('alice')).not.toBeInTheDocument(); }); + it('FE-MOB-ADMIN-002b: a link to a desktop tab opens the same section, an old Settings link Security', async () => { + for (const [tab, card] of [['security', 'Authentication Methods'], ['settings', 'Authentication Methods'], ['services', 'API Keys']]) { + const { unmount } = render(, { initialEntries: [`/admin?tab=${tab}`] }); + await waitFor(() => expect(screen.getByText(card)).toBeInTheDocument()); + unmount(); + } + }); + it('FE-MOB-ADMIN-003: the back button leaves for the dashboard', async () => { renderAdmin(); await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument()); @@ -179,7 +192,7 @@ describe('MAdmin', () => { fireEvent.click(screen.getByRole('button', { name: 'Administration' })); - expect(screen.queryByRole('button', { name: 'MCP Access' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'MCP' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: 'Dev: Notifications' })).not.toBeInTheDocument(); }); @@ -192,7 +205,7 @@ describe('MAdmin', () => { renderAdmin(); await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument()); - await openSection('MCP Access'); + await openSection('MCP'); expect(screen.getByTestId('mcp-tokens-panel')).toBeInTheDocument(); }); @@ -211,7 +224,7 @@ describe('MAdmin', () => { renderAdmin(); await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument()); - await openSection('User Defaults'); + await openSection('Defaults'); expect(screen.getByTestId('default-user-settings')).toBeInTheDocument(); await openSection('Personalization'); @@ -429,4 +442,22 @@ describe('MAdmin', () => { fireEvent.click(await screen.findByRole('button', { name: 'Administration' })); expect(screen.queryByRole('button', { name: 'Storage' })).not.toBeInTheDocument(); }); + + it('FE-MOB-ADMIN-019: with room for two panes the sections stand in a list beside the page', async () => { + setSizeClass('split'); + render(); + await waitFor(() => expect(screen.getByText('alice')).toBeInTheDocument()); + + const sections = screen.getByRole('navigation', { name: 'Administration' }); + expect(within(sections).getByRole('button', { name: 'Users' })).toHaveAttribute('aria-current', 'page'); + // No dropdown pill on top of the page: the list beside it is the switcher. + expect(screen.queryByRole('button', { name: 'Administration', expanded: false })).not.toBeInTheDocument(); + + fireEvent.click(within(sections).getByRole('button', { name: 'Security' })); + await waitFor(() => expect(screen.getByText('Authentication Methods')).toBeInTheDocument()); + expect(within(sections).getByRole('button', { name: 'Security' })).toHaveAttribute('aria-current', 'page'); + + fireEvent.click(within(sections).getByRole('button', { name: 'Create User' })); + expect(screen.getByRole('dialog', { name: 'Create User' })).toBeInTheDocument(); + }); }); diff --git a/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx b/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx index 6a0b85bf1..376830158 100644 --- a/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx @@ -63,7 +63,7 @@ afterEach(() => { }); describe('MAdminAddonManager', () => { - it('FE-MOB-AADD-001: shows the spinner while addons load', async () => { + it('FE-MOB-AADD-001: shows the placeholders while addons load', async () => { server.use( http.get('/api/admin/addons', async () => { await delay(60); @@ -72,9 +72,9 @@ describe('MAdminAddonManager', () => { ); render(); - expect(document.querySelector('.animate-spin')).toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).toBeInTheDocument(); await screen.findByText('No addons available'); - expect(document.querySelector('.animate-spin')).not.toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).not.toBeInTheDocument(); }); it('FE-MOB-AADD-002: the header uses the light wordmark in light mode', async () => { @@ -106,7 +106,7 @@ describe('MAdminAddonManager', () => { expect(await screen.findByText('No addons available')).toBeInTheDocument(); }); - it('FE-MOB-AADD-005: trip addons render with the section band, catalog label and type badge', async () => { + it('FE-MOB-AADD-005: trip addons render under the section band with their catalog label, no type badge of their own', async () => { server.use(addonsRoute([buildAddon({ id: 'packing', name: 'Packing', enabled: true })])); render(); @@ -114,7 +114,8 @@ describe('MAdminAddonManager', () => { // The band names the type and says what it means on a line of its own, no dash between them. expect(screen.getByText('Available as a tab within each trip')).toBeInTheDocument(); expect(screen.getByText('Packing lists and to-do tasks for your trips')).toBeInTheDocument(); - expect(screen.getAllByText('Trip')).toHaveLength(2); + // Only the band names the type: every row under it is of that type. + expect(screen.getAllByText('Trip')).toHaveLength(1); expect(screen.getByRole('switch', { name: 'Lists' })).toHaveAttribute('aria-checked', 'true'); }); @@ -275,8 +276,8 @@ describe('MAdminAddonManager', () => { expect(screen.getByRole('switch', { name: 'Immich' })).toHaveAttribute('aria-checked', 'true'); // Journey + three providers, and providers are not shown as top-level rows. expect(screen.getAllByRole('switch')).toHaveLength(4); - // The band and the addon's type badge both say Global. - expect(screen.getAllByText('Global')).toHaveLength(2); + // Only the band says Global. + expect(screen.getAllByText('Global')).toHaveLength(1); }); it('FE-MOB-AADD-015: toggling a provider persists it and rolls back on failure', async () => { @@ -413,8 +414,8 @@ describe('MAdminAddonManager', () => { expect(screen.getByRole('switch', { name: 'Nextcloud' })).toHaveAttribute('aria-checked', 'true'); // Documents plus two providers, and neither provider carries a type badge of its own. expect(screen.getAllByRole('switch')).toHaveLength(3); - // The band and the addon's type badge. - expect(screen.getAllByText('Trip')).toHaveLength(2); + // The band alone names the type. + expect(screen.getAllByText('Trip')).toHaveLength(1); }); it('FE-MOB-AADD-029: the shelf stays hidden while Documents is off', async () => { diff --git a/client/tests/unit/mobile/admin/MAdminBackupPanel.test.tsx b/client/tests/unit/mobile/admin/MAdminBackupPanel.test.tsx index d5451e1e0..b0112132b 100644 --- a/client/tests/unit/mobile/admin/MAdminBackupPanel.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminBackupPanel.test.tsx @@ -9,6 +9,7 @@ import { buildSettings } from '../../../helpers/factories'; import { useSettingsStore } from '../../../../src/store/settingsStore'; import { ToastContainer } from '../../../../src/components/shared/Toast'; import MAdminBackupPanel from '../../../../src/mobile/screens/admin/MAdminBackupPanel'; +import { mobileOptionLabels, pickMobileOption } from '../../../helpers/mobileSelect'; const manualBackup = { filename: 'backup-2025-01-15.zip', created_at: '2025-01-15T10:00:00Z', size: 2_048_000 }; const autoBackup = { filename: 'auto-backup-2025-02-01.zip', created_at: '2025-02-01T02:00:00Z', size: 512_000 }; @@ -349,14 +350,16 @@ describe('MAdminBackupPanel', () => { }); it('FE-MOB-MBKP-021: the hour picker renders 24h labels and names the server timezone', async () => { + const user = userEvent.setup(); server.use(autoSettingsHandler({ ...DEFAULT_AUTO, enabled: true }, 'Europe/Berlin')); render(); expect(await screen.findByText('Run at hour')).toBeInTheDocument(); expect(screen.getByText('Server local time (24h format), timezone Europe/Berlin')).toBeInTheDocument(); - expect(screen.getByRole('combobox')).toHaveValue('2'); - expect(screen.getByRole('option', { name: '00:00' })).toBeInTheDocument(); - expect(screen.getByRole('option', { name: '23:00' })).toBeInTheDocument(); + expect(screen.getByRole('combobox', { name: 'Run at hour' })).toHaveTextContent('02:00'); + const labels = await mobileOptionLabels(user, 'Run at hour'); + expect(labels).toContain('00:00'); + expect(labels).toContain('23:00'); }); it('FE-MOB-MBKP-022: with a 12h user preference the hours are labelled AM/PM', async () => { @@ -365,9 +368,10 @@ describe('MAdminBackupPanel', () => { render(); expect(await screen.findByText('Server local time (12h format)')).toBeInTheDocument(); - expect(screen.getByRole('option', { name: '12:00 AM' })).toBeInTheDocument(); - expect(screen.getByRole('option', { name: '11:00 AM' })).toBeInTheDocument(); - expect(screen.getByRole('option', { name: '1:00 PM' })).toBeInTheDocument(); + const labels = await mobileOptionLabels(userEvent.setup(), 'Run at hour'); + expect(labels).toContain('12:00 AM'); + expect(labels).toContain('11:00 AM'); + expect(labels).toContain('1:00 PM'); }); it('FE-MOB-MBKP-023: hourly hides the hour picker, weekly shows weekdays, monthly a day select', async () => { @@ -388,12 +392,10 @@ describe('MAdminBackupPanel', () => { expect(screen.queryByText('Day of week')).not.toBeInTheDocument(); expect(screen.getByText('Day of month')).toBeInTheDocument(); // Hour picker plus the 1–28 day picker - const selects = screen.getAllByRole('combobox'); - expect(selects).toHaveLength(2); - expect(within(selects[1]).getAllByRole('option')).toHaveLength(28); - - fireEvent.change(selects[1], { target: { value: '15' } }); - expect(selects[1]).toHaveValue('15'); + expect(screen.getAllByRole('combobox')).toHaveLength(2); + expect(await mobileOptionLabels(user, 'Day of month')).toHaveLength(28); + await user.click(within(screen.getByRole('dialog', { name: 'Day of month' })).getByRole('button', { name: '15' })); + expect(screen.getByRole('combobox', { name: 'Day of month' })).toHaveTextContent('15'); }); it('FE-MOB-MBKP-024: saving sends the edited schedule and confirms with a toast', async () => { @@ -412,7 +414,7 @@ describe('MAdminBackupPanel', () => { await user.click(screen.getByText('Weekly')); await user.click(screen.getByText('Fri')); await user.click(screen.getByText('30 days')); - fireEvent.change(screen.getByRole('combobox'), { target: { value: '5' } }); + await pickMobileOption(user, 'Run at hour', '05:00'); await user.click(screen.getByRole('button', { name: 'Save' })); expect(await screen.findByText('Auto-backup settings saved')).toBeInTheDocument(); diff --git a/client/tests/unit/mobile/admin/MAdminCategoryManager.test.tsx b/client/tests/unit/mobile/admin/MAdminCategoryManager.test.tsx index adcd43e89..9dc35dc56 100644 --- a/client/tests/unit/mobile/admin/MAdminCategoryManager.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminCategoryManager.test.tsx @@ -29,12 +29,12 @@ describe('MAdminCategoryManager', () => { server.use(http.get('/api/categories', () => HttpResponse.json({ categories: [] }))); }); - it('FE-MOB-MCAT-001: shows a spinner while the list is loading, then the empty state', async () => { + it('FE-MOB-MCAT-001: shows placeholders while the list is loading, then the empty state', async () => { render(); - expect(document.querySelector('.animate-spin')).toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).toBeInTheDocument(); expect(await screen.findByText('No categories yet')).toBeInTheDocument(); - expect(document.querySelector('.animate-spin')).not.toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).not.toBeInTheDocument(); }); it('FE-MOB-MCAT-002: renders the card head and the New Category action', async () => { diff --git a/client/tests/unit/mobile/admin/MAdminDefaultUserSettings.test.tsx b/client/tests/unit/mobile/admin/MAdminDefaultUserSettings.test.tsx index d68787931..47e995be5 100644 --- a/client/tests/unit/mobile/admin/MAdminDefaultUserSettings.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminDefaultUserSettings.test.tsx @@ -50,7 +50,7 @@ function resetLink(label: string): HTMLElement { /** The CARTO key input sits under its label inside the field's own wrapper. */ function cartoInput(): HTMLInputElement { - return within(screen.getByText('Shared CARTO key').parentElement as HTMLElement).getByRole('textbox'); + return within(screen.getByText('Shared CARTO key').closest('[data-m-field]') as HTMLElement).getByRole('textbox'); } describe('MAdminDefaultUserSettings', () => { diff --git a/client/tests/unit/mobile/admin/MAdminGitHubPanel.test.tsx b/client/tests/unit/mobile/admin/MAdminGitHubPanel.test.tsx index 39c44c492..11a37a0d9 100644 --- a/client/tests/unit/mobile/admin/MAdminGitHubPanel.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminGitHubPanel.test.tsx @@ -50,7 +50,7 @@ afterEach(() => { async function renderPanel(props: { isPrerelease?: boolean } = {}) { const view = render(); - await waitFor(() => expect(document.querySelector('.animate-spin')).not.toBeInTheDocument()); + await waitFor(() => expect(document.querySelector('[data-skeleton]')).not.toBeInTheDocument()); return view; } @@ -73,7 +73,7 @@ describe('MAdminGitHubPanel', () => { expect(screen.getAllByText('Helps me keep building TREK')).toHaveLength(2); }); - it('FE-MOB-AGH-002: shows a spinner while the releases request is in flight', () => { + it('FE-MOB-AGH-002: shows placeholders while the releases request is in flight', () => { server.use( http.get('/api/admin/github-releases', async () => { await new Promise(() => {}); @@ -82,7 +82,7 @@ describe('MAdminGitHubPanel', () => { ); render(); - expect(document.querySelector('.animate-spin')).toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).toBeInTheDocument(); expect(screen.queryByText('Release History')).not.toBeInTheDocument(); }); diff --git a/client/tests/unit/mobile/admin/MAdminMcpTokensPanel.test.tsx b/client/tests/unit/mobile/admin/MAdminMcpTokensPanel.test.tsx index f089e5edd..9943581da 100644 --- a/client/tests/unit/mobile/admin/MAdminMcpTokensPanel.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminMcpTokensPanel.test.tsx @@ -80,7 +80,7 @@ describe('MAdminMcpTokensPanel', () => { await screen.findByText('No MCP tokens have been created yet'); }); - it('FE-MOB-MCPTOK-002: shows spinners while both requests are in flight', async () => { + it('FE-MOB-MCPTOK-002: shows placeholders while both requests are in flight', async () => { server.use( http.get('/api/admin/mcp-tokens', async () => { await new Promise(() => {}); @@ -93,7 +93,7 @@ describe('MAdminMcpTokensPanel', () => { ); renderPanel(); - expect(document.querySelectorAll('.animate-spin')).toHaveLength(2); + expect(document.querySelectorAll('[data-skeleton]')).toHaveLength(2); expect(screen.queryByText('No MCP tokens have been created yet')).not.toBeInTheDocument(); }); diff --git a/client/tests/unit/mobile/admin/MAdminNotificationDefaults.test.tsx b/client/tests/unit/mobile/admin/MAdminNotificationDefaults.test.tsx new file mode 100644 index 000000000..7ef13e3a7 --- /dev/null +++ b/client/tests/unit/mobile/admin/MAdminNotificationDefaults.test.tsx @@ -0,0 +1,57 @@ +// FE-MOB-ANOTIFDEF-001 to FE-MOB-ANOTIFDEF-003 +import { http, HttpResponse } from 'msw'; +import { describe, expect, it } from 'vitest'; +import MAdminNotificationDefaults from '../../../../src/mobile/screens/admin/MAdminNotificationDefaults'; +import { server } from '../../../helpers/msw/server'; +import { fireEvent, render, waitFor } from '../../../helpers/render'; + +const matrix = (defaults: Record>) => ({ + defaults, + channels: [ + { id: 'inapp', labelKey: 'settings.notificationPreferences.inapp', active: true, configured: true }, + { id: 'email', labelKey: 'settings.notificationPreferences.email', active: true, configured: true }, + ], + event_types: ['trip_invite', 'booking_change'], + implemented_combos: { trip_invite: ['inapp', 'email'], booking_change: ['inapp'] }, +}); + +const cells = () => Array.from(document.querySelectorAll('button[data-state]')) as HTMLElement[]; + +describe('MAdminNotificationDefaults (#1536)', () => { + it('FE-MOB-ANOTIFDEF-001: one pill per channel an event is sent on, each in its state', async () => { + server.use( + http.get('/api/admin/notification-preferences/defaults', () => + HttpResponse.json(matrix({ trip_invite: { inapp: 'on', email: 'blocked' }, booking_change: { inapp: 'off' } })) + ) + ); + render(); + await waitFor(() => expect(cells()).toHaveLength(3)); + expect(cells().map((b) => b.getAttribute('data-state'))).toEqual(['on', 'blocked', 'off']); + }); + + it('FE-MOB-ANOTIFDEF-002: a tap cycles the cell to its next state and saves it', async () => { + const sent: unknown[] = []; + server.use( + http.get('/api/admin/notification-preferences/defaults', () => + HttpResponse.json(matrix({ trip_invite: { inapp: 'on', email: 'on' }, booking_change: { inapp: 'on' } })) + ), + http.put('/api/admin/notification-preferences/defaults', async ({ request }) => { + sent.push(await request.json()); + return HttpResponse.json( + matrix({ trip_invite: { inapp: 'on', email: 'off' }, booking_change: { inapp: 'on' } }) + ); + }) + ); + render(); + await waitFor(() => expect(cells()).toHaveLength(3)); + fireEvent.click(cells()[1]); + await waitFor(() => expect(sent).toHaveLength(1)); + await waitFor(() => expect(cells()[1].getAttribute('data-state')).toBe('off')); + }); + + it('FE-MOB-ANOTIFDEF-003: nothing is drawn until the defaults are loaded', () => { + server.use(http.get('/api/admin/notification-preferences/defaults', () => new Promise(() => {}))); + render(); + expect(cells()).toHaveLength(0); + }); +}); diff --git a/client/tests/unit/mobile/admin/MAdminNotificationsSection.test.tsx b/client/tests/unit/mobile/admin/MAdminNotificationsSection.test.tsx index da79a125c..6b696a886 100644 --- a/client/tests/unit/mobile/admin/MAdminNotificationsSection.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminNotificationsSection.test.tsx @@ -10,6 +10,9 @@ import { useTranslation } from '../../../../src/i18n'; import type { useAdmin } from '../../../../src/pages/admin/useAdmin'; import MAdminNotificationsSection from '../../../../src/mobile/screens/admin/MAdminNotificationsSection'; +// The defaults grid loads its own data and has its own suite (MAdminNotificationDefaults.test.tsx). +vi.mock('../../../../src/mobile/screens/admin/MAdminNotificationDefaults', () => ({ default: () =>
    })); + // The per-event matrix loads its own data and has its own spec — stub it so the // assertions here only see the section's own cards. vi.mock('../../../../src/mobile/screens/admin/MAdminNotifyMatrix', () => ({ diff --git a/client/tests/unit/mobile/admin/MAdminPackingTemplateManager.test.tsx b/client/tests/unit/mobile/admin/MAdminPackingTemplateManager.test.tsx index 0c7e40022..7e15fd17d 100644 --- a/client/tests/unit/mobile/admin/MAdminPackingTemplateManager.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminPackingTemplateManager.test.tsx @@ -51,7 +51,7 @@ beforeEach(() => { }); describe('MAdminPackingTemplateManager', () => { - it('FE-MOB-APKG-001: shows the spinner while templates load, then the empty state', async () => { + it('FE-MOB-APKG-001: shows the placeholders while templates load, then the empty state', async () => { server.use( http.get('/api/admin/packing-templates', async () => { await new Promise(r => setTimeout(r, 60)); @@ -60,12 +60,12 @@ describe('MAdminPackingTemplateManager', () => { ); renderManager(); - expect(document.querySelector('.animate-spin')).toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).toBeInTheDocument(); expect(screen.getByText('Packing Templates')).toBeInTheDocument(); expect(screen.getByText('Create reusable packing lists for your trips')).toBeInTheDocument(); await screen.findByText('No templates created yet'); - expect(document.querySelector('.animate-spin')).not.toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).not.toBeInTheDocument(); }); it('FE-MOB-APKG-002: renders each template with its category and item counts', async () => { diff --git a/client/tests/unit/mobile/admin/MAdminPermissionsPanel.test.tsx b/client/tests/unit/mobile/admin/MAdminPermissionsPanel.test.tsx index 0a1e2dc2b..e26e756a0 100644 --- a/client/tests/unit/mobile/admin/MAdminPermissionsPanel.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminPermissionsPanel.test.tsx @@ -9,6 +9,7 @@ import { resetAllStores } from '../../../helpers/store'; import { usePermissionsStore } from '../../../../src/store/permissionsStore'; import { ToastContainer } from '../../../../src/components/shared/Toast'; import MAdminPermissionsPanel from '../../../../src/mobile/screens/admin/MAdminPermissionsPanel'; +import { mobileOptionLabels, pickMobileOption } from '../../../helpers/mobileSelect'; const ALLOWED = ['admin', 'trip_owner', 'trip_member', 'everybody']; @@ -47,7 +48,7 @@ afterEach(() => { }); describe('MAdminPermissionsPanel', () => { - it('FE-MOB-APERM-001: renders only the spinner while loading', () => { + it('FE-MOB-APERM-001: renders only the placeholders while loading', () => { server.use( http.get('/api/admin/permissions', async () => { await new Promise(() => {}); @@ -56,7 +57,7 @@ describe('MAdminPermissionsPanel', () => { ); renderPanel(); - expect(document.querySelector('.animate-spin')).toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).toBeInTheDocument(); expect(screen.queryByText('Permission Settings')).not.toBeInTheDocument(); }); @@ -76,12 +77,12 @@ describe('MAdminPermissionsPanel', () => { }); it('FE-MOB-APERM-003: a select reflects the stored level and offers every allowed level', async () => { + const user = userEvent.setup(); renderPanel(); await screen.findByText('Permission Settings'); - const select = screen.getByRole('combobox', { name: 'Create trips' }) as HTMLSelectElement; - expect(select.value).toBe('trip_member'); - expect(Array.from(select.options).map((o) => o.textContent)).toEqual([ + expect(screen.getByRole('combobox', { name: 'Create trips' })).toHaveTextContent('Trip members'); + expect(await mobileOptionLabels(user, 'Create trips')).toEqual([ 'Admin only', 'Trip owner', 'Trip members', 'Everyone', ]); }); @@ -125,7 +126,7 @@ describe('MAdminPermissionsPanel', () => { const save = screen.getByRole('button', { name: /Save/ }); expect(save).toBeDisabled(); - await user.selectOptions(screen.getByRole('combobox', { name: 'Create trips' }), 'admin'); + await pickMobileOption(user, 'Create trips', 'Admin only'); expect(save).not.toBeDisabled(); expect(screen.getAllByText('customized')).toHaveLength(1); @@ -151,8 +152,8 @@ describe('MAdminPermissionsPanel', () => { await user.click(screen.getByRole('button', { name: 'Reset to defaults' })); await waitFor(() => expect(screen.queryByText('customized')).not.toBeInTheDocument()); - expect((screen.getByRole('combobox', { name: 'Create trips' }) as HTMLSelectElement).value).toBe('trip_member'); - expect((screen.getByRole('combobox', { name: 'Edit trip details' }) as HTMLSelectElement).value).toBe('trip_owner'); + expect(screen.getByRole('combobox', { name: 'Create trips' })).toHaveTextContent('Trip members'); + expect(screen.getByRole('combobox', { name: 'Edit trip details' })).toHaveTextContent('Trip owner'); expect(screen.getByRole('button', { name: /Save/ })).not.toBeDisabled(); }); @@ -168,7 +169,7 @@ describe('MAdminPermissionsPanel', () => { renderPanel(); await screen.findByText('Permission Settings'); - await user.selectOptions(screen.getByRole('combobox', { name: 'Create trips' }), 'admin'); + await pickMobileOption(user, 'Create trips', 'Admin only'); await user.click(screen.getByRole('button', { name: /Save/ })); await screen.findByText('Permission settings saved'); @@ -184,7 +185,7 @@ describe('MAdminPermissionsPanel', () => { renderPanel(); await screen.findByText('Permission Settings'); - await user.selectOptions(screen.getByRole('combobox', { name: 'Create trips' }), 'admin'); + await pickMobileOption(user, 'Create trips', 'Admin only'); await user.click(screen.getByRole('button', { name: /Save/ })); await screen.findByText('Permission settings saved'); @@ -199,7 +200,7 @@ describe('MAdminPermissionsPanel', () => { renderPanel(); await screen.findByText('Permission Settings'); - await user.selectOptions(screen.getByRole('combobox', { name: 'Create trips' }), 'admin'); + await pickMobileOption(user, 'Create trips', 'Admin only'); const save = screen.getByRole('button', { name: /Save/ }); await user.click(save); diff --git a/client/tests/unit/mobile/admin/MAdminPluginsPanel.test.tsx b/client/tests/unit/mobile/admin/MAdminPluginsPanel.test.tsx index dfd56d45d..49cb829ae 100644 --- a/client/tests/unit/mobile/admin/MAdminPluginsPanel.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminPluginsPanel.test.tsx @@ -1695,13 +1695,14 @@ describe('MAdminPluginsPanel — instance settings', () => { await openRowSheet(plugin({ instanceSettingsCount: 3 })); fireEvent.click(screen.getByText('Instance settings')); - const select = await screen.findByRole('combobox', {}, { timeout: 5000 }); - expect(select).toHaveValue('slow'); + const select = await screen.findByRole('combobox', { name: 'Mode' }, { timeout: 5000 }); + expect(select).toHaveTextContent('Slow'); expect(screen.getByRole('switch', { name: 'enabled' })).toBeInTheDocument(); // label falls back to the key expect(screen.getByRole('spinbutton')).toHaveValue(null); expect(screen.getByText('Pick one')).toBeInTheDocument(); // hint - fireEvent.change(select, { target: { value: 'fast' } }); + fireEvent.click(select); + fireEvent.click(within(await screen.findByRole('dialog', { name: 'Mode' })).getByRole('button', { name: 'Fast' })); fireEvent.click(screen.getByRole('switch', { name: 'enabled' })); fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '3' } }); fireEvent.click(screen.getByRole('button', { name: /^save$/i })); diff --git a/client/tests/unit/mobile/admin/MAdminServices.test.tsx b/client/tests/unit/mobile/admin/MAdminServices.test.tsx new file mode 100644 index 000000000..b706e6b54 --- /dev/null +++ b/client/tests/unit/mobile/admin/MAdminServices.test.tsx @@ -0,0 +1,174 @@ +// FE-MOB-ASVC-001 to FE-MOB-ASVC-009 +import userEvent from '@testing-library/user-event'; +import type { PlaceContribDecisionRequest, PlaceContribState, ServiceIdentityStatus } from '@trek/shared'; +import { http, HttpResponse } from 'msw'; +import { describe, expect, it, vi } from 'vitest'; +import MAdminGoogleDailyLimit from '../../../../src/mobile/screens/admin/MAdminGoogleDailyLimit'; +import MAdminPlaceContrib from '../../../../src/mobile/screens/admin/MAdminPlaceContrib'; +import MAdminServiceQuota from '../../../../src/mobile/screens/admin/MAdminServiceQuota'; +import { server } from '../../../helpers/msw/server'; +import { render, screen, waitFor, within } from '../../../helpers/render'; + +// The keys themselves, so a test fails on a missing or renamed key rather than on wording. +vi.mock('../../../../src/i18n', async (importOriginal) => ({ + ...(await importOriginal()), + useTranslation: () => ({ t: (key: string) => key, locale: 'en-US' }), +})); + +const QUOTA = { limit: 10_000, used: 2_500, remaining: 7_500, resetAt: '2026-10-30T00:00:00.000Z' }; +const CONNECTED: ServiceIdentityStatus = { + state: 'connected', + tier: 'std', + keySource: 'registered', + services: [ + { service: 'places', inUse: true, quota: QUOTA }, + { service: 'photon', inUse: false, quota: null }, + ], + lastSeenAt: '2026-10-29T12:00:00.000Z', +} as ServiceIdentityStatus; + +const ON = { website: true, phone: true, email: true, opening_hours: true, description: true, image: true }; +const AGREED: PlaceContribState = { + termsVersion: 1, + ceiling: 'admin', + eligible: true, + ineligibleReason: null, + consent: { + enabled: true, + fields: ON, + termsVersion: 1, + decision: 'agreed', + decidedBy: 1, + decidedAt: '2026-10-30T10:00:00Z', + }, + showPrompt: false, + snoozedUntil: null, + active: true, + counts: { accepted: 42, duplicate: 0, rejected: 0, withheld: 0, retracted: 0 }, + lastSuccessDay: '2026-10-29', + queue: { size: 7, cap: 5000, full: false }, + pauseReason: null, + registrationOpen: false, +}; + +function serveContrib(state: PlaceContribState) { + const decisions: PlaceContribDecisionRequest[] = []; + server.use( + http.get('/api/admin/places-contribute', () => HttpResponse.json(state)), + http.put('/api/admin/places-contribute/decision', async ({ request }) => { + decisions.push((await request.json()) as PlaceContribDecisionRequest); + return HttpResponse.json(state); + }), + http.get('/api/admin/places-contribute/log', () => + HttpResponse.json({ entries: [], total: 0, page: 1, perPage: 20 }) + ) + ); + return decisions; +} + +describe('MAdminServiceQuota', () => { + it('FE-MOB-ASVC-001: shows the state, the day used against the limit and an unused service', async () => { + server.use(http.get('/api/admin/service-identity', () => HttpResponse.json(CONNECTED))); + render(); + expect(await screen.findByText('admin.trekApi.quota.state.connected')).toBeInTheDocument(); + expect(screen.getByRole('progressbar', { name: 'admin.trekApi.quota.service.places' })).toHaveAttribute( + 'aria-valuenow', + '2500' + ); + expect(screen.getByText('admin.trekApi.quota.notInUse')).toBeInTheDocument(); + }); + + it('FE-MOB-ASVC-002: a new key is asked for through a confirm sheet', async () => { + const user = userEvent.setup(); + let regenerated = false; + server.use( + http.get('/api/admin/service-identity', () => HttpResponse.json(CONNECTED)), + http.post('/api/admin/service-identity/regenerate', () => { + regenerated = true; + return HttpResponse.json(CONNECTED); + }) + ); + render(); + await user.click(await screen.findByRole('button', { name: /admin.trekApi.quota.regenerate/ })); + const sheet = await screen.findByRole('dialog', { name: 'admin.trekApi.quota.regenerateTitle' }); + await user.click(within(sheet).getByRole('button', { name: 'admin.trekApi.quota.regenerate' })); + await waitFor(() => expect(regenerated).toBe(true)); + }); + + it('FE-MOB-ASVC-003: a managed install offers no new key', async () => { + server.use(http.get('/api/admin/service-identity', () => HttpResponse.json(CONNECTED))); + render(); + await screen.findByText('admin.trekApi.quota.state.connected'); + expect(screen.queryByRole('button', { name: /admin.trekApi.quota.regenerate/ })).not.toBeInTheDocument(); + }); +}); + +describe('MAdminGoogleDailyLimit', () => { + it('FE-MOB-ASVC-004: shows today against the cap and saves a new cap', async () => { + const user = userEvent.setup(); + let body: unknown = null; + server.use( + http.get('/api/admin/google-quota', () => + HttpResponse.json({ daily_limit: 500, used_today: 3, exhausted: false }) + ), + http.put('/api/admin/google-quota', async ({ request }) => { + body = await request.json(); + return HttpResponse.json({ daily_limit: 800, used_today: 3, exhausted: false }); + }) + ); + render(); + expect(await screen.findByText('admin.googleQuota.usedOfLimit')).toBeInTheDocument(); + const field = screen.getByRole('textbox', { name: 'admin.googleQuota.title' }); + await user.clear(field); + await user.type(field, '800'); + await user.click(screen.getByRole('button', { name: /common.save/ })); + await waitFor(() => expect(body).not.toBeNull()); + }); + + it('FE-MOB-ASVC-005: a used-up day reads as reached', async () => { + server.use( + http.get('/api/admin/google-quota', () => HttpResponse.json({ daily_limit: 10, used_today: 10, exhausted: true })) + ); + render(); + expect(await screen.findByText('admin.googleQuota.reached')).toBeInTheDocument(); + }); +}); + +describe('MAdminPlaceContrib', () => { + it('FE-MOB-ASVC-006: on, it shows the figures and one switch per field', async () => { + serveContrib(AGREED); + render(); + expect(await screen.findByRole('switch', { name: 'admin.contribute.title' })).toHaveAttribute( + 'aria-checked', + 'true' + ); + expect(screen.getByText(/admin.contribute.figure.accepted 42/)).toBeInTheDocument(); + expect(screen.getByRole('switch', { name: 'admin.contribute.field.website' })).toBeInTheDocument(); + }); + + it('FE-MOB-ASVC-007: switching a field off sends the remaining fields', async () => { + const user = userEvent.setup(); + const decisions = serveContrib(AGREED); + render(); + await user.click(await screen.findByRole('switch', { name: 'admin.contribute.field.phone' })); + await waitFor(() => expect(decisions).toHaveLength(1)); + expect(decisions[0]).toMatchObject({ action: 'fields', fields: { ...ON, phone: false } }); + }); + + it('FE-MOB-ASVC-008: switching it off asks first, then sends off', async () => { + const user = userEvent.setup(); + const decisions = serveContrib(AGREED); + render(); + await user.click(await screen.findByRole('switch', { name: 'admin.contribute.title' })); + const sheet = await screen.findByRole('dialog', { name: 'admin.contribute.offTitle' }); + await user.click(within(sheet).getByRole('button', { name: 'admin.contribute.offConfirm' })); + await waitFor(() => expect(decisions).toEqual([{ action: 'off' }])); + }); + + it('FE-MOB-ASVC-009: standing alone, a switch the environment turned off hides the panel', async () => { + serveContrib({ ...AGREED, eligible: false, ineligibleReason: 'env_off' }); + render(); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(screen.queryByRole('switch')).not.toBeInTheDocument(); + }); +}); diff --git a/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx b/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx index f67393b45..f17c3f660 100644 --- a/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx @@ -10,9 +10,33 @@ import { buildAdminHook, type AdminHook } from '../../../helpers/mobileAdmin'; import { useTranslation } from '../../../../src/i18n'; import MAdminSettingsSection from '../../../../src/mobile/screens/admin/MAdminSettingsSection'; +// The services section's own panels load their data and have their own suite +// (MAdminServices.test.tsx); here only where they sit matters. +vi.mock('../../../../src/mobile/screens/admin/MAdminServiceQuota', () => ({ default: () =>
    })); +vi.mock('../../../../src/mobile/screens/admin/MAdminPlaceContrib', () => ({ default: () =>
    })); +vi.mock('../../../../src/mobile/screens/admin/MAdminGoogleDailyLimit', () => ({ default: () =>
    })); + +const PARTS = ['security', 'services', 'features'] as const; + +/** All three sections at once, so each card's behaviour is tested wherever it now lives. */ +function AllParts({ admin, t }: { admin: AdminHook; t: ReturnType['t'] }) { + return ( + <> + {PARTS.map((part) => ( + + ))} + + ); +} + function Harness({ admin }: { admin: AdminHook }) { const { t } = useTranslation(); - return ; + return ; +} + +function PartHarness({ admin, part }: { admin: AdminHook; part: (typeof PARTS)[number] }) { + const { t } = useTranslation(); + return ; } type Spy = ReturnType; @@ -52,7 +76,7 @@ function OidcHarness() { discovery_url: '', }); const admin = buildAdminHook({ oidcConfig, setOidcConfig }); - return ; + return ; } beforeEach(() => { @@ -69,7 +93,7 @@ describe('MAdminSettingsSection', () => { expect(screen.getByText('Authentication Methods')).toBeInTheDocument(); expect(screen.getByText('Passkey login')).toBeInTheDocument(); - expect(screen.getByText('Require two-factor authentication (2FA)')).toBeInTheDocument(); + expect(screen.getByText('Require 2FA')).toBeInTheDocument(); // Card head and field label share the copy expect(screen.getAllByText('Allowed File Types')).toHaveLength(2); expect(screen.getByText('API Keys')).toBeInTheDocument(); @@ -77,11 +101,39 @@ describe('MAdminSettingsSection', () => { expect(screen.getByText('Danger Zone')).toBeInTheDocument(); }); + it('FE-MOB-ASET-025: each section holds the cards of its desktop tab', () => { + const admin = buildAdminHook(); + const { unmount } = render(); + expect(screen.getByText('Authentication Methods')).toBeInTheDocument(); + expect(screen.getByText('Danger Zone')).toBeInTheDocument(); + expect(screen.queryByText('API Keys')).not.toBeInTheDocument(); + expect(screen.queryByText('Live flight status')).not.toBeInTheDocument(); + unmount(); + + const services = render(); + expect(screen.getByText('API Keys')).toBeInTheDocument(); + expect(screen.getAllByText('Allowed File Types').length).toBeGreaterThan(0); + expect(screen.queryByText('Authentication Methods')).not.toBeInTheDocument(); + services.unmount(); + + render(); + expect(screen.getByText('Live flight status')).toBeInTheDocument(); + expect(screen.queryByText('API Keys')).not.toBeInTheDocument(); + expect(screen.queryByText('Danger Zone')).not.toBeInTheDocument(); + }); + + it('FE-MOB-ASET-026: a managed install keeps the danger zone and the passkey domain to its operator', () => { + renderSettings({ managed: true }); + expect(screen.queryByText('Danger Zone')).not.toBeInTheDocument(); + expect(screen.getByRole('switch', { name: 'Require 2FA' })).toBeInTheDocument(); + }); + it('FE-MOB-ASET-002: the OIDC toggles only appear once OIDC is configured', () => { renderSettings({ oidcConfigured: false }); expect(screen.queryByRole('switch', { name: 'SSO Login' })).not.toBeInTheDocument(); expect(screen.queryByRole('switch', { name: 'SSO Auto-Provisioning' })).not.toBeInTheDocument(); + expect(screen.queryByRole('switch', { name: 'Go straight to SSO' })).not.toBeInTheDocument(); }); it('FE-MOB-ASET-003: an env override disables the password toggles and shows the hint', () => { @@ -126,6 +178,11 @@ describe('MAdminSettingsSection', () => { 'oidc_registration', true, admin.setOidcRegistration, ); + await user.click(toggle('Go straight to SSO')); + expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith( + 'oidc_auto_redirect', false, admin.setOidcAutoRedirect, + ); + await user.click(toggle('Enable passkey login')); expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith('passkey_login', true, admin.setPasskeyLogin); }); @@ -134,7 +191,7 @@ describe('MAdminSettingsSection', () => { const user = userEvent.setup(); const admin = renderSettings({ requireMfa: false }); - await user.click(toggle('Require two-factor authentication (2FA)')); + await user.click(toggle('Require 2FA')); expect(admin.handleToggleRequireMfa).toHaveBeenCalledWith(true); }); @@ -190,7 +247,7 @@ describe('MAdminSettingsSection', () => { ); const admin = renderSettings({ allowedFileTypes: 'jpg,png' }); - await user.click(screen.getAllByRole('button', { name: 'Save' })[1]); + await user.click(screen.getAllByRole('button', { name: 'Save' })[3]); await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('File type settings saved')); expect(sent).toEqual({ allowed_file_types: 'jpg,png' }); @@ -205,7 +262,7 @@ describe('MAdminSettingsSection', () => { ); const admin = renderSettings(); - await user.click(screen.getAllByRole('button', { name: 'Save' })[1]); + await user.click(screen.getAllByRole('button', { name: 'Save' })[3]); await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error')); expect(admin.setSavingFileTypes).toHaveBeenLastCalledWith(false); @@ -426,7 +483,7 @@ describe('MAdminSettingsSection', () => { expect(screen.getByDisplayValue('trek')).toBeInTheDocument(); expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument(); - await user.click(screen.getAllByRole('button', { name: 'Save' })[3]); + await user.click(screen.getAllByRole('button', { name: 'Save' })[1]); await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('OIDC configuration saved')); expect(sent).toEqual({ @@ -458,7 +515,7 @@ describe('MAdminSettingsSection', () => { }, }); - await user.click(screen.getAllByRole('button', { name: 'Save' })[3]); + await user.click(screen.getAllByRole('button', { name: 'Save' })[1]); await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Issuer unreachable')); expect(sent.client_secret).toBe('s3cr3t'); diff --git a/client/tests/unit/mobile/admin/MAdminSheets.test.tsx b/client/tests/unit/mobile/admin/MAdminSheets.test.tsx index 3cdfe716e..9a5b6f95c 100644 --- a/client/tests/unit/mobile/admin/MAdminSheets.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminSheets.test.tsx @@ -1,4 +1,4 @@ -// FE-MOB-ASHEET-001 to FE-MOB-ASHEET-026 +// FE-MOB-ASHEET-001 to FE-MOB-ASHEET-028 import React from 'react'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import userEvent from '@testing-library/user-event'; @@ -217,6 +217,30 @@ describe('MAdminSheets', () => { expect(hitId).toBe('2'); }); + it('FE-MOB-ASHEET-027: unlinking single sign-on confirms first, then forgets the SSO identity of that user', async () => { + const user = userEvent.setup(); + let hitId = ''; + server.use( + http.delete('/api/admin/users/:id/sso', ({ params }) => { + hitId = String(params.id); + return HttpResponse.json({ ok: true }); + }), + ); + const admin = renderSheets({ editingUser: ALICE, oidcConfigured: true }); + + await user.click(screen.getByRole('button', { name: 'Remove SSO link' })); + expect(screen.getByRole('dialog', { name: 'Remove SSO link' })).toBeInTheDocument(); + await user.click(screen.getAllByRole('button', { name: 'Remove SSO link' })[1]); + + await waitFor(() => expect(admin.toast.success).toHaveBeenCalled()); + expect(hitId).toBe('2'); + }); + + it('FE-MOB-ASHEET-028: without single sign-on set up there is nothing to unlink', () => { + renderSheets({ editingUser: ALICE, oidcConfigured: false }); + expect(screen.queryByRole('button', { name: 'Remove SSO link' })).not.toBeInTheDocument(); + }); + it('FE-MOB-ASHEET-012: a failing passkey reset toasts the error and keeps the sheet open', async () => { const user = userEvent.setup(); server.use( @@ -406,7 +430,7 @@ describe('MAdminSheets', () => { ); }); - it('FE-MOB-ASHEET-024: confirming the passkey reset without an edited user does nothing', async () => { + it('FE-MOB-ASHEET-024: the passkey confirm closes with the edit sheet and resets nobody', async () => { const user = userEvent.setup(); let called = false; server.use( @@ -419,13 +443,12 @@ describe('MAdminSheets', () => { const { rerender } = render(); await user.click(screen.getByRole('button', { name: 'Reset passkeys' })); - // The edit sheet closes underneath while the confirm stays open + expect(screen.getByRole('dialog', { name: 'Reset passkeys' })).toBeInTheDocument(); + // The confirm belongs to the user being edited: the edit sheet closing takes it along. rerender(); - await user.click(screen.getByRole('button', { name: 'Reset passkeys' })); - + await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Reset passkeys' })).not.toBeInTheDocument()); expect(called).toBe(false); - expect(screen.getByRole('dialog', { name: 'Reset passkeys' })).toBeInTheDocument(); }); it('FE-MOB-ASHEET-025: resetting 2FA confirms, calls the API and reports it', async () => { diff --git a/client/tests/unit/mobile/admin/MAdminUsersSection.test.tsx b/client/tests/unit/mobile/admin/MAdminUsersSection.test.tsx index 2f078300b..c2090a197 100644 --- a/client/tests/unit/mobile/admin/MAdminUsersSection.test.tsx +++ b/client/tests/unit/mobile/admin/MAdminUsersSection.test.tsx @@ -7,6 +7,7 @@ import { resetAllStores } from '../../../helpers/store'; import { buildAdminHook, buildAdminUser, type AdminHook } from '../../../helpers/mobileAdmin'; import { useTranslation } from '../../../../src/i18n'; import MAdminUsersSection from '../../../../src/mobile/screens/admin/MAdminUsersSection'; +import { mobileOptionLabels, pickMobileOption } from '../../../helpers/mobileSelect'; // The permissions matrix self-loads and has its own suite — stub it out here. vi.mock('../../../../src/mobile/screens/admin/MAdminPermissionsPanel', () => ({ @@ -89,10 +90,10 @@ describe('MAdminUsersSection', () => { expect(screen.getByRole('presentation')).toHaveAttribute('src', '/uploads/bob.png'); }); - it('FE-MOB-AUSERS-003: the spinner replaces the list while users are loading', () => { + it('FE-MOB-AUSERS-003: the placeholders replaces the list while users are loading', () => { renderSection({ users: [ALICE], isLoading: true }); - expect(document.querySelector('.animate-spin')).toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).toBeInTheDocument(); expect(screen.queryByText('alice')).not.toBeInTheDocument(); }); @@ -232,15 +233,15 @@ describe('MAdminUsersSection', () => { />, ); - const select = screen.getByRole('combobox') as HTMLSelectElement; - expect(screen.getByRole('option', { name: 'No trip' })).toBeInTheDocument(); - expect(select.value).toBe(''); + const select = screen.getByRole('combobox'); + const name = select.getAttribute('aria-label') ?? ''; + expect(select).toHaveTextContent('No trip'); + expect(await mobileOptionLabels(user, name)).toEqual(['No trip', 'Japan 2026']); + await user.click(within(screen.getByRole('dialog', { name })).getByRole('button', { name: 'Japan 2026' })); + expect(screen.getByRole('combobox')).toHaveTextContent('Japan 2026'); - fireEvent.change(select, { target: { value: '4' } }); - expect((screen.getByRole('combobox') as HTMLSelectElement).value).toBe('4'); - - fireEvent.change(select, { target: { value: '' } }); - expect((screen.getByRole('combobox') as HTMLSelectElement).value).toBe(''); + await pickMobileOption(user, name, 'No trip'); + expect(screen.getByRole('combobox')).toHaveTextContent('No trip'); await user.click(screen.getByRole('button', { name: 'Create & Copy' })); expect(handleCreateInvite).toHaveBeenCalled(); diff --git a/client/tests/unit/mobile/atlas/MAtlas.test.tsx b/client/tests/unit/mobile/atlas/MAtlas.test.tsx index 159d61aa7..a012885a0 100644 --- a/client/tests/unit/mobile/atlas/MAtlas.test.tsx +++ b/client/tests/unit/mobile/atlas/MAtlas.test.tsx @@ -23,11 +23,11 @@ beforeEach(() => { }); describe('MAtlas', () => { - it('FE-MOB-ATLASSCR-001: shows only a spinner while the atlas is loading', () => { + it('FE-MOB-ATLASSCR-001: shows only placeholders while the atlas is loading', () => { setAtlas({ loading: true }); render(); - expect(document.querySelector('.animate-spin')).toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).toBeInTheDocument(); expect(screen.queryByText('atlas.bucketTab')).not.toBeInTheDocument(); }); @@ -37,7 +37,7 @@ describe('MAtlas', () => { }); render(); - expect(document.querySelector('.animate-spin')).not.toBeInTheDocument(); + expect(document.querySelector('[data-skeleton]')).not.toBeInTheDocument(); expect(screen.getByRole('button', { name: 'atlas.bucketTab' })).toBeInTheDocument(); // Stats card labels come from the real translations via useTranslation. expect(screen.getByText('Countries')).toBeInTheDocument(); @@ -225,11 +225,11 @@ describe('MAtlas', () => { it('FE-MOB-ATLASSCR-017: the planned pill stays away while nothing is planned', () => { render(); - expect(screen.queryByRole('switch')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'atlas.showPlanned' })).not.toBeInTheDocument(); expect(screen.queryByText('atlas.planned')).not.toBeInTheDocument(); }); - it('FE-MOB-ATLASSCR-018: a planned country brings up the pill and its switch flips the layer', () => { + it('FE-MOB-ATLASSCR-018: a planned country brings up a header button that flips the layer', () => { const atlas = setAtlas({ data: buildAtlasData({ stats: { totalTrips: 4, totalPlaces: 21, totalCountries: 7, totalDays: 30, totalCities: 9, totalCountriesPlanned: 2 }, @@ -238,8 +238,9 @@ describe('MAtlas', () => { render(); expect(screen.getByText('atlas.planned')).toBeInTheDocument(); - const toggle = screen.getByRole('switch', { name: 'atlas.showPlanned' }); - expect(toggle).toHaveAttribute('aria-checked', 'false'); + // A button of the same shape as the wishlist one, pressed while the layer shows. + const toggle = screen.getByRole('button', { name: 'atlas.showPlanned' }); + expect(toggle).toHaveAttribute('aria-pressed', 'false'); fireEvent.click(toggle); expect(atlas.togglePlanned).toHaveBeenCalled(); diff --git a/client/tests/unit/mobile/collections/MCollPlaceRow.test.tsx b/client/tests/unit/mobile/collections/MCollPlaceRow.test.tsx index 76ec43102..610f0f499 100644 --- a/client/tests/unit/mobile/collections/MCollPlaceRow.test.tsx +++ b/client/tests/unit/mobile/collections/MCollPlaceRow.test.tsx @@ -62,4 +62,14 @@ describe('MCollPlaceRow', () => { expect(props.onToggleSelect).toHaveBeenCalledWith(7) expect(props.onOpen).not.toHaveBeenCalled() }) + + it('FE-MOB-COLL-013: one card holds the place and its pills, the status worded in a readable mix of its colour', () => { + renderRow() + const status = screen.getByRole('button', { name: 'Want to go' }) + const place = screen.getByText('Jungfernstieg').closest('button') as HTMLElement + // Both inside the same card, not in a card of their own beside it. + expect(status.closest('.rounded-2xl')).toBe(place.parentElement) + expect(status.style.color).toContain('color-mix') + expect(status.style.color).toContain('var(--m-ink)') + }) }) diff --git a/client/tests/unit/mobile/collections/MCollPlaceSheet.test.tsx b/client/tests/unit/mobile/collections/MCollPlaceSheet.test.tsx index e0ca7f625..4562fd658 100644 --- a/client/tests/unit/mobile/collections/MCollPlaceSheet.test.tsx +++ b/client/tests/unit/mobile/collections/MCollPlaceSheet.test.tsx @@ -120,6 +120,9 @@ describe('MCollPlaceSheet', () => { fireEvent.click(screen.getByRole('button', { name: 'Visited' })) expect(onSetStatus).toHaveBeenCalledWith('visited') + // #2567: the fourth status sits in the same cycle. + fireEvent.click(screen.getByRole('button', { name: 'Want to revisit' })) + expect(onSetStatus).toHaveBeenCalledWith('revisit') }) it('FE-MOB-CPLSH-005: a read-only member cannot change the status or edit', () => { diff --git a/client/tests/unit/mobile/collections/MCollSheetKit.test.tsx b/client/tests/unit/mobile/collections/MCollSheetKit.test.tsx index 6c1374157..f51b0f1a1 100644 --- a/client/tests/unit/mobile/collections/MCollSheetKit.test.tsx +++ b/client/tests/unit/mobile/collections/MCollSheetKit.test.tsx @@ -63,8 +63,8 @@ describe('MCollSheetKit', () => { render(footer slot) expect(screen.getByText('footer slot')).toBeInTheDocument() - // Both field presets have to sit on the sheet surface token, not a raw colour. - expect(INPUT_CLS).toContain('bg-[color:var(--m-sheet)]') - expect(TEXTAREA_CLS).toContain('bg-[color:var(--m-sheet)]') + // Both field presets sit on the field surface token, as every phone sheet's fields, not a raw colour. + expect(INPUT_CLS).toContain('bg-[color:var(--m-ic)]') + expect(TEXTAREA_CLS).toContain('bg-[color:var(--m-ic)]') }) }) diff --git a/client/tests/unit/mobile/collections/MCollTripPickerSheet.test.tsx b/client/tests/unit/mobile/collections/MCollTripPickerSheet.test.tsx index 9234bfd0a..360994f92 100644 --- a/client/tests/unit/mobile/collections/MCollTripPickerSheet.test.tsx +++ b/client/tests/unit/mobile/collections/MCollTripPickerSheet.test.tsx @@ -69,11 +69,11 @@ describe('MCollTripPickerSheet', () => { expect(screen.getByText('Sun, Mar 1, 2020')).toBeInTheDocument() }) - it('FE-MOB-CTRIPP-004: the spinner holds the list until the trips arrive', async () => { + it('FE-MOB-CTRIPP-004: the placeholders holds the list until the trips arrive', async () => { let resolve!: (v: { trips: typeof TRIPS }) => void vi.mocked(tripsApi.list).mockReturnValue(new Promise(r => { resolve = r })) setup() - expect(document.querySelector('.animate-spin')).not.toBeNull() + expect(document.querySelector('[data-skeleton]')).not.toBeNull() expect(screen.queryByText('No trips yet')).not.toBeInTheDocument() resolve({ trips: TRIPS }) diff --git a/client/tests/unit/mobile/collections/MCollections.test.tsx b/client/tests/unit/mobile/collections/MCollections.test.tsx index e9e97a7ad..7e28f83b5 100644 --- a/client/tests/unit/mobile/collections/MCollections.test.tsx +++ b/client/tests/unit/mobile/collections/MCollections.test.tsx @@ -1,12 +1,15 @@ -// FE-MOB-COLSCR-001 to FE-MOB-COLSCR-033 +// FE-MOB-COLSCR-001 to FE-MOB-COLSCR-038 import React from 'react' import { describe, it, expect, vi, beforeEach } from 'vitest' -import { render, screen, fireEvent, waitFor } from '../../../helpers/render' +import { render, screen, fireEvent, waitFor, within } from '../../../helpers/render' +import { setSizeClass } from '../../../helpers/sizeClass' import MCollections from '../../../../src/mobile/screens/collections/MCollections' import { ALL_SAVED } from '../../../../src/store/collectionStore' const mocks = vi.hoisted(() => ({ coll: {} as Record })) +const routeTransition = vi.hoisted(() => ({ skipNextRouteTransition: vi.fn() })) +vi.mock('../../../../src/mobile/routeTransition', () => routeTransition) vi.mock('../../../../src/pages/collections/useCollections', () => ({ useCollections: () => mocks.coll, })) @@ -162,10 +165,11 @@ function makeHook(over: Record = {}): Record { incomingInvites: [], orderedInvites: [], routeInvite: null, - counts: { all: 1, idea: 1, want: 0, visited: 0 }, + counts: { all: 1, idea: 1, want: 0, visited: 0, revisit: 0 }, view: 'list', statusFilter: 'all', categoryFilter: 'all', + categoryOptions: [], ratingFilter: 'all', search: '', selectedPlaceId: null, @@ -206,21 +210,22 @@ describe('MCollections', () => { mocks.coll = makeHook() }) - it('FE-MOB-COLSCR-001: shows only the spinner while the first load is in flight', () => { + it('FE-MOB-COLSCR-001: shows only the placeholders while the first load is in flight', () => { mocks.coll = makeHook({ loading: true, collections: [], places: [], visiblePlaces: [] }) render() expect(screen.queryByPlaceholderText('collections.search')).not.toBeInTheDocument() - expect(document.querySelector('.animate-spin')).not.toBeNull() + expect(document.querySelector('[data-skeleton]')).not.toBeNull() }) - it('FE-MOB-COLSCR-002: with no lists at all it offers the first-list CTA', () => { + it('FE-MOB-COLSCR-002: with no lists at all the dock + button starts the first one; the screen has no button of its own', async () => { mocks.coll = makeHook({ collections: [], ownedLists: [], activeCollection: null, activeId: null, canShare: false }) - render() + render(, { initialEntries: ['/collections?create=place'] }) expect(screen.getByText('collections.empty.firstTitle')).toBeInTheDocument() - fireEvent.click(screen.getByRole('button', { name: /collections.newList/ })) - expect(fn('setEditorTarget')).toHaveBeenCalledWith('new') + expect(screen.queryByRole('button', { name: /^collections.newList$/ })).not.toBeInTheDocument() + await waitFor(() => expect(fn('setEditorTarget')).toHaveBeenCalledWith('new')) + expect(fn('setShowAddPlace')).not.toHaveBeenCalled() expect(screen.queryByPlaceholderText('collections.search')).not.toBeInTheDocument() }) @@ -266,6 +271,8 @@ describe('MCollections', () => { fireEvent.click(screen.getByText('Julien Tipps')) expect(fn('handleSelectList')).toHaveBeenCalledWith(2) + // Another list is the same screen: the URL change must not slide a page in. + expect(routeTransition.skipNextRouteTransition).toHaveBeenCalled() // Picking closes the dropdown again. expect(screen.queryByText('Julien Tipps')).not.toBeInTheDocument() }) @@ -299,7 +306,7 @@ describe('MCollections', () => { // The union has no label chip, so the status chip is the only "all" chip. mocks.coll = makeHook({ isAllSaved: true, activeId: ALL_SAVED, activeCollection: null, canShare: false, - counts: { all: 5, idea: 2, want: 2, visited: 1 }, + counts: { all: 5, idea: 2, want: 2, visited: 1, revisit: 0 }, }) render() @@ -360,7 +367,7 @@ describe('MCollections', () => { expect(fn('setLabelFilter')).toHaveBeenCalledWith([2, 1]) }) - it('FE-MOB-COLSCR-013: a list without labels says so, and the manage chip opens the manager', () => { + it('FE-MOB-COLSCR-013: a list without labels says so, and the label panel opens the manager', () => { render() // Status chip and label chip both read "all" while nothing is filtered. @@ -369,8 +376,10 @@ describe('MCollections', () => { fireEvent.click(chips[1]) expect(screen.getByText('collections.labels.empty')).toBeInTheDocument() - fireEvent.click(screen.getByRole('button', { name: /collections.labels.title/ })) + fireEvent.click(screen.getByRole('button', { name: 'collections.labels.add' })) expect(fn('setShowLabelManager')).toHaveBeenCalledWith(true) + // Opening the manager closes the panel. + expect(screen.queryByText('collections.labels.empty')).not.toBeInTheDocument() }) it('FE-MOB-COLSCR-014: the backdrop under an open dropdown closes it again', () => { @@ -400,7 +409,7 @@ describe('MCollections', () => { fireEvent.click(screen.getByRole('button', { name: /collections.selectAll/ })) expect(fn('handleSelectAll')).toHaveBeenCalledTimes(1) - fireEvent.click(screen.getByRole('button', { name: 'common.cancel' })) + fireEvent.click(screen.getByRole('button', { name: 'packing.editDone' })) expect(fn('setSelectMode')).toHaveBeenCalledWith(false) }) @@ -459,7 +468,7 @@ describe('MCollections', () => { mocks.coll = makeHook({ places: [], visiblePlaces: [], placesLoading: true }) const loadingView = render() - expect(loadingView.container.querySelector('.animate-spin')).not.toBeNull() + expect(loadingView.container.querySelector('[data-skeleton]')).not.toBeNull() mocks.coll = makeHook({ places: [], visiblePlaces: [] }) render() @@ -647,12 +656,12 @@ describe('MCollections', () => { expect(fn('setShowAddPlace')).not.toHaveBeenCalled() }) - it('FE-MOB-COLSCR-029: desktop-only category and rating filters are cleared on phone (#1435)', async () => { + it('FE-MOB-COLSCR-029: the desktop-only rating filter is cleared on phone, the category filter is kept (#1435, #2618)', async () => { mocks.coll = makeHook({ categoryFilter: 3, ratingFilter: 4 }) render() - await waitFor(() => expect(fn('setCategoryFilter')).toHaveBeenCalledWith('all')) - expect(fn('setRatingFilter')).toHaveBeenCalledWith('all') + await waitFor(() => expect(fn('setRatingFilter')).toHaveBeenCalledWith('all')) + expect(fn('setCategoryFilter')).not.toHaveBeenCalled() }) it('FE-MOB-COLSCR-030: the add sheet has no fixed target while the union is active', () => { @@ -665,6 +674,66 @@ describe('MCollections', () => { }) }) +// #2618: the phone could filter by status and label, but not by category. +describe('MCollections: category filter (#2618)', () => { + const categoryOptions = [ + { id: 3, name: 'Restaurant', color: '#E8843D', icon: 'utensils', count: 2 }, + { id: 5, name: 'Museum', color: null, icon: null, count: 1 }, + ] + + it('FE-MOB-COLSCR-035: the chip lists the categories present with their counts and picks one', () => { + mocks.coll = makeHook({ categoryOptions }) + render() + + const chip = screen.getByRole('button', { name: 'categories.title: collections.status.filterAll' }) + expect(chip).toHaveAttribute('aria-expanded', 'false') + fireEvent.click(chip) + expect(chip).toHaveAttribute('aria-expanded', 'true') + // The "all" row counts every categorised place. + expect(screen.getByRole('button', { name: /^collections.status.filterAll\s*3$/ })).toBeInTheDocument() + + fireEvent.click(screen.getByRole('button', { name: /^Restaurant\s*2$/ })) + expect(fn('setCategoryFilter')).toHaveBeenCalledWith(3) + // Picking closes the panel. + expect(screen.queryByRole('button', { name: /^Museum\s*1$/ })).not.toBeInTheDocument() + }) + + it('FE-MOB-COLSCR-036: an active category names itself and the "all" row clears it', () => { + mocks.coll = makeHook({ categoryOptions, categoryFilter: 5 }) + render() + + fireEvent.click(screen.getByRole('button', { name: 'categories.title: Museum' })) + fireEvent.click(screen.getByRole('button', { name: /^collections.status.filterAll\s*3$/ })) + expect(fn('setCategoryFilter')).toHaveBeenCalledWith('all') + }) + + it('FE-MOB-COLSCR-037: without categories the chip stays away, unless a category is still set from another list', () => { + mocks.coll = makeHook() + const { unmount } = render() + expect(screen.queryByRole('button', { name: /^categories.title/ })).not.toBeInTheDocument() + unmount() + + mocks.coll = makeHook({ categoryFilter: 7, categories: [{ id: 7, name: 'Beach' }] }) + render() + fireEvent.click(screen.getByRole('button', { name: 'categories.title: Beach' })) + fireEvent.click(screen.getByRole('button', { name: /^collections.status.filterAll\s*0$/ })) + expect(fn('setCategoryFilter')).toHaveBeenCalledWith('all') + }) + + it('FE-MOB-COLSCR-038: opening one filter panel closes the other', () => { + mocks.coll = makeHook({ categoryOptions }) + render() + + fireEvent.click(screen.getByRole('button', { name: 'categories.title: collections.status.filterAll' })) + expect(screen.getByRole('button', { name: /^Museum\s*1$/ })).toBeInTheDocument() + // The status chip is the first chip reading "all". + fireEvent.click(screen.getAllByRole('button', { name: 'collections.status.filterAll' })[0]) + expect(screen.queryByRole('button', { name: /^Museum\s*1$/ })).not.toBeInTheDocument() + // The status panel is open in its place (its rows name each status). + expect(screen.getAllByRole('button', { name: /collections.status.idea/ }).length).toBeGreaterThan(0) + }) +}) + // #2645: the phone had no way to answer a list invite, and the notification's // link landed on "Start your first collection". describe('MCollections: invites (#2645)', () => { @@ -694,4 +763,17 @@ describe('MCollections: invites (#2645)', () => { expect(names).toEqual(['Lisbon', 'Rome']) expect(screen.getByPlaceholderText('collections.search')).toBeInTheDocument() }) + + it('FE-MOB-COLSCR-034: with room for two panes the lists stand beside the places and the head names the list', () => { + setSizeClass('split') + render() + const lists = screen.getByRole('navigation', { name: 'collections.title' }) + expect(within(lists).getByRole('button', { name: /Hamburg/ })).toHaveAttribute('aria-current', 'page') + expect(screen.getByRole('heading', { name: 'Hamburg' })).toBeInTheDocument() + + fireEvent.click(within(lists).getByRole('button', { name: /collections.allSaved/ })) + expect(fn('handleSelectList')).toHaveBeenCalledWith(ALL_SAVED) + fireEvent.click(within(lists).getByRole('button', { name: /collections.newList/ })) + expect(fn('setEditorTarget')).toHaveBeenCalledWith('new') + }) }) diff --git a/client/tests/unit/mobile/collections/collectionsMobileModel.test.ts b/client/tests/unit/mobile/collections/collectionsMobileModel.test.ts index 6e7d0c04a..a5bb36c24 100644 --- a/client/tests/unit/mobile/collections/collectionsMobileModel.test.ts +++ b/client/tests/unit/mobile/collections/collectionsMobileModel.test.ts @@ -21,10 +21,12 @@ describe('collectionsMobileModel', () => { expect(categoryMeta({ name: null, color: '#123456' })).toBeNull() }) - it('FE-MOB-COLL-003: the status canon covers the Idea → Want to go → Visited cycle', () => { + it('FE-MOB-COLL-003: the status canon covers the Idea → Want to go → Visited → Want to revisit cycle', () => { expect(STATUS_SPEC.idea.labelKey).toBe('collections.status.idea') expect(STATUS_SPEC.want.labelKey).toBe('collections.status.want') expect(STATUS_SPEC.visited.labelKey).toBe('collections.status.visited') + expect(STATUS_SPEC.revisit.labelKey).toBe('collections.status.revisit') + expect(STATUS_SPEC.revisit.color).toBe('var(--m-st-pending)') expect(STATUS_SPEC.idea.color).toBe('#9A9AA1') expect(STATUS_SPEC.want.color).toBe('#4A7DDB') expect(STATUS_SPEC.visited.color).toBe('#2FA37A') diff --git a/client/tests/unit/mobile/dashboard/MDashWidgets.test.tsx b/client/tests/unit/mobile/dashboard/MDashWidgets.test.tsx index 6b8b97f24..170907dc4 100644 --- a/client/tests/unit/mobile/dashboard/MDashWidgets.test.tsx +++ b/client/tests/unit/mobile/dashboard/MDashWidgets.test.tsx @@ -43,6 +43,8 @@ function enableCollectionsAddon(enabled: boolean) { beforeEach(() => { resetAllStores(); + // The converter waits for the saved pair (#3009); these widgets render with settings in place. + useSettingsStore.setState({ isLoaded: true }); fxHandler(); collectionsHandler([]); }); @@ -396,7 +398,10 @@ describe('MUpcomingWidget', () => { />, ); - expect(screen.getByText('Sep 3 · 19:30 · Narita')).toBeInTheDocument(); + // Date, time and place as badges of their own, no dots strung between them. + expect(screen.getByText('Sep 3')).toBeInTheDocument(); + expect(screen.getByText('19:30')).toBeInTheDocument(); + expect(screen.getByText('Narita')).toBeInTheDocument(); }); it('FE-MOB-DWID-030: an unparseable date degrades to the remaining parts', () => { @@ -447,6 +452,8 @@ describe('MUpcomingWidget', () => { />, ); - expect(screen.getAllByText('Pending')).toHaveLength(1); + // A letter on the icon's corner, with the word as its accessible name. + expect(screen.getAllByLabelText('Pending')).toHaveLength(1); + expect(screen.getByLabelText('Pending')).toHaveTextContent(/^P$/); }); }); diff --git a/client/tests/unit/mobile/dashboard/MDashboard.test.tsx b/client/tests/unit/mobile/dashboard/MDashboard.test.tsx index b8a293235..d137687a8 100644 --- a/client/tests/unit/mobile/dashboard/MDashboard.test.tsx +++ b/client/tests/unit/mobile/dashboard/MDashboard.test.tsx @@ -8,6 +8,7 @@ import { useInAppNotificationStore } from '../../../../src/store/inAppNotificati import { usePluginStore } from '../../../../src/store/pluginStore'; import type { TripCardBadge } from '../../../../src/api/client'; import type { DashboardTrip } from '../../../../src/pages/dashboard/dashboardModel'; +import { setSizeClass } from '../../../helpers/sizeClass'; // FE-MOB-DASH-001 onwards @@ -109,6 +110,18 @@ describe('MDashboard', () => { expect(screen.getByText('Lisbon')).toBeInTheDocument(); }); + it('FE-MOB-DASH-040: the spotlight title keeps its own direction and its progress fills from the start edge', () => { + mocks.dash = buildDash({ spotlight: buildTrip() }); + render(); + // dir="auto": a Latin title in the Arabic UI is cut at its end, not its beginning. + expect(screen.getAllByText('Japan 2026')[0]).toHaveAttribute('dir', 'auto'); + const fill = document.querySelector('span[style*="width"].rounded-full.bg-white') as HTMLElement; + expect(fill).not.toBeNull(); + // start-0, not left-0: in Arabic the bar fills from the right like every other bar. + expect(fill).toHaveClass('start-0'); + expect(fill.className).not.toMatch(/\bleft-0\b/); + }); + it('FE-MOB-DASH-002: archived filter swaps card actions to restore + permanent delete', () => { const handleUnarchive = vi.fn(); mocks.dash = buildDash({ @@ -404,6 +417,31 @@ describe('MDashboard', () => { expect(screen.getByText('Upcoming reservations')).toBeInTheDocument(); }); + it('FE-MOB-DASH-041: crossing the split size keeps the widgets mounted, so the converter keeps its amount', () => { + mocks.dash = buildDash(); + render(); + const amount = screen.getAllByRole('textbox', { name: 'From' })[0] as HTMLInputElement; + fireEvent.change(amount, { target: { value: '250' } }); + + setSizeClass('split'); + expect(screen.getAllByRole('textbox', { name: 'From' })[0]).toBe(amount); + expect(amount.value).toBe('250'); + + setSizeClass('compact'); + expect(screen.getAllByRole('textbox', { name: 'From' })[0]).toBe(amount); + expect(amount.value).toBe('250'); + }); + + it('FE-MOB-DASH-042: on a landscape tablet the widget column scrolls on its own, within the window', () => { + mocks.dash = buildDash(); + render(); + const column = screen.getAllByRole('textbox', { name: 'From' })[0].closest('[class*="split:sticky"]') as HTMLElement; + expect(column).not.toBeNull(); + expect(column.className).toContain('split:overflow-y-auto'); + expect(column.className).toContain('split:max-h-[calc(100dvh-var(--m-safe-top,12px)-70px)]'); + expect(column.className).toContain('split:overscroll-contain'); + }); + it('FE-MOB-DASH-027: a malformed date renders a dash instead of crashing', () => { mocks.dash = buildDash({ gridTrips: [buildTrip({ id: 14, start_date: 'not-a-date', end_date: iso(3) })] }); render(); diff --git a/client/tests/unit/mobile/dashboard/MNewTripSheet.test.tsx b/client/tests/unit/mobile/dashboard/MNewTripSheet.test.tsx index 71d6750bc..ae7a0f51a 100644 --- a/client/tests/unit/mobile/dashboard/MNewTripSheet.test.tsx +++ b/client/tests/unit/mobile/dashboard/MNewTripSheet.test.tsx @@ -97,6 +97,18 @@ describe('MNewTripSheet', () => { expect(screen.getByText('Add cover image')).toBeInTheDocument(); }); + it('FE-MOB-NTSH-095: the form uses the shared form chrome: icon header, flat fields, no frame on the focused sheet', () => { + render( {}} onSave={() => {}} />); + const dialog = screen.getByRole('dialog', { name: 'Create New Trip' }); + expect(dialog).toHaveClass('m-form-sheet'); + expect(dialog.querySelector('.m-fs-head')).not.toBeNull(); + expect(dialog.querySelector('.m-fs-foot')).not.toBeNull(); + // No section cards inside the card. + expect(dialog.querySelector('section')).toBeNull(); + // Each date has its field to itself: the keyboard entry waits in the picker. + expect(screen.queryByRole('button', { name: /enter date manually/i })).toBeNull(); + }); + it('FE-MOB-NTSH-001b: create mode defaults the currency to the user\'s default_currency (#1784)', () => { useSettingsStore.setState(s => ({ settings: { ...s.settings, default_currency: 'USD' } })); render( {}} onSave={() => {}} />); diff --git a/client/tests/unit/mobile/formSheet.test.tsx b/client/tests/unit/mobile/formSheet.test.tsx new file mode 100644 index 000000000..90f006a8f --- /dev/null +++ b/client/tests/unit/mobile/formSheet.test.tsx @@ -0,0 +1,195 @@ +import { act, renderHook } from '@testing-library/react'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { useRef, useState } from 'react'; +import { describe, expect, it, vi } from 'vitest'; +import { sizeClassOf } from '../../../src/hooks/sizeClass'; +import { useAutoGrow } from '../../../src/hooks/useAutoGrow'; +import MSheet from '../../../src/mobile/components/MSheet'; +import { edgeFadeClass, useEdgeFade } from '../../../src/mobile/components/useEdgeFade'; +import { + FormSheetBody, + FormSheetFooter, + FormSheetHeader, + SheetDateField, +} from '../../../src/mobile/screens/trip/sheets/PlSheetChrome'; +import { MemberAvatar } from '../../../src/mobile/screens/trip/tabs/MCostsPayment'; +import { fireEvent, render, screen } from '../../helpers/render'; + +// FE-MOB-FORMSHEET-001 onwards: the form sheet the touch shell presents every +// form in (MSheet `form` + PlSheetChrome), and the stylesheet rules that lay it out. + +function Form({ onClose = () => {} }: { onClose?: () => void }) { + return ( + + + + + + {}} submitLabel="Add" /> + + ); +} + +describe('form sheet chrome', () => { + it('FE-MOB-FORMSHEET-001: header, body and footer carry the parts the short-window layout places', () => { + render(); + const panel = screen.getByRole('dialog', { name: 'Add expense' }); + expect(panel).toHaveClass('m-form-sheet'); + const [head, body, foot] = Array.from(panel.children) as HTMLElement[]; + expect(head).toHaveClass('m-fs-head'); + expect(body).toHaveClass('m-fs-body', 'overflow-y-auto'); + expect(foot).toHaveClass('m-fs-foot'); + // The close button is the one the layout hides once Cancel stands beside the title. + expect(screen.getByRole('button', { name: 'Close' })).toHaveClass('m-fs-close'); + }); + + it('FE-MOB-FORMSHEET-002: a long title wraps to a second line instead of being cut after one', () => { + render(); + const title = screen.getAllByText('Add expense').find((el) => el.tagName === 'DIV') as HTMLElement; + expect(title).toHaveClass('line-clamp-2'); + expect(title).not.toHaveClass('truncate'); + }); + + it('FE-MOB-FORMSHEET-003: the body is the container its paired rows measure against', () => { + render(); + const body = screen.getByRole('textbox', { name: 'Name' }).parentElement as HTMLElement; + expect(body.className).toContain('[container-type:inline-size]'); + }); + + it('FE-MOB-FORMSHEET-004: the body fades at the foot while more waits below, and at the top once scrolled', () => { + render(); + const body = screen.getByRole('textbox', { name: 'Name' }).parentElement as HTMLElement; + Object.defineProperty(body, 'scrollHeight', { configurable: true, value: 900 }); + Object.defineProperty(body, 'clientHeight', { configurable: true, value: 400 }); + act(() => { + body.dispatchEvent(new Event('scroll')); + }); + expect(body).toHaveClass('m-fade-b'); + act(() => { + body.scrollTop = 200; + body.dispatchEvent(new Event('scroll')); + }); + expect(body).toHaveClass('m-fade-tb'); + act(() => { + body.scrollTop = 500; + body.dispatchEvent(new Event('scroll')); + }); + expect(body).toHaveClass('m-fade-t'); + }); + + it('FE-MOB-FORMSHEET-005: the date field keeps its keyboard entry in the picker, so the date has the field to itself', () => { + render( {}} />); + // No second round button beside the date taking its room. + expect(screen.queryByRole('button', { name: /enter date manually|common\.datepicker\.enterManually/i })).toBeNull(); + const trigger = screen.getByRole('button', { expanded: false }); + fireEvent.click(trigger); + expect( + screen.getByRole('button', { name: /enter date manually|common\.datepicker\.enterManually/i }) + ).toBeInTheDocument(); + expect(trigger.closest('.rounded-full')).not.toBeNull(); + }); +}); + +describe('useEdgeFade on the vertical axis', () => { + function box(scrollHeight: number, clientHeight: number, scrollTop = 0) { + const el = document.createElement('div'); + Object.defineProperty(el, 'scrollHeight', { configurable: true, value: scrollHeight }); + Object.defineProperty(el, 'clientHeight', { configurable: true, value: clientHeight }); + el.scrollTop = scrollTop; + return el; + } + + it('FE-MOB-FORMSHEET-006: reads the top and the foot, and its classes never mirror', () => { + expect(edgeFadeClass(renderHook(() => useEdgeFade(box(400, 400), 'y')).result.current, 'y')).toBe(''); + expect(edgeFadeClass(renderHook(() => useEdgeFade(box(900, 400), 'y')).result.current, 'y')).toBe('m-fade-b'); + expect(edgeFadeClass({ start: true, end: false }, 'y')).toBe('m-fade-t'); + expect(edgeFadeClass({ start: true, end: true }, 'y')).toBe('m-fade-tb'); + // The strip's own classes are unchanged. + expect(edgeFadeClass({ start: true, end: true })).toBe('m-fade-se'); + }); + + it('FE-MOB-FORMSHEET-007: measures again when fields come and go inside a box that keeps its height', async () => { + const el = box(400, 400); + const { result } = renderHook(() => useEdgeFade(el, 'y')); + expect(result.current.end).toBe(false); + Object.defineProperty(el, 'scrollHeight', { configurable: true, value: 800 }); + await act(async () => { + el.appendChild(document.createElement('div')); + // Measured on the next frame, so a burst of changes is measured once. + await new Promise((resolve) => setTimeout(resolve, 40)); + }); + expect(result.current.end).toBe(true); + }); +}); + +describe('useAutoGrow', () => { + it('FE-MOB-FORMSHEET-008: a textarea grows to its lines instead of slicing the last one', () => { + function Story() { + const ref = useRef(null); + const [text, setText] = useState('one'); + useAutoGrow(ref, text); + return