mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 15:40:06 +00:00
Compare commits
99 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| daf3c765b0 | |||
| 058c3b3909 | |||
| 7f3ead2c85 | |||
| 1553be3d5b | |||
| fc891c16b2 | |||
| bcad069705 | |||
| 610845e84d | |||
| 4705d88933 | |||
| ed134fdef3 | |||
| 8c5e7373d3 | |||
| 5b27624c33 | |||
| ac0f8f052d | |||
| 81b66d3170 | |||
| 9bfdd10638 | |||
| bbc9c72168 | |||
| 5c5c468489 | |||
| 5685cdfe13 | |||
| 82ded80978 | |||
| 46a2fd2bbb | |||
| ff676c8fc2 | |||
| 0b6a77eeb5 | |||
| 7c6189f504 | |||
| 6bbe597719 | |||
| 218304179c | |||
| a6328cef3b | |||
| 96d8b5c664 | |||
| b5350287a4 | |||
| dbe0b847bd | |||
| fc1022a452 | |||
| 8b008a74fe | |||
| 1fa5c8cec2 | |||
| 443a4fd488 | |||
| 8d5d34fbb3 | |||
| 57fb2cf47b | |||
| 20d10d765d | |||
| fd6d1969f5 | |||
| 8c0cca536a | |||
| dd1a117b92 | |||
| 59b8d00373 | |||
| 9ea489ac97 | |||
| 17c56326e9 | |||
| f3bdcf7ffb | |||
| e7b900d309 | |||
| ffd9338217 | |||
| 2186d8b230 | |||
| 06aaddc34d | |||
| 6f669920f1 | |||
| 1fb20a542c | |||
| d8be9a40e7 | |||
| 512584b4f1 | |||
| 985998e757 | |||
| 742c0dd72d | |||
| efd34df038 | |||
| 321980c95b | |||
| d4595269b5 | |||
| 32de7adbf6 | |||
| fef7ac4587 | |||
| 7a57c58dd0 | |||
| 3dd63331bc | |||
| 20c8457f18 | |||
| eaef3c014e | |||
| f02c0e088b | |||
| 2915ea573a | |||
| 407de33560 | |||
| addcbe4801 | |||
| a9fd443b63 | |||
| b8dffdbb13 | |||
| 3b42ffa67b | |||
| 2ea1c99e31 | |||
| d383d3527b | |||
| 05843c8e5b | |||
| 19270adef8 | |||
| f9ab280b7e | |||
| c88d3abc5e | |||
| 10d95a39ac | |||
| 7d802081ce | |||
| 7586126797 | |||
| 9fa2bef101 | |||
| ed1bba9371 | |||
| 3c1cf8b347 | |||
| 1ed77870f9 | |||
| 22ee4dbac7 | |||
| 6926591112 | |||
| 66382e791b | |||
| 32837afe2e | |||
| 05f4c84885 | |||
| 6905729ab6 | |||
| 85aa1c91ff | |||
| de9901d941 | |||
| 95a0cd2f77 | |||
| f922068a8e | |||
| 5c5d85ef60 | |||
| d83e98366b | |||
| 756eae39ff | |||
| 4f66a344ca | |||
| 96b2778c2f | |||
| 98c883b4e8 | |||
| df82208bd5 | |||
| 18867d9499 |
+15
-1
@@ -28,8 +28,10 @@ updates:
|
||||
groups:
|
||||
# Packages that release in lockstep move together, so a PR never pins
|
||||
# half of them on one version and half on the next.
|
||||
# better-sqlite3 and kysely are pinned exactly by @mikro-orm/sqlite and
|
||||
# share its connection, so they move with MikroORM.
|
||||
mikro-orm:
|
||||
patterns: ['@mikro-orm/*']
|
||||
patterns: ['@mikro-orm/*', better-sqlite3, kysely]
|
||||
update-types: [minor, patch]
|
||||
nestjs:
|
||||
patterns: ['@nestjs/*']
|
||||
@@ -54,6 +56,18 @@ updates:
|
||||
# by hand once mapbox-gl checks the built-ins first again.
|
||||
- dependency-name: mapbox-gl
|
||||
versions: ['>=3.33.0']
|
||||
# The packages below move by hand, each for its reason. A security
|
||||
# advisory for one of them still shows up in the Security tab, where it
|
||||
# is handled together with that reason.
|
||||
#
|
||||
# Pinned exactly by @nestjs/schedule; a newer cron of our own would be a
|
||||
# second copy whose CronJob the scheduler does not accept.
|
||||
- dependency-name: cron
|
||||
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
|
||||
# Root pins that must name the rollup version the lockfile installs (the
|
||||
# Alpine image needs the musl binaries).
|
||||
- dependency-name: '@rollup/rollup-linux-*-musl'
|
||||
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
|
||||
|
||||
# plugin-sdk is standalone with a lockfile of its own and ships to npm.
|
||||
- package-ecosystem: npm
|
||||
|
||||
@@ -105,9 +105,63 @@ jobs:
|
||||
track: ${{ inputs.track || 'internal' }}
|
||||
status: draft
|
||||
|
||||
# The same build for installs outside Google Play: the universal APK Google
|
||||
# Play makes of this bundle, signed with the Play app signing key, published
|
||||
# to liketrek/trek-android for Obtainium (wiki/Native-Apps.md). Only for a
|
||||
# release tag, and held back while the app needs a server version that is
|
||||
# not released yet.
|
||||
- name: Whether the latest server release serves this build
|
||||
id: released
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
tag=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name)
|
||||
git fetch --depth=1 origin "refs/tags/$tag:refs/tags/$tag"
|
||||
git show "$tag:server/src/nest/health/features.controller.ts" > "$RUNNER_TEMP/released-features.ts"
|
||||
node scripts/ci/android-apk-release.mjs guard "$RUNNER_TEMP/released-features.ts" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Universal APK from Google Play
|
||||
if: steps.released.outputs.publish == 'true'
|
||||
env:
|
||||
PLAY_APK_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_APK_SERVICE_ACCOUNT_JSON }}
|
||||
APK: trek-${{ steps.version.outputs.version }}.apk
|
||||
run: |
|
||||
printf '%s' "$PLAY_APK_SERVICE_ACCOUNT_JSON" > "$RUNNER_TEMP/play-apk.json"
|
||||
node scripts/ci/android-apk-release.mjs download "$RUNNER_TEMP/play-apk.json" com.liketrek.trek \
|
||||
"${{ steps.version.outputs.build }}" "$RUNNER_TEMP/$APK"
|
||||
rm -f "$RUNNER_TEMP/play-apk.json"
|
||||
cd "$RUNNER_TEMP" && sha256sum "$APK" > "$APK.sha256"
|
||||
|
||||
- uses: actions/create-github-app-token@v3
|
||||
if: steps.released.outputs.publish == 'true'
|
||||
id: apk-token
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: liketrek
|
||||
repositories: trek-android
|
||||
|
||||
# One release per app version: a newer build of the same version replaces
|
||||
# its APK, so the release always holds what Google Play holds for it.
|
||||
- name: Publish to liketrek/trek-android
|
||||
if: steps.released.outputs.publish == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.apk-token.outputs.token }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
BUILD: ${{ steps.version.outputs.build }}
|
||||
run: |
|
||||
apk="$RUNNER_TEMP/trek-$VERSION.apk"
|
||||
notes="TREK $VERSION for Android (build $BUILD): the build Google Play distributes, with the same signature. Connect it to your own TREK server; push and TREK Cloud need Google Play services. Changes: https://github.com/liketrek/TREK/releases"
|
||||
if gh release view "v$VERSION" -R liketrek/trek-android > /dev/null 2>&1; then
|
||||
gh release upload "v$VERSION" -R liketrek/trek-android --clobber "$apk" "$apk.sha256"
|
||||
gh release edit "v$VERSION" -R liketrek/trek-android --notes "$notes"
|
||||
else
|
||||
gh release create "v$VERSION" -R liketrek/trek-android --title "TREK $VERSION" --notes "$notes" "$apk" "$apk.sha256"
|
||||
fi
|
||||
|
||||
- name: Remove the upload key
|
||||
if: always()
|
||||
run: rm -f "$RUNNER_TEMP/upload.jks"
|
||||
run: rm -f "$RUNNER_TEMP/upload.jks" "$RUNNER_TEMP/play-apk.json"
|
||||
|
||||
ios:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
|
||||
@@ -1224,6 +1224,14 @@ jobs:
|
||||
--set service.port=8080 \
|
||||
--set-json 'httpRoute={"enabled":true,"parentRefs":[{"name":"gateway","namespace":"gateway-system","sectionName":"https"}],"hostnames":["trek.example.com"],"paths":["/","/api"],"annotations":{"example.com/note":"custom route"},"timeouts":{"request":"0s","backendRequest":"0s"}}' \
|
||||
> "$out/http-route-variants.yaml"
|
||||
helm template trek charts/trek \
|
||||
--set-json 'extraObjects=[{"apiVersion":"batch/v1","kind":"CronJob","metadata":{"name":"{{ include \"trek.fullname\" . }}-backup-copy"},"spec":{"schedule":"0 3 * * *","jobTemplate":{"spec":{"template":{"spec":{"restartPolicy":"OnFailure","containers":[{"name":"copy","image":"busybox:1.36","command":["ls","/data/backups"],"volumeMounts":[{"name":"data","mountPath":"/data","readOnly":true}]}],"volumes":[{"name":"data","persistentVolumeClaim":{"claimName":"{{ include \"trek.fullname\" . }}-data","readOnly":true}}]}}}}}},"apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: {{ .Release.Name }}-notes\ndata:\n release: {{ .Release.Name | quote }}\n"]' \
|
||||
> "$out/extra-objects.yaml"
|
||||
# kubeconform accepts a name that still reads {{ ... }}, so check that both forms went through tpl.
|
||||
if grep -n '{{' "$out/extra-objects.yaml"; then
|
||||
echo "::error::extraObjects left a template unrendered"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Check the manifests against the Kubernetes schemas
|
||||
# The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources.
|
||||
|
||||
@@ -60,3 +60,4 @@ See `values.yaml` for more options.
|
||||
- Set `env.OIDC_DISCOVERY_URL` to override the auto-constructed OIDC discovery endpoint. Required for providers (e.g. Authentik) that expose it at a non-standard path.
|
||||
- `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands `/app/data` and `/app/uploads` to `node` (uid 1000) if the directory or anything directly inside it is not owned by `node` yet, and drops to `node`. Deeper files are not checked. Only the owning user is changed (plus a `root` group), so a different `fsGroup` stays in place. A volume that refuses `chown` (NFS with `root_squash`) logs a warning instead; set `runAsUser: 1000` then. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`.
|
||||
- Use `extraVolumes` and `extraVolumeMounts` to add your own volumes to the pod. To give the booking import more KItinerary extractors, mount a ConfigMap at `/usr/local/share/kitinerary/extractors`, with one `.json` and one `.js` key for each extractor; see the example in `values.yaml`.
|
||||
- Use `extraObjects` to render further Kubernetes objects next to the chart's own, for example a backup `CronJob`. Each item is a map or a string of YAML, and `{{ }}` in it is evaluated, so `{{ .Release.Name }}` works. A backup job should copy TREK's own backups from `backups/` on the data volume and mount it read only, since that volume also holds the encryption key. The archives carry `.encryption_key` too unless `ENCRYPTION_KEY` is set, so protect the copy's destination like the data volume.
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{{- range .Values.extraObjects }}
|
||||
---
|
||||
{{- if kindIs "string" . }}
|
||||
{{ tpl . $ }}
|
||||
{{- else }}
|
||||
{{ tpl (toYaml .) $ }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -338,6 +338,29 @@ extraVolumes: []
|
||||
# readOnly: true
|
||||
extraVolumeMounts: []
|
||||
|
||||
# Further Kubernetes objects the chart renders next to its own, for example a Job, a
|
||||
# CronJob or a ConfigMap. Each item is rendered as written, either as a map or as a
|
||||
# string of YAML, and {{ }} in it is evaluated, so {{ include "trek.fullname" . }} or
|
||||
# {{ .Release.Name }} work, in both forms. Write literal braces as {{ "{{" }}.
|
||||
# A backup job must only read the data volume: it also holds the encryption key and the
|
||||
# server's secrets, and a second writer corrupts travel.db. Rather than copying the live
|
||||
# travel.db, copy TREK's own backups (Admin, Backup, automatic backups) from backups/ in
|
||||
# that volume. Those archives carry .encryption_key too (unless ENCRYPTION_KEY is set),
|
||||
# so protect the job's destination like the data volume itself.
|
||||
# extraObjects:
|
||||
# - apiVersion: v1
|
||||
# kind: ConfigMap
|
||||
# metadata:
|
||||
# name: '{{ include "trek.fullname" . }}-extra'
|
||||
# data:
|
||||
# note: hello
|
||||
# - |
|
||||
# apiVersion: v1
|
||||
# kind: ConfigMap
|
||||
# metadata:
|
||||
# name: {{ .Release.Name }}-notes
|
||||
extraObjects: []
|
||||
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.util.TypedValue;
|
||||
@@ -11,11 +14,13 @@ import android.view.Menu;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.webkit.CookieManager;
|
||||
import android.webkit.WebView;
|
||||
import android.widget.Button;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
import com.getcapacitor.WebViewListener;
|
||||
import com.liketrek.trek.screen.TrekKeyCommands;
|
||||
import com.liketrek.trek.tiles.TrekTileStore;
|
||||
import com.liketrek.trek.widget.TrekWidgetUpdater;
|
||||
@@ -26,6 +31,9 @@ public class MainActivity extends BridgeActivity {
|
||||
/** The share sheet (share/ShareActivity.kt) left an item for the import. */
|
||||
public static final String ACTION_SHARE_HANDOFF = "com.liketrek.trek.SHARE_HANDOFF";
|
||||
|
||||
/** The page colour of the address screen (native-shell/shell.css --page). */
|
||||
private static final int SHELL_PAGE = 0xFFFFFAF5;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
registerPlugin(TrekShellPlugin.class);
|
||||
@@ -57,6 +65,33 @@ public class MainActivity extends BridgeActivity {
|
||||
// and Chrome honours that, but the WebView draws the stretch on its root
|
||||
// scroller natively. It scales the whole view, top bar and bottom dock included.
|
||||
bridge.getWebView().setOverScrollMode(View.OVER_SCROLL_NEVER);
|
||||
// The address screen, and the step from it to the server just picked:
|
||||
// the warm ground of the first screens behind everything, so the
|
||||
// restart and the page's first frames do not flash white. The window's
|
||||
// colour is also what an older WebView shows under the status bar,
|
||||
// where it lays the page out between the bars (native/appBoot.ts).
|
||||
if (!onServer || restarting) {
|
||||
Drawable windowBackground = getWindow().getDecorView().getBackground();
|
||||
// A new drawable: setBackgroundColor would recolour the theme's own one,
|
||||
// and the restore below would hand the window the warm ground back.
|
||||
getWindow().getDecorView().setBackground(new ColorDrawable(SHELL_PAGE));
|
||||
bridge.getWebView().setBackgroundColor(SHELL_PAGE);
|
||||
// Once the server's page is up, the window is the one a normal launch
|
||||
// has, so the status bar of an older WebView follows the system again.
|
||||
if (onServer) {
|
||||
bridge.addWebViewListener(new WebViewListener() {
|
||||
private boolean restored;
|
||||
|
||||
@Override
|
||||
public void onPageLoaded(WebView webView) {
|
||||
if (restored) return;
|
||||
restored = true;
|
||||
getWindow().getDecorView().setBackground(windowBackground);
|
||||
webView.setBackgroundColor(Color.WHITE);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
// Set before any WebView callback can run: they are posted to this thread.
|
||||
if (onServer) {
|
||||
bridge.setWebViewClient(
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import { devices, expect, test, type Locator, type Page } from '@playwright/test';
|
||||
import { encodePolyline6 } from '@trek/shared';
|
||||
|
||||
async function createTourTrip(page: Page): Promise<number> {
|
||||
const trip = await page.request.post('/api/trips', {
|
||||
data: { title: 'Tour type picker', start_date: '2099-06-01', end_date: '2099-06-05' },
|
||||
});
|
||||
await expect(trip).toBeOK();
|
||||
const {
|
||||
trip: { id },
|
||||
} = await trip.json();
|
||||
await expect(await page.request.put(`/api/trips/${id}/addons/tours`, { data: { enabled: true } })).toBeOK();
|
||||
return id;
|
||||
}
|
||||
|
||||
async function expectInside(element: Locator, boundary: Locator) {
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const target = await element.boundingBox();
|
||||
const rail = await boundary.boundingBox();
|
||||
return (
|
||||
!!target &&
|
||||
!!rail &&
|
||||
target.x >= rail.x - 1 &&
|
||||
target.y >= rail.y - 1 &&
|
||||
target.x + target.width <= rail.x + rail.width + 1 &&
|
||||
target.y + target.height <= rail.y + rail.height + 1
|
||||
);
|
||||
})
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
function editorFields(page: Page) {
|
||||
const trigger = page.getByTestId('tour-type-select');
|
||||
const scrollArea = page.getByTestId('tour-planner-editor-scroll');
|
||||
return { trigger, scrollArea, menu: page.getByRole('group', { name: 'Tour type', exact: true }) };
|
||||
}
|
||||
|
||||
test('Tour type follows and fits inside the narrow editor rail', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1024, height: 480 });
|
||||
const tripId = await createTourTrip(page);
|
||||
await page.goto(`/trips/${tripId}?tab=tour-planner`);
|
||||
await page.getByRole('button', { name: 'Plan new tour' }).click();
|
||||
await expect(page.getByTestId('tour-planner-empty-state')).toBeAttached();
|
||||
|
||||
const grip = page.locator('[data-resize="left"]');
|
||||
for (let step = 0; step < 8; step++) await grip.press('ArrowLeft');
|
||||
const { trigger, scrollArea, menu } = editorFields(page);
|
||||
await trigger.scrollIntoViewIfNeeded();
|
||||
await expectInside(trigger, scrollArea);
|
||||
await trigger.click();
|
||||
await expectInside(menu, scrollArea);
|
||||
await expect.poll(() => menu.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
|
||||
|
||||
async function anchorGap() {
|
||||
return menu.evaluate((el) => {
|
||||
const anchor = document.querySelector('[data-testid="tour-type-select"]')!.getBoundingClientRect();
|
||||
const panel = el.getBoundingClientRect();
|
||||
return Math.round(Math.max(panel.top - anchor.bottom, anchor.top - panel.bottom));
|
||||
});
|
||||
}
|
||||
await expect.poll(anchorGap).toBe(4);
|
||||
const start = await scrollArea.evaluate((el) => el.scrollTop);
|
||||
await scrollArea.evaluate((el) => el.scrollBy(0, 20));
|
||||
await expect.poll(() => scrollArea.evaluate((el) => el.scrollTop)).toBeGreaterThan(start);
|
||||
await expect.poll(anchorGap).toBe(4);
|
||||
await expectInside(menu, scrollArea);
|
||||
await scrollArea.evaluate((el, top) => {
|
||||
el.scrollTop = top;
|
||||
}, start);
|
||||
await expect.poll(anchorGap).toBe(4);
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(trigger).toBeFocused();
|
||||
await expect(menu).toHaveCount(0);
|
||||
|
||||
await trigger.click();
|
||||
await scrollArea.evaluate((el) => el.scrollBy(0, 180));
|
||||
await expect(trigger).toHaveAttribute('aria-expanded', 'false');
|
||||
await expect(menu).toHaveCount(0);
|
||||
await scrollArea.evaluate((el) => {
|
||||
el.scrollTop = 0;
|
||||
});
|
||||
await expect(menu).toHaveCount(0);
|
||||
|
||||
await trigger.click();
|
||||
const ski = menu.getByTestId('tour-type-option-ski');
|
||||
await page.keyboard.press('End');
|
||||
await expect(ski).toBeInViewport();
|
||||
await expect(ski).toBeFocused();
|
||||
await page.keyboard.press('Enter');
|
||||
await expect(trigger).toContainText('Ski & winter');
|
||||
await expect(menu).toHaveCount(0);
|
||||
await page.getByRole('button', { name: 'Alpine', exact: true }).click();
|
||||
const hardest = page.getByRole('button', { name: 'Hardest runs', exact: true });
|
||||
const hardestMenu = page.getByRole('group', { name: 'Hardest runs', exact: true });
|
||||
await hardest.click();
|
||||
await expectInside(hardestMenu, scrollArea);
|
||||
await hardestMenu.getByRole('button', { name: 'Easy', exact: true }).click();
|
||||
await expect(hardest).toContainText('Easy');
|
||||
await expect(hardestMenu).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('the saved hike difficulty dropdown fits above the field and keeps alpine confirmation', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1024, height: 520 });
|
||||
const tripId = await createTourTrip(page);
|
||||
const saved = await page.request.post(`/api/trips/${tripId}/tours`, {
|
||||
data: {
|
||||
name: 'Saved ridge walk',
|
||||
tour_type: 'hike',
|
||||
max_hiking_difficulty: 2,
|
||||
route_geometry: [
|
||||
[48.1, 11.1, 500],
|
||||
[48.11, 11.11, 550],
|
||||
],
|
||||
waypoints: [
|
||||
{ lat: 48.1, lng: 11.1, role: 'start', sequence: 0 },
|
||||
{ lat: 48.11, lng: 11.11, role: 'end', sequence: 1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
await expect(saved).toBeOK();
|
||||
const {
|
||||
tour: { place_id },
|
||||
} = await saved.json();
|
||||
const detailUrl = `**/api/trips/${tripId}/tours/${place_id}`;
|
||||
const detailGate = Promise.withResolvers<void>();
|
||||
await page.route(
|
||||
detailUrl,
|
||||
async (route) => {
|
||||
await detailGate.promise;
|
||||
await route.continue();
|
||||
},
|
||||
{ times: 1 }
|
||||
);
|
||||
const shape = encodePolyline6([
|
||||
{ lat: 48.1, lon: 11.1 },
|
||||
{ lat: 48.11, lon: 11.11 },
|
||||
]);
|
||||
await page.route('**/api/routing/valhalla/route', (route) =>
|
||||
route.fulfill({
|
||||
json: { trip: { legs: [{ shape, summary: { length: 1.4, time: 1200 } }] } },
|
||||
})
|
||||
);
|
||||
await page.goto(`/trips/${tripId}?tab=tour-planner`);
|
||||
const detailRequested = page.waitForRequest(detailUrl);
|
||||
await page.getByRole('option', { name: /Saved ridge walk/ }).click();
|
||||
await detailRequested;
|
||||
|
||||
const { trigger, menu, scrollArea } = editorFields(page);
|
||||
try {
|
||||
await expect(trigger).toHaveCount(0);
|
||||
await expect(menu).toHaveCount(0);
|
||||
} finally {
|
||||
detailGate.resolve();
|
||||
}
|
||||
await expect(page.getByLabel('Tour name')).toHaveValue('Saved ridge walk');
|
||||
await trigger.click();
|
||||
await expectInside(menu, scrollArea);
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true });
|
||||
const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true });
|
||||
await difficulty.scrollIntoViewIfNeeded();
|
||||
await difficulty.click();
|
||||
await expectInside(difficultyMenu, scrollArea);
|
||||
await expect(difficultyMenu).toHaveCSS('transform-origin', /px [1-9][0-9.]*px$/);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(difficulty).toBeFocused();
|
||||
await expect(difficultyMenu).toHaveCount(0);
|
||||
await difficulty.click();
|
||||
await scrollArea.evaluate((el) => {
|
||||
el.scrollTop = 0;
|
||||
});
|
||||
await expect(difficulty).toHaveAttribute('aria-expanded', 'false');
|
||||
await expect(difficultyMenu).toHaveCount(0);
|
||||
|
||||
await difficulty.click();
|
||||
await difficultyMenu.getByRole('button', { name: 'T3: Demanding mountain hiking' }).click();
|
||||
await expect(difficulty).toContainText('T3:');
|
||||
await difficulty.click();
|
||||
await difficultyMenu.getByRole('button', { name: 'T4: Alpine hiking' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Enable alpine routing?' })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Cancel' }).click();
|
||||
await expect(difficulty).toContainText('T3:');
|
||||
|
||||
const categories = page.getByTestId('tour-poi-categories');
|
||||
await categories.click();
|
||||
await expectInside(page.getByRole('group', { name: 'What to look for', exact: true }), scrollArea);
|
||||
});
|
||||
|
||||
test('the tour editor dropdowns fit in the native tablet layout', async ({ playwright, baseURL, storageState }) => {
|
||||
const browser = await playwright.webkit.launch();
|
||||
try {
|
||||
const page = await browser.newPage({
|
||||
...devices['iPad Pro 11'],
|
||||
viewport: { width: 680, height: 620 },
|
||||
baseURL,
|
||||
storageState,
|
||||
});
|
||||
page.setDefaultTimeout(10_000);
|
||||
// The browser supplies the WebKit viewport and touch input. This flag selects the app shell.
|
||||
await page.addInitScript(() => Object.assign(window, { CapacitorCustomPlatform: { name: 'ios' } }));
|
||||
const tripId = await createTourTrip(page);
|
||||
await page.goto(`/trips/${tripId}?tab=tour-planner`);
|
||||
await page.getByRole('tab', { name: 'Plan a tour', exact: true }).tap();
|
||||
await page.getByRole('button', { name: 'Plan new tour' }).tap();
|
||||
const { trigger, menu, scrollArea } = editorFields(page);
|
||||
await trigger.tap();
|
||||
await expectInside(menu, scrollArea);
|
||||
await scrollArea.evaluate((el) => el.scrollBy(0, 160));
|
||||
await expect(trigger).toHaveAttribute('aria-expanded', 'false');
|
||||
|
||||
const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true });
|
||||
const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true });
|
||||
await difficulty.tap();
|
||||
await expectInside(difficultyMenu, scrollArea);
|
||||
await difficultyMenu.getByRole('button', { name: 'T1: Hiking' }).tap();
|
||||
await expect(difficulty).toContainText('T1:');
|
||||
await expect(difficultyMenu).toHaveCount(0);
|
||||
|
||||
await trigger.tap();
|
||||
await menu.getByTestId('tour-type-option-ski').tap();
|
||||
await page.getByRole('button', { name: 'Alpine', exact: true }).tap();
|
||||
const hardest = page.getByRole('button', { name: 'Hardest runs', exact: true });
|
||||
const hardestMenu = page.getByRole('group', { name: 'Hardest runs', exact: true });
|
||||
await hardest.tap();
|
||||
await expectInside(hardestMenu, scrollArea);
|
||||
await hardestMenu.getByRole('button', { name: 'Easy', exact: true }).tap();
|
||||
await expect(hardest).toContainText('Easy');
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { SplashScreen } from '@capacitor/splash-screen';
|
||||
import { StatusBar, Style } from '@capacitor/status-bar';
|
||||
import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../shared/src/auth/password-policy';
|
||||
import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape
|
||||
import { pageUnderStatusBar } from '../src/native/appBoot';
|
||||
import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
|
||||
import { opensSoon, refundedBeforeOpening } from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap';
|
||||
@@ -1705,7 +1706,9 @@ function showUnreachable(server: string, cert?: ClientCertDemand, failure?: stri
|
||||
*/
|
||||
async function paintStatusBar(): Promise<void> {
|
||||
try {
|
||||
await StatusBar.setStyle({ style: Style.Dark });
|
||||
// Below the bar on an older Android WebView the page stops, and the bar
|
||||
// stands on the window's light colour instead: dark icons there.
|
||||
await StatusBar.setStyle({ style: pageUnderStatusBar() ? Style.Dark : Style.Light });
|
||||
if (wideLayout.matches) await StatusBar.hide();
|
||||
else await StatusBar.show();
|
||||
} catch {
|
||||
|
||||
@@ -204,11 +204,32 @@
|
||||
--sea: #cfe3ef;
|
||||
--text-face: 'Plus Jakarta Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
--display-face: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
/* The insets of the device, from the web view or, on iOS, from the native side. */
|
||||
--safe-top: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
|
||||
--safe-bottom: max(env(safe-area-inset-bottom, 0px), var(--trek-native-safe-bottom, 0px));
|
||||
--safe-start: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
|
||||
--safe-end: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
|
||||
/* The insets of the device, from the web view or from the native side. On
|
||||
* Android a web view can report env() as 0 while the page reaches under the
|
||||
* status and navigation bars; Capacitor's SystemBars writes the real insets
|
||||
* to --safe-area-inset-* instead (0 where it lays the web view out between
|
||||
* the bars). iOS measures its own (TrekBridgeViewController publishSafeArea).
|
||||
* In a browser the variables are unset: env() alone. */
|
||||
--safe-top: max(
|
||||
env(safe-area-inset-top, 0px),
|
||||
var(--safe-area-inset-top, 0px),
|
||||
var(--trek-native-safe-top, 0px)
|
||||
);
|
||||
--safe-bottom: max(
|
||||
env(safe-area-inset-bottom, 0px),
|
||||
var(--safe-area-inset-bottom, 0px),
|
||||
var(--trek-native-safe-bottom, 0px)
|
||||
);
|
||||
--safe-start: max(
|
||||
env(safe-area-inset-left, 0px),
|
||||
var(--safe-area-inset-left, 0px),
|
||||
var(--trek-native-safe-left, 0px)
|
||||
);
|
||||
--safe-end: max(
|
||||
env(safe-area-inset-right, 0px),
|
||||
var(--safe-area-inset-right, 0px),
|
||||
var(--trek-native-safe-right, 0px)
|
||||
);
|
||||
color-scheme: light;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
+3
-3
@@ -118,7 +118,7 @@
|
||||
"plyr": "^3.8.5",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-dropzone": "^14.4.1",
|
||||
"react-dropzone": "^20.2.1",
|
||||
"react-leaflet": "^5.0.0",
|
||||
"react-leaflet-cluster": "^4.1.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
@@ -141,7 +141,7 @@
|
||||
"@testing-library/user-event": "^14.6.13",
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
||||
"@types/leaflet": "^1.9.22",
|
||||
"@types/node": "^25.9.8",
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
@@ -154,7 +154,7 @@
|
||||
"eslint-plugin-react-refresh": "^0.5.8",
|
||||
"fake-indexeddb": "^6.2.7",
|
||||
"jsdom": "^29.1.1",
|
||||
"msw": "^2.15.0",
|
||||
"msw": "^3.0.8",
|
||||
"postcss": "^8.5.33",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
|
||||
@@ -12,6 +12,16 @@
|
||||
(function () {
|
||||
try {
|
||||
var raw = localStorage.getItem('trek_appearance');
|
||||
// Inside the iOS and Android app, before anyone signed in on this server
|
||||
// from here: the page carries on the address screen's colour until the
|
||||
// sign-in screen is up (native/appBoot.ts), instead of flashing white.
|
||||
// The app's bridge is in place before this script runs.
|
||||
var w = window;
|
||||
var inApp = !!(w.androidBridge || (w.webkit && w.webkit.messageHandlers && w.webkit.messageHandlers.bridge));
|
||||
if (inApp && !raw) {
|
||||
document.documentElement.setAttribute('data-app-boot', '');
|
||||
document.documentElement.style.backgroundColor = '#fffaf5';
|
||||
}
|
||||
if (!raw) return;
|
||||
var s = JSON.parse(raw);
|
||||
if (!s || s.v !== 1) return;
|
||||
|
||||
@@ -8,14 +8,14 @@
|
||||
"trek/no-swallowed-catch": 126,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 66,
|
||||
"react-hooks/refs": 534,
|
||||
"react-hooks/refs": 533,
|
||||
"react-hooks/set-state-in-effect": 189,
|
||||
"@typescript-eslint/no-floating-promises": 162,
|
||||
"react-hooks/exhaustive-deps": 113,
|
||||
"@typescript-eslint/no-unused-vars": 117,
|
||||
"react-hooks/immutability": 28,
|
||||
"max-lines-per-function": 127,
|
||||
"react-hooks/static-components": 50,
|
||||
"react-hooks/static-components": 38,
|
||||
"react-hooks/preserve-manual-memoization": 12,
|
||||
"no-useless-assignment": 7,
|
||||
"no-empty": 19,
|
||||
|
||||
@@ -2121,7 +2121,6 @@
|
||||
"tests/unit/sync/tripSyncManager.test.ts",
|
||||
"tests/unit/tripStore.test.ts",
|
||||
"tests/unit/utils/cleanAmount.test.ts",
|
||||
"tests/unit/utils/fileDownload.test.ts",
|
||||
"tests/unit/utils/formatters.test.ts",
|
||||
"tests/unit/utils/placeFiles.test.ts",
|
||||
"tests/unit/utils/shellGuard.test.ts",
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"src/components/Map/MapView.tsx": 1200,
|
||||
"src/components/Map/MapViewGL.test.tsx": 2919,
|
||||
"src/components/Map/MapViewGL.tsx": 2116,
|
||||
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
|
||||
"src/components/Planner/DayDetailPanel.test.tsx": 2332,
|
||||
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 2908,
|
||||
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
|
||||
@@ -17,9 +17,9 @@
|
||||
"src/components/Studio/countryShapes.ts": 2595,
|
||||
"src/index.css": 1636,
|
||||
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
|
||||
"src/pages/JourneyDetailPage.test.tsx": 4028,
|
||||
"src/pages/LoginPage.tsx": 1294,
|
||||
"src/pages/TripPlannerPage.tsx": 1128,
|
||||
"src/pages/JourneyDetailPage.test.tsx": 3886,
|
||||
"src/pages/LoginPage.tsx": 1273,
|
||||
"src/pages/TripPlannerPage.tsx": 1127,
|
||||
"src/pages/atlas/useAtlas.ts": 1207,
|
||||
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
|
||||
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
|
||||
|
||||
@@ -45,7 +45,7 @@
|
||||
"components/Journey/JourneyMapGL.tsx": 5,
|
||||
"components/Journey/MobileEntryView.tsx": 94,
|
||||
"components/Journey/MobileMapTimeline.tsx": 8,
|
||||
"components/Journey/PhotoLightbox.tsx": 13,
|
||||
"components/Journey/PhotoLightbox.tsx": 11,
|
||||
"components/Journey/VideoPlayer.tsx": 2,
|
||||
"components/Journey/VideoPlayerLazy.tsx": 1,
|
||||
"components/Journey/journeyMapPopup.ts": 17,
|
||||
@@ -262,7 +262,7 @@
|
||||
"mobile/screens/trip/tabs/MCollabTab.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MCostsTab.tsx": 70,
|
||||
"mobile/screens/trip/tabs/MDocSyncSheet.tsx": 43,
|
||||
"mobile/screens/trip/tabs/MFileLightbox.tsx": 12,
|
||||
"mobile/screens/trip/tabs/MFileLightbox.tsx": 11,
|
||||
"mobile/screens/trip/tabs/MFileLinkSheet.tsx": 2,
|
||||
"mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4,
|
||||
|
||||
+28
-4
@@ -1,13 +1,14 @@
|
||||
import React from 'react'
|
||||
import { render, screen, waitFor, act } from '@testing-library/react'
|
||||
import { MemoryRouter, useLocation } from 'react-router'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, onTestFinished, vi } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { server } from '../tests/helpers/msw/server'
|
||||
import { useAuthStore } from './store/authStore'
|
||||
import { useSettingsStore } from './store/settingsStore'
|
||||
import { resetAllStores } from '../tests/helpers/store'
|
||||
import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories'
|
||||
import { locationAt } from '../tests/helpers/location'
|
||||
import { offlineDb } from './db/offlineDb'
|
||||
import { SETTINGS_WAIT_MS } from './utils/startDestination'
|
||||
import App from './App'
|
||||
@@ -185,9 +186,29 @@ describe('RootRedirect — startup destination', () => {
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({ isLoaded: false })
|
||||
stubActiveTrip({ id: 42, title: 'Japan' })
|
||||
// App asks for the settings on its own as soon as the user is signed in.
|
||||
// Held until the redirect is decided, or whichever answer lands first wins
|
||||
// and the test proves nothing about the mirror; released here, so it cannot
|
||||
// land in the next test either.
|
||||
let releaseSettings = () => {}
|
||||
const settingsHeld = new Promise<void>((resolve) => { releaseSettings = resolve })
|
||||
onTestFinished(() => releaseSettings())
|
||||
server.use(
|
||||
http.get('/api/settings', async () => {
|
||||
await settingsHeld
|
||||
return HttpResponse.json({
|
||||
settings: buildSettings({ start_page: 'active_trip', start_trip_tab: 'finanzplan' }),
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
|
||||
expect(currentPath()).toBe('/trips/42?tab=finanzplan')
|
||||
expect(useSettingsStore.getState().isLoaded).toBe(false)
|
||||
|
||||
releaseSettings()
|
||||
await waitFor(() => expect(useSettingsStore.getState().isLoaded).toBe(true))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -532,7 +553,7 @@ describe('Version cache-busting', () => {
|
||||
const reload = vi.fn()
|
||||
Object.defineProperty(window, 'location', {
|
||||
writable: true,
|
||||
value: { ...window.location, reload },
|
||||
value: locationAt('/', { reload }),
|
||||
})
|
||||
|
||||
server.use(
|
||||
@@ -587,7 +608,7 @@ describe('Version cache-busting', () => {
|
||||
// and try to update.
|
||||
localStorage.setItem('trek_app_version', '2.9.9')
|
||||
const reload = vi.fn()
|
||||
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
|
||||
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
|
||||
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () =>
|
||||
@@ -609,7 +630,7 @@ describe('Version cache-busting', () => {
|
||||
// failure neither deletes anything nor reloads into the old worker's shell.
|
||||
localStorage.setItem('trek_app_version', '2.9.9')
|
||||
const reload = vi.fn()
|
||||
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
|
||||
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
|
||||
const cachesDelete = vi.fn().mockResolvedValue(true)
|
||||
const unregister = vi.fn().mockResolvedValue(true)
|
||||
vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete })
|
||||
@@ -685,6 +706,9 @@ describe('RootRedirect — preference not mirrored on this device', () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({ isLoaded: false })
|
||||
// No backend: the settings never arrive, so only the timeout can decide.
|
||||
// Answered, they would open the dashboard on their own and hide the wait.
|
||||
server.use(http.get('/api/settings', () => HttpResponse.error()))
|
||||
|
||||
renderApp('/')
|
||||
expect(screen.queryByText('Dashboard')).not.toBeInTheDocument()
|
||||
|
||||
+12
-1
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState, useRef, ReactNode, Suspense } from 'react'
|
||||
import React, { useEffect, useLayoutEffect, useState, useRef, ReactNode, Suspense } from 'react'
|
||||
import { Routes, Route, Navigate, useLocation, useNavigationType } from 'react-router'
|
||||
import { useAuthStore } from './store/authStore'
|
||||
import { useSettingsStore } from './store/settingsStore'
|
||||
@@ -17,6 +17,8 @@ import BackgroundTasksWidget from './components/BackgroundTasks/BackgroundTasksW
|
||||
import MobileShell from './mobile/MobileShell'
|
||||
import MRouteFallback from './mobile/components/MRouteFallback'
|
||||
import ErrorBoundary from './components/shared/ErrorBoundary'
|
||||
import AppBootScreen from './components/shared/AppBootScreen'
|
||||
import { endAppBoot, isAppBoot } from './native/appBoot'
|
||||
import { lazyWithRetry } from './utils/lazyWithRetry'
|
||||
import { reconcileAppVersion } from './utils/versionHandover'
|
||||
import { useServerVersionStore } from './store/serverVersionStore'
|
||||
@@ -113,6 +115,7 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
|
||||
const isPhone = useIsPhone()
|
||||
|
||||
if (isLoading) {
|
||||
if (isAppBoot()) return <AppBootScreen />
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
@@ -286,6 +289,7 @@ function RootRedirect() {
|
||||
}, [isLoading, isAuthenticated, settingsLoaded, settingsGaveUp, settings, target])
|
||||
|
||||
if (isLoading || (isAuthenticated && !target)) {
|
||||
if (isAppBoot()) return <AppBootScreen />
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50">
|
||||
<div className="w-10 h-10 border-4 border-slate-200 border-t-slate-900 rounded-full animate-spin"></div>
|
||||
@@ -306,6 +310,7 @@ function RouteFallback() {
|
||||
// on a phone the desktop spinner on bg-surface would be a foreign white sheet
|
||||
// in front of the mobile screen.
|
||||
const isPhone = useIsPhone()
|
||||
if (isAppBoot()) return <AppBootScreen />
|
||||
if (isPhone) return <MRouteFallback />
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-surface">
|
||||
@@ -398,6 +403,12 @@ export default function App() {
|
||||
const location = useLocation()
|
||||
const isSharedPage = location.pathname.startsWith('/shared/')
|
||||
|
||||
// Inside the app: the handover from its address screen ends once a signed-in
|
||||
// screen is up, before it paints, so it can rise in (native/appBoot.ts).
|
||||
useLayoutEffect(() => {
|
||||
if (isAuthenticated && location.pathname !== '/' && location.pathname !== '/login') endAppBoot()
|
||||
}, [isAuthenticated, location.pathname])
|
||||
|
||||
useEffect(() => {
|
||||
const run = () =>
|
||||
applyAppearance({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031
|
||||
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { delay, http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildAdmin } from '../../../tests/helpers/factories';
|
||||
@@ -341,12 +341,43 @@ describe('DefaultUserSettingsTab', () => {
|
||||
expect(input).toHaveValue('pk.old');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'pk.new');
|
||||
fireEvent.blur(input);
|
||||
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
|
||||
// would blur it a second time and race that save against the reset request
|
||||
await user.tab();
|
||||
expect(input).not.toHaveFocus();
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }]));
|
||||
|
||||
// Clicking the reset link also blurs the field again, so only the last PUT is checked
|
||||
await user.click(resetLink('Shared Mapbox token'));
|
||||
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ mapbox_access_token: null }));
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }, { mapbox_access_token: null }]));
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-032: a reset clicked while the save of the field is still out is the one that stays', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { state } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.old' });
|
||||
// The save is the slower request: sent at once, the reset would overtake it.
|
||||
const done: string[] = [];
|
||||
server.use(
|
||||
http.put('/api/admin/default-user-settings', async ({ request }) => {
|
||||
const body = await request.json() as Record<string, unknown>;
|
||||
if (body.mapbox_access_token !== null) await delay(100);
|
||||
if (body.mapbox_access_token === null) delete state.mapbox_access_token;
|
||||
else state.mapbox_access_token = body.mapbox_access_token;
|
||||
done.push(body.mapbox_access_token === null ? 'reset' : 'save');
|
||||
return HttpResponse.json({ ...state });
|
||||
}),
|
||||
);
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Shared Mapbox token');
|
||||
|
||||
const input = screen.getByPlaceholderText('pk.eyJ…');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'pk.new');
|
||||
// The click leaves the field, which saves it, and resets it right after.
|
||||
await user.click(resetLink('Shared Mapbox token'));
|
||||
|
||||
await waitFor(() => expect(done).toEqual(['save', 'reset']));
|
||||
expect(state.mapbox_access_token).toBeUndefined();
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
|
||||
});
|
||||
|
||||
@@ -449,12 +480,14 @@ describe('DefaultUserSettingsTab', () => {
|
||||
expect(input).toHaveValue('ck.old');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'ck.new');
|
||||
fireEvent.blur(input);
|
||||
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
|
||||
// would blur it a second time and race that save against the reset request
|
||||
await user.tab();
|
||||
expect(input).not.toHaveFocus();
|
||||
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }]));
|
||||
|
||||
// Clicking the reset link also blurs the field again, so only the last PUT is checked
|
||||
await user.click(resetLink('Shared CARTO key'));
|
||||
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ carto_api_key: null }));
|
||||
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }, { carto_api_key: null }]));
|
||||
await waitFor(() => expect(cartoInput()).toHaveValue(''));
|
||||
});
|
||||
|
||||
|
||||
@@ -11,6 +11,39 @@ import DevNotificationsPanel from './DevNotificationsPanel';
|
||||
|
||||
const ADMIN_USER = buildUser({ id: 1, username: 'testadmin', role: 'admin' });
|
||||
|
||||
/**
|
||||
* Renders the panel and waits until both lookups (trips and users) have landed, so a test
|
||||
* acts on the settled panel and no lookup answers after it has ended.
|
||||
*/
|
||||
async function renderSettled() {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await screen.findByText('User-Scoped Events');
|
||||
}
|
||||
|
||||
const LOOKUPS = ['/api/admin/users', '/api/trips'];
|
||||
|
||||
/**
|
||||
* Records the GET requests to `paths` that have been answered, for the tests whose lookups
|
||||
* come back empty or failed and so change nothing on screen to wait for. Call before render;
|
||||
* the returned function waits until exactly `paths` (a path once per expected request) ended.
|
||||
*/
|
||||
function trackRequests(paths: string[] = LOOKUPS) {
|
||||
const answered: string[] = [];
|
||||
const onEnd = ({ request }: { request: Request }) => {
|
||||
const { pathname } = new URL(request.url);
|
||||
if (request.method === 'GET' && paths.includes(pathname)) answered.push(pathname);
|
||||
};
|
||||
server.events.on('request:end', onEnd);
|
||||
return async () => {
|
||||
try {
|
||||
await waitFor(() => expect([...answered].sort()).toEqual([...paths].sort()));
|
||||
} finally {
|
||||
server.events.removeListener('request:end', onEnd);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { user: ADMIN_USER, isAuthenticated: true });
|
||||
@@ -21,9 +54,12 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('DevNotificationsPanel', () => {
|
||||
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', () => {
|
||||
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
expect(screen.getByText('DEV ONLY')).toBeInTheDocument();
|
||||
// Let the lookups the panel started land here, not in the next test
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await screen.findByText('User-Scoped Events');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-002: four section titles render after data loads', async () => {
|
||||
@@ -36,8 +72,7 @@ describe('DevNotificationsPanel', () => {
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-003: trip selector populated from API', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await renderSettled();
|
||||
const [tripSelect] = screen.getAllByRole('combobox');
|
||||
const options = Array.from(tripSelect.querySelectorAll('option'));
|
||||
const labels = options.map(o => o.textContent);
|
||||
@@ -46,8 +81,7 @@ describe('DevNotificationsPanel', () => {
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-004: user selector populated from API', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('User-Scoped Events');
|
||||
await renderSettled();
|
||||
const selects = screen.getAllByRole('combobox');
|
||||
// Second combobox is the user selector (first is trip selector)
|
||||
const userSelect = selects[1];
|
||||
@@ -66,8 +100,7 @@ describe('DevNotificationsPanel', () => {
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
await waitFor(() => expect(capturedBody).toBeDefined());
|
||||
expect(capturedBody).toMatchObject({
|
||||
@@ -75,6 +108,8 @@ describe('DevNotificationsPanel', () => {
|
||||
scope: 'user',
|
||||
targetId: ADMIN_USER.id,
|
||||
});
|
||||
// The send settles inside this test, so its toast cannot land in the next one
|
||||
await screen.findByText('Sent: simple-me');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-006: success toast shown after fire', async () => {
|
||||
@@ -84,30 +119,34 @@ describe('DevNotificationsPanel', () => {
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-007: all buttons disabled while a send is in-flight', async () => {
|
||||
// The send is held open until the assertion ran, then released, so it settles in this test
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
server.use(
|
||||
http.post('/api/admin/dev/test-notification', async () => {
|
||||
await new Promise(() => {}); // never resolves — simulates in-flight
|
||||
await gate;
|
||||
return HttpResponse.json({ ok: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
|
||||
// The request handler never resolves, so sending stays true after the click settles
|
||||
// The request handler is held, so sending stays true after the click settles
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
|
||||
await waitFor(() => {
|
||||
const buttons = screen.getAllByRole('button');
|
||||
buttons.forEach(btn => expect(btn).toBeDisabled());
|
||||
});
|
||||
|
||||
release();
|
||||
await screen.findByText('Sent: simple-me');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-008: the server error field is what the toast shows', async () => {
|
||||
@@ -117,8 +156,7 @@ describe('DevNotificationsPanel', () => {
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
expect(await screen.findByText('No channel configured')).toBeInTheDocument();
|
||||
});
|
||||
@@ -130,8 +168,7 @@ describe('DevNotificationsPanel', () => {
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
expect(await screen.findByText('Failed')).toBeInTheDocument();
|
||||
});
|
||||
@@ -145,8 +182,7 @@ describe('DevNotificationsPanel', () => {
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await renderSettled();
|
||||
|
||||
const [tripSelect] = screen.getAllByRole('combobox');
|
||||
const tokyoOption = Array.from(tripSelect.querySelectorAll('option')).find(
|
||||
@@ -159,15 +195,19 @@ describe('DevNotificationsPanel', () => {
|
||||
|
||||
await waitFor(() => expect(capturedBody).toBeDefined());
|
||||
expect(capturedBody!.targetId).toBe(tokyoId);
|
||||
// The send settles inside this test, so its toast cannot land in the next one
|
||||
await screen.findByText('Sent: booking_change');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-010: Trip-Scoped section absent when no trips', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips', () => HttpResponse.json({ trips: [] })),
|
||||
);
|
||||
const lookupsAnswered = trackRequests();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
// Wait for user data to confirm async effects have settled
|
||||
await screen.findByText('User-Scoped Events');
|
||||
await lookupsAnswered();
|
||||
expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -180,8 +220,7 @@ describe('DevNotificationsPanel', () => {
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
|
||||
await user.click(screen.getByText('Boolean → Me').closest('button')!);
|
||||
await screen.findByText('Sent: boolean-me');
|
||||
@@ -216,8 +255,7 @@ describe('DevNotificationsPanel', () => {
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await renderSettled();
|
||||
|
||||
const [tripSelect] = screen.getAllByRole('combobox');
|
||||
const tripId = Number((tripSelect as HTMLSelectElement).value);
|
||||
@@ -247,8 +285,7 @@ describe('DevNotificationsPanel', () => {
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('User-Scoped Events');
|
||||
await renderSettled();
|
||||
|
||||
const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;
|
||||
const aliceOption = Array.from(userSelect.querySelectorAll('option')).find(
|
||||
@@ -278,9 +315,11 @@ describe('DevNotificationsPanel', () => {
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-014: the User-Scoped section is hidden when no users come back', async () => {
|
||||
server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] })));
|
||||
const lookupsAnswered = trackRequests();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await lookupsAnswered();
|
||||
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -288,22 +327,38 @@ describe('DevNotificationsPanel', () => {
|
||||
server.use(
|
||||
http.get('/api/trips', () => HttpResponse.error()),
|
||||
http.get('/api/admin/users', () => HttpResponse.error()),
|
||||
// A network error makes the API client probe /api/health before it rejects; the server
|
||||
// is down here, so the probe fails too instead of going out to the real network
|
||||
http.get('/api/health', () => HttpResponse.error()),
|
||||
);
|
||||
const lookupsAnswered = trackRequests([...LOOKUPS, '/api/health', '/api/health']);
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
|
||||
expect(await screen.findByText('Type Testing')).toBeInTheDocument();
|
||||
await lookupsAnswered();
|
||||
await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument());
|
||||
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-016: a trigger takes its hover background from CSS, not inline styles', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
|
||||
const btn = screen.getByText('Simple → Me').closest('button')!;
|
||||
fireEvent.mouseEnter(btn);
|
||||
expect(btn.style.background).toBe('');
|
||||
expect(btn.className).toContain('hover:bg-surface-secondary');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-017: a send button stays the same element while the panel updates around it', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
const btn = screen.getByRole('button', { name: /Simple → Me/ });
|
||||
|
||||
// The lookups answer and re-render the panel.
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await screen.findByText('User-Scoped Events');
|
||||
|
||||
expect(btn.isConnected).toBe(true);
|
||||
expect(screen.getByRole('button', { name: /Simple → Me/ })).toBe(btn);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,20 +25,17 @@ function ButtonGrid({ children }: { children: React.ReactNode }): React.ReactEle
|
||||
return <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">{children}</div>
|
||||
}
|
||||
|
||||
export default function DevNotificationsPanel(): React.ReactElement {
|
||||
const ids = useId()
|
||||
const {
|
||||
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
|
||||
tripInviteId, vacayInviteId, send,
|
||||
} = useDevNotifications()
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
const Btn = ({
|
||||
id, label, sub, icon: Icon, onClick,
|
||||
}: {
|
||||
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void
|
||||
}) => (
|
||||
/**
|
||||
* One send button. Declared here, not inside the panel: a component made during
|
||||
* render is a new type on every render, so React would remount every button on
|
||||
* each state change and a click could land on one that is already gone.
|
||||
*/
|
||||
function Btn({
|
||||
id, label, sub, icon: Icon, onClick, sending,
|
||||
}: {
|
||||
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void; sending: string | null
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button type="button"
|
||||
onClick={onClick}
|
||||
disabled={sending !== null}
|
||||
@@ -54,6 +51,14 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
{sending === id && <Loader2 size={15} className="flex-none animate-spin text-content-faint" />}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export default function DevNotificationsPanel(): React.ReactElement {
|
||||
const ids = useId()
|
||||
const {
|
||||
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
|
||||
tripInviteId, vacayInviteId, send,
|
||||
} = useDevNotifications()
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -66,16 +71,16 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
badge={<StatusPill tone="warning">DEV ONLY</StatusPill>}
|
||||
>
|
||||
<ButtonGrid>
|
||||
<Btn id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
|
||||
<Btn sending={sending} id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
|
||||
onClick={send.simpleMe}
|
||||
/>
|
||||
<Btn id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
|
||||
<Btn sending={sending} id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
|
||||
onClick={send.booleanMe}
|
||||
/>
|
||||
<Btn id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
|
||||
<Btn sending={sending} id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
|
||||
onClick={send.navigateMe}
|
||||
/>
|
||||
<Btn id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
|
||||
<Btn sending={sending} id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
|
||||
onClick={send.simpleAdmins}
|
||||
/>
|
||||
</ButtonGrid>
|
||||
@@ -94,19 +99,19 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
</SelectBox>
|
||||
</EditorField>
|
||||
<ButtonGrid>
|
||||
<Btn id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
|
||||
<Btn sending={sending} id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
|
||||
onClick={send.bookingChange}
|
||||
/>
|
||||
<Btn id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
|
||||
<Btn sending={sending} id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
|
||||
onClick={send.tripReminder}
|
||||
/>
|
||||
<Btn id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
|
||||
<Btn sending={sending} id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
|
||||
onClick={send.photosShared}
|
||||
/>
|
||||
<Btn id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
|
||||
<Btn sending={sending} id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
|
||||
onClick={send.collabMessage}
|
||||
/>
|
||||
<Btn id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
|
||||
<Btn sending={sending} id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
|
||||
onClick={send.packingTagged}
|
||||
/>
|
||||
</ButtonGrid>
|
||||
@@ -127,6 +132,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
</EditorField>
|
||||
<ButtonGrid>
|
||||
<Btn
|
||||
sending={sending}
|
||||
id={tripInviteId}
|
||||
label="trip_invite"
|
||||
sub="navigate · user"
|
||||
@@ -134,6 +140,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
onClick={send.tripInvite}
|
||||
/>
|
||||
<Btn
|
||||
sending={sending}
|
||||
id={vacayInviteId}
|
||||
label="vacay_invite"
|
||||
sub="navigate · user"
|
||||
@@ -147,7 +154,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
{/* ── Admin-Scoped Events ──────────────────────────────────────────── */}
|
||||
<SettingsCard icon={ShieldCheck} title="Admin-Scoped Events" hint="Fires to all admin users.">
|
||||
<ButtonGrid>
|
||||
<Btn id="version_available" label="version_available" sub="navigate · admin" icon={Download}
|
||||
<Btn sending={sending} id="version_available" label="version_available" sub="navigate · admin" icon={Download}
|
||||
onClick={send.versionAvailable}
|
||||
/>
|
||||
</ButtonGrid>
|
||||
|
||||
@@ -137,19 +137,25 @@ describe('useDefaultUserSettings', () => {
|
||||
|
||||
act(() => result.current.pickTilePreset(''));
|
||||
act(() => result.current.pickStylePreset(''));
|
||||
// Writes go out in order, a microtask later: let any that was queued start first.
|
||||
await act(async () => {});
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
|
||||
act(() => result.current.pickTilePreset('https://tile.openstreetmap.de/{z}/{x}/{y}.png'));
|
||||
expect(result.current.mapTileUrl).toBe('https://tile.openstreetmap.de/{z}/{x}/{y}.png');
|
||||
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' });
|
||||
await waitFor(() =>
|
||||
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' })
|
||||
);
|
||||
|
||||
act(() => result.current.pickStylePreset('https://tiles.openfreemap.org/styles/positron'));
|
||||
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' });
|
||||
await waitFor(() =>
|
||||
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' })
|
||||
);
|
||||
|
||||
act(() => result.current.setMapboxStyle('mapbox://styles/not-for-maplibre'));
|
||||
act(() => result.current.commitStyle());
|
||||
expect(result.current.mapboxStyle).toBe(OPENFREEMAP_DEFAULT_STYLE);
|
||||
expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE });
|
||||
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE }));
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(3));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { adminApi } from '../../api/client';
|
||||
import { useWritesInOrder } from '../../hooks/useWritesInOrder';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
@@ -87,32 +88,38 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
|
||||
.catch(() => setLoaded(true));
|
||||
}, []);
|
||||
|
||||
const save = async (patch: Partial<Defaults>) => {
|
||||
try {
|
||||
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
|
||||
setDefaults(updated);
|
||||
toast.success(t('admin.defaultSettings.saved'));
|
||||
} catch (err: unknown) {
|
||||
toast.error(errorMessage(err, t('common.error')));
|
||||
}
|
||||
};
|
||||
// A field's save on blur and the reset clicked right after it reach the server in
|
||||
// that order, or the save landing last would store the old value again.
|
||||
const inOrder = useWritesInOrder();
|
||||
|
||||
const reset = async (key: keyof Defaults) => {
|
||||
try {
|
||||
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
|
||||
setDefaults(updated);
|
||||
if (key === 'map_tile_url') setMapTileUrl('');
|
||||
if (key === 'mapbox_access_token') setMapboxToken('');
|
||||
if (key === 'carto_api_key') setCartoKey('');
|
||||
if (key === 'mapbox_style' || key === 'maplibre_style') {
|
||||
const provider = normalizeProvider(defaults.map_provider);
|
||||
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
|
||||
const save = (patch: Partial<Defaults>) =>
|
||||
inOrder(async () => {
|
||||
try {
|
||||
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
|
||||
setDefaults(updated);
|
||||
toast.success(t('admin.defaultSettings.saved'));
|
||||
} catch (err: unknown) {
|
||||
toast.error(errorMessage(err, t('common.error')));
|
||||
}
|
||||
toast.success(t('admin.defaultSettings.reset'));
|
||||
} catch (err: unknown) {
|
||||
toast.error(errorMessage(err, t('common.error')));
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
const reset = (key: keyof Defaults) =>
|
||||
inOrder(async () => {
|
||||
try {
|
||||
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
|
||||
setDefaults(updated);
|
||||
if (key === 'map_tile_url') setMapTileUrl('');
|
||||
if (key === 'mapbox_access_token') setMapboxToken('');
|
||||
if (key === 'carto_api_key') setCartoKey('');
|
||||
if (key === 'mapbox_style' || key === 'maplibre_style') {
|
||||
const provider = normalizeProvider(defaults.map_provider);
|
||||
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
|
||||
}
|
||||
toast.success(t('admin.defaultSettings.reset'));
|
||||
} catch (err: unknown) {
|
||||
toast.error(errorMessage(err, t('common.error')));
|
||||
}
|
||||
});
|
||||
|
||||
const isSet = (key: keyof Defaults) => defaults[key] !== undefined;
|
||||
|
||||
|
||||
@@ -339,6 +339,8 @@ describe('CollectionPlaceDetail', () => {
|
||||
address: 'Somewhere',
|
||||
lat: 52.5,
|
||||
lng: 13.4,
|
||||
// No notes on this place, and none written (#3168).
|
||||
notes: null,
|
||||
});
|
||||
// Back in read mode.
|
||||
expect(await screen.findByRole('button', { name: 'Edit' })).toBeInTheDocument();
|
||||
|
||||
@@ -32,7 +32,7 @@ interface CollectionPlaceDetailProps {
|
||||
anchorRect?: { left: number; width: number } | null
|
||||
onClose: () => void
|
||||
onSetStatus: (status: CollectionStatus) => void
|
||||
onSave: (patch: { name?: string; description?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null; address?: string | null }) => Promise<void>
|
||||
onSave: (patch: { name?: string; description?: string | null; notes?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null; address?: string | null }) => Promise<void>
|
||||
/** Upload a custom cover image (#1136); enables the cover change/remove controls. */
|
||||
onUploadImage?: (file: File) => Promise<void>
|
||||
onCopyToTrip: () => void
|
||||
@@ -74,7 +74,7 @@ export default function CollectionPlaceDetail({
|
||||
const navigationTargets = getNavigationTargets(place)
|
||||
const descRef = useRef<HTMLTextAreaElement>(null)
|
||||
const {
|
||||
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, links, setLinks, setLink,
|
||||
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, notes, setNotes, links, setLinks, setLink,
|
||||
labelIds, toggleLabel, address, setAddress, lat, setLat, lng, setLng, saving, imgBusy, cover: banner, assignedLabels,
|
||||
handleImagePick: handleCoverPick, handleImageRemove, cancelEdit: resetForm, save,
|
||||
} = useCollectionPlaceForm({ place, labels, onSave, onUploadImage, t, normalizeLinkUrl, withCoordinates: true })
|
||||
@@ -226,6 +226,11 @@ export default function CollectionPlaceDetail({
|
||||
<MarkdownToolbar textareaRef={descRef} onUpdate={setDescription} />
|
||||
<textarea ref={descRef} value={description} onChange={e => setDescription(e.target.value)} rows={4} placeholder={t('collections.descriptionPlaceholder')} className="col-detail-textarea" />
|
||||
</div>
|
||||
{/* Notes: the traveller's own, apart from the description (#3168) */}
|
||||
<div className="col-detail-field">
|
||||
<div className="col-detail-label">{t('collections.notes')}</div>
|
||||
<textarea value={notes} onChange={e => setNotes(e.target.value)} rows={3} placeholder={t('collections.notesPlaceholder')} className="col-detail-textarea" />
|
||||
</div>
|
||||
{/* Links */}
|
||||
<div className="col-detail-field">
|
||||
<div className="col-detail-label">{t('collections.links')}</div>
|
||||
@@ -248,6 +253,12 @@ export default function CollectionPlaceDetail({
|
||||
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{place.description}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
{place.notes?.trim() && (
|
||||
<div className="col-detail-field">
|
||||
<div className="col-detail-label">{t('collections.notes')}</div>
|
||||
<p className="m-0 whitespace-pre-wrap text-body text-content-muted [overflow-wrap:anywhere]">{place.notes}</p>
|
||||
</div>
|
||||
)}
|
||||
{place.links && place.links.length > 0 && (
|
||||
<div className="col-detail-links">
|
||||
{place.links.map((l, i) => (
|
||||
|
||||
@@ -176,6 +176,7 @@ describe('useCollectionPlaceForm', () => {
|
||||
expect(detail.props.onSave).toHaveBeenCalledWith({
|
||||
name: 'Louvre',
|
||||
description: 'Museum',
|
||||
notes: null,
|
||||
links: [{ label: 'Map', url: 'https://maps.example' }],
|
||||
category_id: 3,
|
||||
label_ids: [11],
|
||||
@@ -192,6 +193,7 @@ describe('useCollectionPlaceForm', () => {
|
||||
expect(sheet.props.onSave).toHaveBeenCalledWith({
|
||||
name: 'Louvre',
|
||||
description: 'Museum',
|
||||
notes: null,
|
||||
links: [{ label: 'Site', url: 'https://louvre.example' }],
|
||||
category_id: 3,
|
||||
label_ids: [10],
|
||||
@@ -199,6 +201,25 @@ describe('useCollectionPlaceForm', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-COMP-COLPLACEHOOK-014: seeds, edits and saves the own notes on a saved place (#3168)', async () => {
|
||||
const sheet = setup({ place: place({ notes: 'Book a week ahead' }) });
|
||||
expect(sheet.result.current.notes).toBe('Book a week ahead');
|
||||
act(() => {
|
||||
sheet.result.current.setEditing(true);
|
||||
sheet.result.current.setNotes(' Closed on Tuesdays ');
|
||||
});
|
||||
await act(async () => {
|
||||
await sheet.result.current.save();
|
||||
});
|
||||
expect(sheet.props.onSave).toHaveBeenCalledWith(expect.objectContaining({ notes: 'Closed on Tuesdays' }));
|
||||
|
||||
act(() => sheet.result.current.setNotes(' '));
|
||||
await act(async () => {
|
||||
await sheet.result.current.save();
|
||||
});
|
||||
expect(sheet.props.onSave).toHaveBeenLastCalledWith(expect.objectContaining({ notes: null }));
|
||||
});
|
||||
|
||||
it('FE-COMP-COLPLACEHOOK-010: a failed save stays in edit mode and toasts', async () => {
|
||||
const onSave = vi.fn().mockRejectedValue({ response: { data: { error: 'Locked' } } });
|
||||
const { result } = setup({ onSave });
|
||||
|
||||
@@ -12,6 +12,7 @@ import { cleanListLinks } from './useListEditor';
|
||||
export interface CollectionPlacePatch {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
notes?: string | null;
|
||||
links?: CollectionLink[];
|
||||
category_id?: number | null;
|
||||
label_ids?: number[];
|
||||
@@ -84,6 +85,8 @@ export function useCollectionPlaceForm({
|
||||
const [name, setName] = useState(shown?.name ?? '');
|
||||
const [categoryId, setCategoryId] = useState<number | null>(shown?.category_id ?? null);
|
||||
const [description, setDescription] = useState(shown?.description ?? '');
|
||||
// The traveller's own notes on the place (#3168), apart from its description.
|
||||
const [notes, setNotes] = useState(shown?.notes ?? '');
|
||||
const [links, setLinks] = useState<CollectionLink[]>(shown?.links ?? []);
|
||||
const [labelIds, setLabelIds] = useState<number[]>(shown?.label_ids ?? []);
|
||||
const [address, setAddress] = useState(shown?.address ?? '');
|
||||
@@ -101,6 +104,7 @@ export function useCollectionPlaceForm({
|
||||
setName(p.name);
|
||||
setCategoryId(p.category_id ?? null);
|
||||
setDescription(p.description ?? '');
|
||||
setNotes(p.notes ?? '');
|
||||
setLinks(p.links ?? []);
|
||||
setLabelIds(p.label_ids ?? []);
|
||||
setAddress(p.address ?? '');
|
||||
@@ -189,6 +193,7 @@ export function useCollectionPlaceForm({
|
||||
const base = {
|
||||
name: name.trim() || shown.name,
|
||||
description: description.trim() || null,
|
||||
notes: notes.trim() || null,
|
||||
links: cleanListLinks(links, normalizeLinkUrl),
|
||||
category_id: categoryId,
|
||||
label_ids: labelIds,
|
||||
@@ -215,6 +220,8 @@ export function useCollectionPlaceForm({
|
||||
setCategoryId,
|
||||
description,
|
||||
setDescription,
|
||||
notes,
|
||||
setNotes,
|
||||
links,
|
||||
setLinks,
|
||||
setLink,
|
||||
|
||||
@@ -526,6 +526,24 @@ describe('FileManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-COMP-FILEMANAGER-039: a file pasted while the drop zone has focus is uploaded once', async () => {
|
||||
const onUpload = vi.fn().mockResolvedValue({ file: { id: 56 } });
|
||||
render(<FileManager {...defaultProps} onUpload={onUpload} />);
|
||||
|
||||
const zone = document.querySelector('[role="presentation"]') as HTMLElement;
|
||||
const file = new File(['data'], 'pasted.png', { type: 'image/png' });
|
||||
const pasteEvent = new Event('paste', { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(pasteEvent, 'clipboardData', {
|
||||
value: { types: ['Files'], files: [file], items: [{ kind: 'file', type: 'image/png', getAsFile: () => file }] },
|
||||
});
|
||||
|
||||
await fireEvent(zone, pasteEvent);
|
||||
|
||||
await waitFor(() => expect(onUpload).toHaveBeenCalled());
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
expect(onUpload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-FILEMANAGER-028: upload with places open assign modal after upload', async () => {
|
||||
const { buildPlace } = await import('../../../tests/helpers/factories');
|
||||
const place = buildPlace({ id: 10, name: 'Sagrada Familia' });
|
||||
|
||||
@@ -124,7 +124,9 @@ export function useFileManager({ files = [], onUpload, onDelete, onUpdate, place
|
||||
toast.error(t('files.uploadErrorSize', { max: maxUploadMb }))
|
||||
}
|
||||
},
|
||||
noClick: false,
|
||||
// Pasting is handled once for the whole panel (handlePaste), with the upload
|
||||
// permission check; the zone's own paste upload would send each file twice.
|
||||
noPaste: true,
|
||||
})
|
||||
|
||||
const handlePaste = useCallback((e: React.ClipboardEvent) => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-029
|
||||
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-030
|
||||
|
||||
// Plyr needs a real media pipeline, so the player is stubbed here.
|
||||
vi.mock('./VideoPlayer', () => ({
|
||||
@@ -87,9 +87,9 @@ describe('PhotoLightbox', () => {
|
||||
|
||||
it('FE-COMP-LIGHTBOX-007: does not render when photos array is empty', () => {
|
||||
const onClose = vi.fn();
|
||||
const { container } = render(<PhotoLightbox photos={[]} onClose={onClose} />);
|
||||
render(<PhotoLightbox photos={[]} onClose={onClose} />);
|
||||
// Component returns null when photo is undefined (empty array, index 0 is undefined)
|
||||
expect(container.querySelector('img')).not.toBeInTheDocument();
|
||||
expect(document.querySelector('img')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-008: calls onClose when close button clicked', () => {
|
||||
@@ -100,10 +100,10 @@ describe('PhotoLightbox', () => {
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-009: opens at the requested start index', () => {
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={2} onClose={vi.fn()} />);
|
||||
render(<PhotoLightbox photos={samplePhotos} startIndex={2} onClose={vi.fn()} />);
|
||||
expect(screen.getByText('3 / 3')).toBeInTheDocument();
|
||||
// The third photo has no caption, so its img is presentational.
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', '/photos/3.jpg');
|
||||
expect(document.querySelector('img')).toHaveAttribute('src', '/photos/3.jpg');
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-010: only offers the arrows that lead somewhere', () => {
|
||||
@@ -162,8 +162,8 @@ describe('PhotoLightbox', () => {
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-015: swipes horizontally to move between photos', () => {
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
|
||||
fireEvent.touchStart(surface, { touches: [{ clientX: 200, clientY: 200 }] });
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 100, clientY: 210 }] });
|
||||
@@ -176,8 +176,8 @@ describe('PhotoLightbox', () => {
|
||||
|
||||
it('FE-COMP-LIGHTBOX-016: swipes down to close', () => {
|
||||
const onClose = vi.fn();
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
|
||||
fireEvent.touchStart(surface, { touches: [{ clientX: 200, clientY: 100 }] });
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 210, clientY: 300 }] });
|
||||
@@ -187,8 +187,8 @@ describe('PhotoLightbox', () => {
|
||||
|
||||
it('FE-COMP-LIGHTBOX-017: ignores a touch end without a matching touch start', () => {
|
||||
const onClose = vi.fn();
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 210, clientY: 300 }] });
|
||||
|
||||
@@ -294,8 +294,8 @@ describe('PhotoLightbox', () => {
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-026: a swipe to the right turns to the next photo', () => {
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
|
||||
fireEvent.touchStart(surface, { touches: [{ clientX: 100, clientY: 200 }] });
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 200, clientY: 210 }] });
|
||||
@@ -305,6 +305,13 @@ describe('PhotoLightbox', () => {
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 100, clientY: 210 }] });
|
||||
expect(screen.getByText('2 / 3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-030: the left inset of the screen stays on the left, where the close button now sits', () => {
|
||||
render(<PhotoLightbox photos={samplePhotos} onClose={vi.fn()} />);
|
||||
const style = screen.getByRole('dialog').style;
|
||||
expect(style.paddingInlineEnd).toContain('safe-area-inset-left');
|
||||
expect(style.paddingInlineStart).toContain('safe-area-inset-right');
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-027: a caption with a source page links to it in a new tab, one without stays text', () => {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { ChevronLeft, ChevronRight, Loader2, X, ZoomIn, ZoomOut } from 'lucide-react'
|
||||
import VideoPlayer from './VideoPlayerLazy'
|
||||
import { usePhotoZoom } from './usePhotoZoom'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { isRtlLanguage, useTranslation } from '../../i18n'
|
||||
import { lockBodyScroll } from '../../utils/bodyScrollLock'
|
||||
|
||||
interface LightboxPhoto {
|
||||
id: string
|
||||
@@ -34,10 +36,22 @@ interface Props {
|
||||
/** The round glass buttons of the top bar. */
|
||||
const ROUND_BTN: React.CSSProperties = {
|
||||
background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '50%',
|
||||
width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', cursor: 'pointer',
|
||||
width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', cursor: 'pointer', flex: 'none',
|
||||
}
|
||||
|
||||
/** Close is the one every visitor needs: a little stronger than the rest. */
|
||||
const CLOSE_BTN: React.CSSProperties = { ...ROUND_BTN, background: 'rgba(255,255,255,0.18)' }
|
||||
|
||||
/**
|
||||
* The device's insets, from whichever source reports them: env() in a browser,
|
||||
* the values Capacitor's SystemBars writes on Android, the ones the iOS app
|
||||
* measures itself. The viewer is portalled to <body>, outside the phone shell
|
||||
* that defines its own --m-safe-* tokens, so it reads the sources directly.
|
||||
*/
|
||||
const SAFE = (side: 'top' | 'bottom' | 'left' | 'right') =>
|
||||
`max(env(safe-area-inset-${side}, 0px), var(--safe-area-inset-${side}, 0px), var(--trek-native-safe-${side}, 0px))`
|
||||
|
||||
export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }: Props) {
|
||||
const [idx, setIdx] = useState(startIndex)
|
||||
const touchStart = useRef<{ x: number; y: number } | null>(null)
|
||||
@@ -51,7 +65,11 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
useEffect(() => {
|
||||
const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
dialogRef.current?.focus()
|
||||
return () => opener?.focus()
|
||||
const unlock = lockBodyScroll()
|
||||
return () => {
|
||||
unlock()
|
||||
opener?.focus()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const photo = photos[idx]
|
||||
@@ -111,7 +129,9 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
|
||||
if (!photo) return null
|
||||
|
||||
return (
|
||||
// Portalled to <body>: inside a transformed sheet or pane, `fixed` would be
|
||||
// relative to that box and the viewer would open as a small window in it.
|
||||
return createPortal(
|
||||
<div
|
||||
ref={dialogRef}
|
||||
role="dialog"
|
||||
@@ -120,26 +140,28 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
tabIndex={-1}
|
||||
style={{
|
||||
outline: 'none',
|
||||
position: 'fixed', inset: 0, zIndex: 10000,
|
||||
position: 'fixed', inset: 0, zIndex: 'var(--z-modal)',
|
||||
background: 'rgba(0,0,0,0.92)', backdropFilter: 'blur(20px)',
|
||||
display: 'flex', flexDirection: 'column',
|
||||
paddingBottom: 'var(--bottom-nav-h)',
|
||||
paddingBottom: SAFE('bottom'),
|
||||
// The insets belong to the screen's sides, which right to left swaps.
|
||||
paddingInlineStart: SAFE(rtl ? 'right' : 'left'),
|
||||
paddingInlineEnd: SAFE(rtl ? 'left' : 'right'),
|
||||
}}
|
||||
onTouchStart={onTouchStart}
|
||||
onTouchMove={onTouchMove}
|
||||
onTouchEnd={onTouchEnd}
|
||||
>
|
||||
{/* Photo area — centered with nav overlays */}
|
||||
<div
|
||||
className="group/lightbox"
|
||||
style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden' }}
|
||||
>
|
||||
{/* Top bar */}
|
||||
<div style={{ position: 'absolute', top: 0, insetInline: 0, zIndex: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px' }}>
|
||||
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500 }}>
|
||||
{idx + 1} / {photos.length}
|
||||
</span>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
{/* Top bar: its own row below the status bar and a notch, so the close
|
||||
button is always there to tap and never sits over the photo. */}
|
||||
<div style={{
|
||||
flex: 'none', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
|
||||
paddingBlock: `calc(${SAFE('top')} + 10px) 10px`, paddingInline: 16,
|
||||
}}>
|
||||
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
|
||||
{idx + 1} / {photos.length}
|
||||
</span>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
{isImage && (
|
||||
<>
|
||||
<Tooltip label={t('journey.lightbox.zoomOut')}>
|
||||
@@ -162,16 +184,17 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
</Tooltip>
|
||||
</>
|
||||
)}
|
||||
<button type="button" onClick={onClose} aria-label={t('common.close')} style={{
|
||||
background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '50%',
|
||||
width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', cursor: 'pointer',
|
||||
}}>
|
||||
<X size={18} />
|
||||
<button type="button" onClick={onClose} aria-label={t('common.close')} style={CLOSE_BTN}>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Photo area: what is left below the bar, with the page arrows over it. */}
|
||||
<div
|
||||
className="group/lightbox"
|
||||
style={{ flex: 1, minHeight: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden', padding: '0 8px 8px' }}
|
||||
>
|
||||
{/* Prev button — visible on hover (desktop), always visible (mobile) */}
|
||||
{hasPrev && (
|
||||
<button type="button" onClick={prev} aria-label={t('journey.lightbox.previous')} className="flex sm:opacity-0 sm:group-hover/lightbox:opacity-100 focus-visible:opacity-100 transition-opacity" style={{
|
||||
@@ -200,7 +223,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
onError={() => setLoadedId(photo.id)}
|
||||
{...zoom.mouse}
|
||||
style={{
|
||||
maxWidth: '92vw', maxHeight: '92vh',
|
||||
maxWidth: '100%', maxHeight: '100%',
|
||||
objectFit: 'contain', borderRadius: 4,
|
||||
animation: 'fadeIn 0.15s ease',
|
||||
userSelect: 'none',
|
||||
@@ -212,7 +235,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
{loading && (
|
||||
<div data-testid="lightbox-loading" aria-hidden="true" style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
|
||||
{photo.thumbSrc && (
|
||||
<img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '92vw', height: '92vh', objectFit: 'contain', borderRadius: 4 }} />
|
||||
<img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: 4 }} />
|
||||
)}
|
||||
<span style={{ ...ROUND_BTN, position: 'absolute', cursor: 'default' }}>
|
||||
<Loader2 size={18} className="animate-spin" />
|
||||
@@ -252,6 +275,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { pluginsApi } from '../../api/client'
|
||||
import type { RouteEngine, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
|
||||
import { haversineKm } from '../../utils/geo'
|
||||
import { countRoute } from './routeUsageCounter'
|
||||
import { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore'
|
||||
import { cacheRoute, keepStandIn, rememberRoute, routeInMemory, standIn, storedRoute } from './routeStore'
|
||||
import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
|
||||
import type { RouteAlternative } from './routeTypes'
|
||||
import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
|
||||
@@ -289,6 +289,12 @@ function withEngine(route: RouteWithLegs, engine: RouteEngine): RouteWithLegs {
|
||||
* A day planned with Valhalla: its answer, kept under the Valhalla key, or where it gives
|
||||
* none OSRM's for the whole day, kept under the plain key. One engine per day, never one
|
||||
* leg from each. While the relay rests, a day that avoids nothing is not put to it at all.
|
||||
*
|
||||
* A day that avoids nothing and that Valhalla could not route is not put to it again for a
|
||||
* while: OSRM's answer, the same road an OSRM instance draws, stands in for it under a key
|
||||
* of its own, so every visit does not wait out the relay first (#3228). Never under the
|
||||
* Valhalla key, which holds only what Valhalla answered. A day that avoids something is
|
||||
* asked again, since the stand-in drives the very road it means to leave out.
|
||||
*/
|
||||
async function valhallaOrOsrmDay(
|
||||
waypoints: Waypoint[],
|
||||
@@ -299,6 +305,9 @@ async function valhallaOrOsrmDay(
|
||||
signal?: AbortSignal
|
||||
},
|
||||
): Promise<RouteWithLegs> {
|
||||
const standInKey = avoiding.length ? null : `${keys.valhalla}:standin`
|
||||
const stoodIn = standInKey ? await standIn(standInKey) : null
|
||||
if (stoodIn) return stoodIn
|
||||
const asking = avoiding.length > 0 || valhallaRoutesDays()
|
||||
const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null
|
||||
if (routed) {
|
||||
@@ -307,7 +316,10 @@ async function valhallaOrOsrmDay(
|
||||
}
|
||||
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
|
||||
cacheRoute(keys.plain, plain)
|
||||
return withFallbackNoted(plain, avoiding)
|
||||
const drawn = withFallbackNoted(plain, avoiding)
|
||||
// A day left before Valhalla answered, or never put to it, was not refused by it.
|
||||
if (standInKey && asking && !signal?.aborted) keepStandIn(standInKey, drawn)
|
||||
return drawn
|
||||
}
|
||||
|
||||
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { Ref } from 'react'
|
||||
import { AlertTriangle, Route } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { MapTogglePill } from './MapTogglePill'
|
||||
@@ -6,6 +7,9 @@ import { routeDistanceLabel } from './tripRouteLabels'
|
||||
import type { TripRouteOverview as Overview } from './useTripRouteOverview'
|
||||
import type { DistanceUnit } from '../../types'
|
||||
|
||||
export const TRIP_OVERVIEW_MAX_WIDTH = 320
|
||||
export const TRIP_OVERVIEW_INSET = 14
|
||||
|
||||
/**
|
||||
* Toggle for the whole-trip route overview (#1736). Same frosted shell as the other
|
||||
* map controls, so it lines up with the compass and the layer switcher.
|
||||
@@ -29,13 +33,14 @@ export function TripRouteOverviewPill({ active, onToggle }: { active: boolean; o
|
||||
* One component for both shells: the phone and the desktop place it differently but the
|
||||
* rows are the same rows, and a second copy of them is a second thing to keep in step.
|
||||
*/
|
||||
export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectDay, maxWidth = 320 }: {
|
||||
export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectDay, maxWidth = TRIP_OVERVIEW_MAX_WIDTH, cardRef }: {
|
||||
overview: Overview
|
||||
unit: DistanceUnit
|
||||
selectedDayId?: number | null
|
||||
onSelectDay?: (dayId: number) => void
|
||||
/** How wide the card may grow before day names start to ellipsize. */
|
||||
maxWidth?: number
|
||||
cardRef?: Ref<HTMLDivElement>
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
if (!overview.days.length) return null
|
||||
@@ -45,6 +50,7 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={cardRef}
|
||||
data-testid="trip-overview-panel"
|
||||
style={{
|
||||
pointerEvents: 'auto', borderRadius: 14, overflow: 'hidden',
|
||||
|
||||
@@ -35,4 +35,12 @@ describe('centredMapCard', () => {
|
||||
expect(resolve(box.width, 1920)).toBe(800);
|
||||
expect(resolve(box.centre, 1920)).toBe(960);
|
||||
});
|
||||
|
||||
it('keeps the whole-trip toggle reachable beside the day card', () => {
|
||||
const box = centredMapCard(350, 310, { clearPill: true, rightGap: 74 });
|
||||
const width = resolve(box.width, 1280);
|
||||
const centre = resolve(box.centre, 1280);
|
||||
expect(centre - width / 2).toBeGreaterThanOrEqual(350 + 62);
|
||||
expect(centre + width / 2).toBeLessThanOrEqual(1280 - 310 - 74);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,7 @@ const PILL_CLEARANCE = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8;
|
||||
* it and gives up the few pixels it needs, a wide map keeps it exactly centred.
|
||||
* The phone shows these cards as sheets with no pill beside them, so it leaves
|
||||
* `clearPill` off.
|
||||
* `rightGap` reserves room for a map control on the other edge.
|
||||
*
|
||||
* `extent` is what the card is placed in: '100%' of the map, or '100vw' for the
|
||||
* fixed day panel.
|
||||
@@ -29,13 +30,21 @@ const PILL_CLEARANCE = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8;
|
||||
export function centredMapCard(
|
||||
leftWidth: number,
|
||||
rightWidth: number,
|
||||
{ extent = '100%', clearPill = false }: { extent?: string; clearPill?: boolean } = {}
|
||||
{
|
||||
extent = '100%',
|
||||
clearPill = false,
|
||||
rightGap = EDGE_GAP,
|
||||
}: { extent?: string; clearPill?: boolean; rightGap?: number } = {}
|
||||
): { centre: string; width: string } {
|
||||
const free = `(${extent} - ${leftWidth}px - ${rightWidth}px)`;
|
||||
const centre = `calc(${leftWidth}px + ${free} / 2)`;
|
||||
if (!clearPill) return { centre, width: `min(800px, calc(${free} - ${2 * EDGE_GAP}px))` };
|
||||
const width = `min(800px, calc(${free} - ${PILL_CLEARANCE + EDGE_GAP}px))`;
|
||||
return { width, centre: `max(${centre}, calc(${leftWidth}px + ${PILL_CLEARANCE}px + ${width} / 2))` };
|
||||
const leftGap = clearPill ? PILL_CLEARANCE : EDGE_GAP;
|
||||
const width = `min(800px, calc(${free} - ${leftGap + rightGap}px))`;
|
||||
const centreClearingLeft = `max(${centre}, calc(${leftWidth}px + ${leftGap}px + ${width} / 2))`;
|
||||
if (rightGap === EDGE_GAP) return { width, centre: clearPill ? centreClearingLeft : centre };
|
||||
|
||||
const maxCentre = `calc(${extent} - ${rightWidth + rightGap}px - ${width} / 2)`;
|
||||
return { width, centre: `min(${centreClearingLeft}, ${maxCentre})` };
|
||||
}
|
||||
|
||||
/** How a card that floats over the map is placed there, read by `centredMapCard`. */
|
||||
|
||||
@@ -39,3 +39,21 @@ export async function storedRoute(key: string): Promise<RouteWithLegs | null> {
|
||||
if (kept) rememberRoute(key, kept);
|
||||
return kept;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long OSRM's answer stands in for a day Valhalla could not route. Long enough that
|
||||
* reopening the trip draws that day at once instead of waiting out the relay again on
|
||||
* every visit (#3228), short enough that a Valhalla back from an outage gets the day again
|
||||
* the same day.
|
||||
*/
|
||||
const STAND_IN_MS = 60 * 60 * 1000;
|
||||
|
||||
/** Keeps OSRM's answer for a day Valhalla could not route, on the device only, for `STAND_IN_MS`. */
|
||||
export function keepStandIn(key: string, route: RouteWithLegs): void {
|
||||
void routeCacheRepo.put(key, route);
|
||||
}
|
||||
|
||||
/** The answer that stood in for a day Valhalla could not route, while it is recent enough. */
|
||||
export function standIn(key: string): Promise<RouteWithLegs | null> {
|
||||
return routeCacheRepo.get<RouteWithLegs>(key, STAND_IN_MS);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ export interface TripRouteOverview extends TripRouteSummary {
|
||||
loading: boolean
|
||||
}
|
||||
|
||||
/** The overview as the planner reads it: also whether the trip has any stop to route at all. */
|
||||
type PlannedTripRouteOverview = TripRouteOverview & { hasPlannedRoute: boolean }
|
||||
|
||||
const EMPTY: TripRouteOverview = { ...summariseTripRoute([]), loading: false }
|
||||
const EMPTY_PLACES: Place[] = []
|
||||
|
||||
@@ -49,7 +52,7 @@ export function useTripRouteOverview(
|
||||
vias?: TripRouteVias,
|
||||
/** MDT-02: where the stages of the trip's multi-day tours run, so a day holding one draws that stage. */
|
||||
tourStageStops?: TourStageStops,
|
||||
): TripRouteOverview {
|
||||
): PlannedTripRouteOverview {
|
||||
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
|
||||
// Leg text is formatted at compute time, so a km↔mi switch has to re-run (#1300).
|
||||
@@ -131,5 +134,6 @@ export function useTripRouteOverview(
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [planKey, tripId, distanceUnit])
|
||||
|
||||
return result
|
||||
const hasPlannedRoute = plan.length > 0
|
||||
return useMemo(() => ({ ...result, hasPlannedRoute }), [result, hasPlannedRoute])
|
||||
}
|
||||
|
||||
@@ -59,6 +59,8 @@ interface Traffic {
|
||||
osrm: string[];
|
||||
}
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
|
||||
const answered = (body: RouteBody) => HttpResponse.json({ trip: valhallaTrip(body.locations) });
|
||||
|
||||
/** Every routing host answering, the relay as `relay` says; what each was asked is recorded. */
|
||||
@@ -274,12 +276,59 @@ describe('the route cache keeps the engine apart', () => {
|
||||
|
||||
up = true;
|
||||
resetValhallaTurns();
|
||||
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(2000);
|
||||
expect(traffic.relay).toHaveLength(1);
|
||||
|
||||
const now = Date.now();
|
||||
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
|
||||
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
|
||||
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('VDAY-CACHE-005: a day the relay could not route opens drawn after a reload, without waiting for the relay again (#3228)', async () => {
|
||||
const points = freshDay(3);
|
||||
let slow = true;
|
||||
const traffic = listen((body) =>
|
||||
slow ? HttpResponse.json({ error: 'The TREK routing service took too long' }, { status: 504 }) : answered(body)
|
||||
);
|
||||
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).engine).toBe('osrm');
|
||||
const { offlineDb } = await import('../../db/offlineDb');
|
||||
const stoodIn = (key: string) => key.includes(`${points[0].lng},${points[0].lat}`) && key.endsWith(':standin');
|
||||
await vi.waitFor(async () => expect(await offlineDb.routeCache.filter((row) => stoodIn(row.key)).count()).toBe(1));
|
||||
|
||||
// A reload: the modules, and with them the routes in memory and the relay's rest, start over.
|
||||
vi.resetModules();
|
||||
const reloaded = await import('./RouteCalculator');
|
||||
const again = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
|
||||
expect([again.distance, again.engine]).toEqual([2000, 'osrm']);
|
||||
expect([traffic.relay.length, traffic.osrm.length]).toEqual([1, 1]);
|
||||
|
||||
// An hour on, the relay gets the day again and its answer is kept as the day's.
|
||||
slow = false;
|
||||
const now = Date.now();
|
||||
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
|
||||
const routed = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
|
||||
expect([routed.distance, routed.engine]).toEqual([4000, 'valhalla']);
|
||||
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the route cache while the relay rests', () => {
|
||||
it('VDAY-CACHE-006: a day drawn by OSRM while the relay rested is asked again as soon as it is back', async () => {
|
||||
let up = false;
|
||||
const traffic = listen((body) => (up ? answered(body) : HttpResponse.json({ error: 'down' }, { status: 503 })));
|
||||
await calculateRouteWithLegs(freshDay(2), { profile: 'driving' });
|
||||
const points = freshDay(3);
|
||||
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).engine).toBe('osrm');
|
||||
expect(traffic.relay).toHaveLength(1);
|
||||
|
||||
up = true;
|
||||
resetValhallaTurns();
|
||||
const routed = await calculateRouteWithLegs(points, { profile: 'driving' });
|
||||
expect([routed.distance, routed.engine]).toEqual([4000, 'valhalla']);
|
||||
expect(traffic.relay).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('VDAY-CACHE-003: a day kept from Valhalla is still found while the relay rests, as it is offline', async () => {
|
||||
const points = freshDay(3);
|
||||
let up = true;
|
||||
|
||||
@@ -463,6 +463,36 @@ describe('downloadTripPDF', () => {
|
||||
expect(html).not.toContain('<script>alert(1)</script>')
|
||||
})
|
||||
|
||||
// #3236: day notes, transport notes and the day intro are markdown in the planner too.
|
||||
it('FE-COMP-TRIPPDF-016m: renders markdown in day notes, transport notes and the day intro, sanitized', async () => {
|
||||
const md = {
|
||||
...richArgs,
|
||||
days: [{ ...dayWithPlaces, notes: '**Intro** day\n\n- museum\n- lunch' }],
|
||||
dayNotes: [{ ...dayNote, time: '*Bring* water\n___\n<script>alert(1)</script>' }],
|
||||
reservations: [{ ...transportReservation, notes: 'Seat **14A**\n1. check in\n2. board' }],
|
||||
}
|
||||
await downloadTripPDF(md)
|
||||
const html = getIframe()?.srcdoc ?? ''
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html')
|
||||
const card = (selector: string) => {
|
||||
const found = doc.querySelector(selector)
|
||||
if (!found) throw new Error(`${selector} is not in the export`)
|
||||
return found
|
||||
}
|
||||
const intro = card('.day-intro')
|
||||
expect(intro.querySelector('strong')?.textContent).toBe('Intro')
|
||||
expect([...intro.querySelectorAll('li')].map(li => li.textContent)).toEqual(['museum', 'lunch'])
|
||||
const noteLine = card('.tl-note .note-time')
|
||||
expect(noteLine.querySelector('em')?.textContent).toBe('Bring')
|
||||
expect(noteLine.querySelector('hr')).not.toBeNull()
|
||||
expect(noteLine.querySelector('script')).toBeNull()
|
||||
expect(noteLine.textContent).toContain('<script>alert(1)</script>')
|
||||
const transportNote = card('.transport-note')
|
||||
expect(transportNote.querySelector('strong')?.textContent).toBe('14A')
|
||||
expect([...transportNote.querySelectorAll('ol li')].map(li => li.textContent)).toEqual(['check in', 'board'])
|
||||
expect(html).not.toContain('**')
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-016b: formats price chip and totals in the trip currency, not EUR', async () => {
|
||||
const usdArgs = {
|
||||
...richArgs,
|
||||
@@ -1464,7 +1494,8 @@ describe('downloadTripPDF — transport notes', () => {
|
||||
await downloadTripPDF({ ...richArgs, reservations: [{ ...withNote, notes: 'Gate <b>B12</b>' }] })
|
||||
const html = getIframe()!.srcdoc
|
||||
|
||||
expect(html).toContain('<div class="note-time transport-note">Gate <b>B12</b></div>')
|
||||
// Markdown like the planner (#3236), raw HTML still printed as text.
|
||||
expect(html).toContain('<div class="note-time transport-note md"><p><bdi>Gate <b>B12</b></bdi></p></div>')
|
||||
expect(html).not.toContain('pdf-no-transport-notes"')
|
||||
expect(notesToggle()!.getAttribute('aria-checked')).toBe('true')
|
||||
})
|
||||
@@ -1472,7 +1503,7 @@ describe('downloadTripPDF — transport notes', () => {
|
||||
it('FE-PDF-TNOTES-002: without any transport note there is nothing to switch', async () => {
|
||||
await downloadTripPDF(richArgs)
|
||||
|
||||
expect(getIframe()!.srcdoc).not.toContain('class="note-time transport-note"')
|
||||
expect(getIframe()!.srcdoc).not.toContain('class="note-time transport-note')
|
||||
expect(notesToggle()).toBeNull()
|
||||
// The page break switch is still there on its own.
|
||||
expect(document.querySelector('#pdf-daybreak-toggle')).not.toBeNull()
|
||||
|
||||
@@ -245,6 +245,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
return url ? thumbs.get(url) ?? url : null
|
||||
},
|
||||
markdown: text => markdown.row(text),
|
||||
markdownHtml: text => markdown.html(text),
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -303,7 +304,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
? `<div class="empty-day">${escHtml(tr('dayplan.emptyDay'))}</div>`
|
||||
: `<ol class="timeline">${merged.map(item => {
|
||||
if (item.type === 'transport') return bookingItem(item.data as PdfBooking, day, ctx, flags)
|
||||
if (item.type === 'note') return noteItem(item.data as DayNote)
|
||||
if (item.type === 'note') return noteItem(item.data as DayNote, ctx)
|
||||
const a = item.data as Assignment
|
||||
if (!a.place) return ''
|
||||
number++
|
||||
@@ -316,7 +317,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
cost: dayCost(day.id) || null,
|
||||
}, ctx)
|
||||
const strip = photoStrip((stripPhotos.get(day.id) || []).map(p => ({ ...p, url: stripCopies.get(p.url) ?? p.url })))
|
||||
const intro = day.notes && day.notes.trim() ? `<div class="day-intro">${escHtml(day.notes.trim())}</div>` : ''
|
||||
const intro = day.notes && day.notes.trim() ? `<div class="day-intro md">${markdown.html(day.notes.trim())}</div>` : ''
|
||||
const stays = staysBlock(staysForDay(day, days, accommodationList), day, ctx)
|
||||
|
||||
// A real <table> so the browser repeats the <thead> day header at the top of
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import { createMarkdownHtml } from '../shared/markdownHtml';
|
||||
|
||||
/**
|
||||
* A place's description and notes are markdown in the app, so the export
|
||||
* renders them the same way instead of printing the raw syntax (#2692): one
|
||||
* info row per text, the HTML from the app's own sanitized pipeline.
|
||||
* Place descriptions and notes, day notes, booking notes and the day intro are
|
||||
* markdown in the app, so the export renders them the same way instead of
|
||||
* printing the raw syntax (#2692, #3236), the HTML from the app's own sanitized
|
||||
* pipeline. `row` lays a place's text out as an info row, `html` is the bare
|
||||
* markup for a card that brings its own box.
|
||||
*/
|
||||
export function createPdfMarkdown(): { row: (text: string) => string; dispose: () => void } {
|
||||
export function createPdfMarkdown(): {
|
||||
row: (text: string) => string;
|
||||
html: (text: string) => string;
|
||||
dispose: () => void;
|
||||
} {
|
||||
const markdown = createMarkdownHtml();
|
||||
return {
|
||||
row: (text) =>
|
||||
`<div class="info-row"><span class="info-spacer"></span><div class="info-text muted md">${markdown.html(text)}</div></div>`,
|
||||
html: markdown.html,
|
||||
dispose: markdown.dispose,
|
||||
};
|
||||
}
|
||||
@@ -17,6 +24,7 @@ export function createPdfMarkdown(): { row: (text: string) => string; dispose: (
|
||||
/** The markdown's own spacing, lists, tables and links at the export's small size. */
|
||||
export const PDF_MARKDOWN_CSS = `
|
||||
.info-text.md { min-width: 0; overflow-wrap: anywhere; }
|
||||
.note-time.md, .day-intro.md { white-space: normal; }
|
||||
.md > :first-child { margin-top: 0; }
|
||||
.md > :last-child { margin-bottom: 0; }
|
||||
.md p, .md ul, .md ol, .md table, .md blockquote, .md pre { margin: 0 0 4px; }
|
||||
|
||||
@@ -50,6 +50,7 @@ function context(over: Partial<PdfDayContext> = {}): PdfDayContext {
|
||||
placesById: new Map([[fullPlace.id, fullPlace]]),
|
||||
photoOf: () => null,
|
||||
markdown: (text) => `<p>${text}</p>`,
|
||||
markdownHtml: (text) => `<p>${text}</p>`,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
@@ -169,7 +170,7 @@ describe('noteItem', () => {
|
||||
icon: 'Ticket',
|
||||
color: '#2563eb',
|
||||
} as DayNote;
|
||||
const tinted = parse(noteItem(note));
|
||||
const tinted = parse(noteItem(note, context()));
|
||||
expect(tinted.querySelector('.note-card')?.className).toBe('note-card note-tinted');
|
||||
expect(tinted.querySelector('.note-card')?.getAttribute('style')).toBe('--note:#2563eb');
|
||||
expect(texts(tinted, '.note-text')).toEqual(['Buy <tickets>']);
|
||||
@@ -177,7 +178,7 @@ describe('noteItem', () => {
|
||||
expect(texts(tinted, '.note-time')).toEqual(['08:00']);
|
||||
expect(tinted.querySelector('.tl-start')).toBeNull();
|
||||
|
||||
const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote));
|
||||
const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote, context()));
|
||||
expect(plain.querySelector('.note-card')?.className).toBe('note-card');
|
||||
expect(plain.querySelector('.note-time')).toBeNull();
|
||||
});
|
||||
|
||||
@@ -30,8 +30,10 @@ export interface PdfDayContext {
|
||||
placesById: ReadonlyMap<number, Place>;
|
||||
/** The picture to print for a place, already shrunk where it could be; null for none. */
|
||||
photoOf: (place: Assignment['place']) => string | null;
|
||||
/** A place's description or notes as sanitized markdown. */
|
||||
/** A place's description or notes as sanitized markdown, laid out as an info row. */
|
||||
markdown: (text: string) => string;
|
||||
/** A note's markdown as sanitized HTML, for a card that brings its own box. */
|
||||
markdownHtml: (text: string) => string;
|
||||
}
|
||||
|
||||
const NEUTRAL = '#6b6b75';
|
||||
@@ -214,7 +216,7 @@ export function bookingItem(r: PdfBooking, day: Day, ctx: PdfDayContext, flags:
|
||||
${bookingLines(r, tr).map(bookingLineHtml).join('')}
|
||||
${location ? `<div class="note-time">${escHtml(location)}</div>` : ''}
|
||||
${extras.length ? `<div class="note-extra">${extras.join('')}</div>` : ''}
|
||||
${note ? `<div class="note-time transport-note">${escHtml(note)}</div>` : ''}
|
||||
${note ? `<div class="note-time transport-note md">${ctx.markdownHtml(note)}</div>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
return item('booking', timeColumn(start, end), bookingIcon(r.type, 11), card, `--kind:${tint}`);
|
||||
@@ -226,15 +228,16 @@ export function bookingItem(r: PdfBooking, day: Day, ctx: PdfDayContext, flags:
|
||||
* A day note. A coloured note carries its colour as the rule along its edge and its
|
||||
* icon (#1629), not as a fill: a tint costs ink and reads as grey on a mono printer.
|
||||
*/
|
||||
export function noteItem(note: DayNote): string {
|
||||
export function noteItem(note: DayNote, ctx: PdfDayContext): string {
|
||||
const colour = note.color ? hexColour(note.color, '') : '';
|
||||
// A note's `time` is the free line the day plan prints under its text, not a clock,
|
||||
// so it stays in the card and the time column stays empty.
|
||||
// so it stays in the card and the time column stays empty. The planner renders it as
|
||||
// markdown, so the card does too (#3236).
|
||||
const subtitle = typeof note.time === 'string' ? note.time.trim() : '';
|
||||
const card = `<div class="note-card${colour ? ' note-tinted' : ''}"${colour ? ` style="--note:${colour}"` : ''}>
|
||||
<span class="note-icon">${noteIcon(note.icon)}</span>
|
||||
<div class="note-body"><div class="note-text">${escHtml(note.text)}</div>${
|
||||
subtitle ? `<div class="note-time">${escHtml(subtitle)}</div>` : ''
|
||||
subtitle ? `<div class="note-time md">${ctx.markdownHtml(subtitle)}</div>` : ''
|
||||
}</div>
|
||||
</div>`;
|
||||
return item('note', timeColumn('', ''), '', card);
|
||||
|
||||
@@ -204,6 +204,9 @@ describe('BookingCostsSection', () => {
|
||||
expect(screen.getByText('Transport')).toBeInTheDocument();
|
||||
expect(screen.getByText(money(99, 'CHF'))).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /Create expense/ })).not.toBeInTheDocument();
|
||||
// The save adds the cost itself and opens no editor, so the preview says that (#3237).
|
||||
expect(screen.getByText('Added to Costs when you save the booking.')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Saves the booking, then opens the Costs editor.')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-COSTSEC-016: an amount without a currency is in the trip currency, whatever the display currency (#2525)', () => {
|
||||
|
||||
@@ -29,7 +29,7 @@ export function BookingCostsSection({ reservationId, placeId = null, hintKey = '
|
||||
reservationId: number | null
|
||||
/** Set instead of reservationId when the block sits in the place form (#1298). */
|
||||
placeId?: number | null
|
||||
/** What gets saved before the editor opens — "the booking" or "the place". */
|
||||
/** The create button's hint: what gets saved before the editor opens, "the booking" or "the place". */
|
||||
hintKey?: string
|
||||
/** A cost parsed from an import that will be linked on save — previewed before the booking exists. */
|
||||
pendingExpense?: { total_price: number; currency?: string | null; category: string } | null
|
||||
@@ -76,6 +76,8 @@ export function BookingCostsSection({ reservationId, placeId = null, hintKey = '
|
||||
}
|
||||
|
||||
// Import review (booking not saved yet): preview the parsed cost that will be linked on save.
|
||||
// The save adds it itself and opens no editor, so the line under it says so, not the
|
||||
// create button's hint (#3237).
|
||||
if (linked.length === 0 && pendingExpense && pendingExpense.total_price > 0) {
|
||||
const meta = catMeta(pendingExpense.category)
|
||||
const Icon = meta.Icon
|
||||
@@ -86,7 +88,7 @@ export function BookingCostsSection({ reservationId, placeId = null, hintKey = '
|
||||
<span style={{ width: 26, height: 26, borderRadius: 7, display: 'grid', placeItems: 'center', background: meta.color + '22', color: meta.color, flexShrink: 0 }}><Icon size={14} /></span>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div className="text-content" style={{ ...fs(14, 'body'), fontWeight: 600 }}>{t(meta.labelKey)}</div>
|
||||
<div className="text-content-faint" style={fs(12, 'body')}>{t(hintKey)}</div>
|
||||
<div className="text-content-faint" style={fs(12, 'body')}>{t('reservations.importedExpenseHint')}</div>
|
||||
</div>
|
||||
<span className="text-content" style={{ ...fs(14, 'body'), fontWeight: 700, flexShrink: 0 }}>{formatMoney(pendingExpense.total_price, ownCurrency(pendingExpense.currency), locale)}</span>
|
||||
</div>
|
||||
|
||||
@@ -1,32 +1,12 @@
|
||||
// FE-PLANNER-DAYDETAIL-DF-001 to FE-PLANNER-DAYDETAIL-DF-002
|
||||
// The day panel's heading with "date first in day headings" on (#2921).
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { buildAdmin, buildDay, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { dayDetailProps as props, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { seedStore } from '../../../tests/helpers/store';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import DayDetailPanel from './DayDetailPanel';
|
||||
|
||||
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
|
||||
|
||||
const props = {
|
||||
day,
|
||||
days: [day],
|
||||
places: [],
|
||||
categories: [],
|
||||
tripId: 1,
|
||||
assignments: {},
|
||||
reservations: [],
|
||||
lat: null,
|
||||
lng: null,
|
||||
onClose: vi.fn(),
|
||||
onAccommodationChange: vi.fn(),
|
||||
};
|
||||
|
||||
function settings(dayDateFirst: boolean) {
|
||||
seedStore(useSettingsStore, {
|
||||
settings: { time_format: '24h', temperature_unit: 'celsius', day_date_first: dayDateFirst },
|
||||
@@ -34,14 +14,7 @@ function settings(dayDateFirst: boolean) {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
server.use(
|
||||
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
|
||||
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] }))
|
||||
);
|
||||
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
|
||||
resetDayDetailPanel();
|
||||
});
|
||||
|
||||
describe('DayDetailPanel with the date first', () => {
|
||||
|
||||
@@ -5,43 +5,17 @@ import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { usePermissionsStore } from '../../store/permissionsStore';
|
||||
import { usePluginStore } from '../../store/pluginStore';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser, buildAdmin, buildTrip, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
|
||||
import { seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser, buildAdmin, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
|
||||
import { dayDetailDay as day, dayDetailProps as defaultProps, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
|
||||
import DayDetailPanel from './DayDetailPanel';
|
||||
import { isBlurred } from '../../../tests/helpers/bookingCodeBlur';
|
||||
|
||||
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
|
||||
|
||||
const defaultProps = {
|
||||
day,
|
||||
days: [day],
|
||||
places: [],
|
||||
categories: [],
|
||||
tripId: 1,
|
||||
assignments: {},
|
||||
reservations: [],
|
||||
lat: null,
|
||||
lng: null,
|
||||
onClose: vi.fn(),
|
||||
onAccommodationChange: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
server.use(
|
||||
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
|
||||
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] })),
|
||||
);
|
||||
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
|
||||
seedStore(useSettingsStore, {
|
||||
settings: { time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false },
|
||||
});
|
||||
resetDayDetailPanel({ time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false });
|
||||
});
|
||||
|
||||
/** The stay picker filters by category through a pill that opens its list; this picks one entry of it. */
|
||||
@@ -147,13 +121,23 @@ describe('DayDetailPanel', () => {
|
||||
});
|
||||
|
||||
it('FE-PLANNER-DAYDETAIL-009: weather loading state shown briefly', async () => {
|
||||
// The forecast is held until the spinner was seen, then released, so the request
|
||||
// does not stay open past this test.
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => { release = resolve; });
|
||||
server.use(
|
||||
http.get('/api/weather/detailed', () => new Promise(() => {})), // never resolves
|
||||
http.get('/api/weather/detailed', async () => {
|
||||
await gate;
|
||||
return HttpResponse.json({ error: true });
|
||||
}),
|
||||
);
|
||||
render(<DayDetailPanel {...defaultProps} lat={48.8566} lng={2.3522} />);
|
||||
// The spinner announces itself as a loading status
|
||||
const spinner = await screen.findByRole('status', { name: 'Loading...' });
|
||||
expect(spinner.querySelector('.animate-spin')).not.toBeNull();
|
||||
|
||||
release();
|
||||
expect(await screen.findByText(/No weather/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-DAYDETAIL-101: a late forecast for the previous day never replaces the one for the current day', async () => {
|
||||
@@ -1606,14 +1590,14 @@ describe('DayDetailPanel remaining branches', () => {
|
||||
const user = userEvent.setup();
|
||||
const onAccommodationChange = vi.fn();
|
||||
let updateBody: Record<string, unknown> | null = null;
|
||||
let listCalls = 0;
|
||||
// The reload after the save reads the new name; keyed on the save, not on a
|
||||
// count of reads, so a stray read before it cannot rename the stay early.
|
||||
server.use(
|
||||
http.get('/api/trips/1/accommodations', () => {
|
||||
listCalls += 1;
|
||||
return HttpResponse.json({
|
||||
accommodations: [hotel(listCalls > 1 ? { place_name: 'Reloaded Hotel' } : {})],
|
||||
});
|
||||
}),
|
||||
http.get('/api/trips/1/accommodations', () =>
|
||||
HttpResponse.json({
|
||||
accommodations: [hotel(updateBody ? { place_name: 'Reloaded Hotel' } : {})],
|
||||
}),
|
||||
),
|
||||
http.put('/api/trips/1/accommodations/1', async ({ request }) => {
|
||||
updateBody = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ accommodation: hotel() });
|
||||
@@ -1874,25 +1858,40 @@ describe('DayDetailPanel remaining branches, part two', () => {
|
||||
expect(await screen.findByText('15h 20m')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', () => {
|
||||
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', async () => {
|
||||
// Each mount reads the stays; wait for that read to be answered, so it cannot
|
||||
// reach the handler of the test that runs next.
|
||||
let staysRead = 0;
|
||||
server.use(
|
||||
http.get('/api/trips/1/accommodations', () => {
|
||||
staysRead += 1;
|
||||
return HttpResponse.json({ accommodations: [] });
|
||||
}),
|
||||
);
|
||||
const bare = buildDay({ id: 2, trip_id: 1, date: null, title: null });
|
||||
const { unmount } = render(<DayDetailPanel {...defaultProps} day={bare} days={[defaultProps.day, bare]} collapsed />);
|
||||
expect(screen.getByText('Day 2')).toBeInTheDocument();
|
||||
await waitFor(() => expect(staysRead).toBe(1));
|
||||
unmount();
|
||||
|
||||
render(<DayDetailPanel {...defaultProps} day={bare} days={[]} collapsed />);
|
||||
expect(screen.getByText('Day ?')).toBeInTheDocument();
|
||||
await waitFor(() => expect(staysRead).toBe(2));
|
||||
});
|
||||
|
||||
it('FE-W5DDP-020: an empty reload after the edit-save clears the accommodation', async () => {
|
||||
const user = userEvent.setup();
|
||||
let listCalls = 0;
|
||||
// The list empties once the edit is saved, not on a count of reads, so a stray
|
||||
// read before the save cannot empty it early.
|
||||
let saved = false;
|
||||
server.use(
|
||||
http.get('/api/trips/1/accommodations', () => {
|
||||
listCalls += 1;
|
||||
return listCalls === 1 ? HttpResponse.json({ accommodations: [hotel()] }) : HttpResponse.json({});
|
||||
http.get('/api/trips/1/accommodations', () =>
|
||||
saved ? HttpResponse.json({}) : HttpResponse.json({ accommodations: [hotel()] }),
|
||||
),
|
||||
http.put('/api/trips/1/accommodations/1', () => {
|
||||
saved = true;
|
||||
return HttpResponse.json({ accommodation: hotel() });
|
||||
}),
|
||||
http.put('/api/trips/1/accommodations/1', () => HttpResponse.json({ accommodation: hotel() })),
|
||||
);
|
||||
|
||||
render(<DayDetailPanel {...defaultProps} places={[buildPlace({ id: 5, name: 'Grand Hotel' })]} />);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useRef, useId, type ReactNode } from 'react'
|
||||
import React, { useEffect, useRef, useId, type ReactNode, type Ref } from 'react'
|
||||
import { X, CloudRain, Wind, Droplets, Sunrise, Sunset, Hotel, Calendar, MapPin, LogIn, LogOut, Pencil, ChevronsDown, ChevronsUp, ArrowRight, Check, Moon, type LucideIcon } from 'lucide-react'
|
||||
import type { WeatherResult } from '@trek/shared'
|
||||
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
|
||||
@@ -53,6 +53,8 @@ interface DayDetailPanelProps {
|
||||
onAccommodationChange: () => void
|
||||
leftWidth?: number
|
||||
rightWidth?: number
|
||||
rightGap?: number
|
||||
panelRef?: Ref<HTMLDivElement>
|
||||
collapsed?: boolean
|
||||
onToggleCollapse?: () => void
|
||||
mobile?: boolean
|
||||
@@ -73,7 +75,7 @@ interface DayDetailPanelProps {
|
||||
* head band that folds the card away, then the weather, the bookings of the
|
||||
* day and where the night is spent, each under its own label.
|
||||
*/
|
||||
export default function DayDetailPanel({ day, days, places, categories = [], tripId, assignments, reservations = [], lat, lng, onClose, onAccommodationChange, leftWidth = 0, rightWidth = 0, collapsed: collapsedProp = false, onToggleCollapse, mobile = false, onUpdateDayTitle, weatherPlaceName = null, openStayPicker = false, onStayPickerOpened, onOpenBooking }: DayDetailPanelProps) {
|
||||
export default function DayDetailPanel({ day, days, places, categories = [], tripId, assignments, reservations = [], lat, lng, onClose, onAccommodationChange, leftWidth = 0, rightWidth = 0, rightGap, panelRef, collapsed: collapsedProp = false, onToggleCollapse, mobile = false, onUpdateDayTitle, weatherPlaceName = null, openStayPicker = false, onStayPickerOpened, onOpenBooking }: DayDetailPanelProps) {
|
||||
const { t, language } = useTranslation()
|
||||
const can = useCanDo()
|
||||
const toast = useToast()
|
||||
@@ -184,10 +186,10 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
|
||||
setShowHotelPicker('edit')
|
||||
}
|
||||
const removeAccommodation = (acc: Accommodation) => { handleRemoveAccommodation(acc).catch(showError) }
|
||||
const mapCard = centredMapCard(leftWidth, rightWidth, { extent: '100vw', clearPill: !mobile })
|
||||
const mapCard = centredMapCard(leftWidth, rightWidth, { extent: '100vw', clearPill: !mobile, rightGap })
|
||||
|
||||
return (
|
||||
<div className="fixed z-50" style={{ bottom: 'calc(var(--bottom-nav-h) + 20px)', left: mapCard.centre, transform: 'translateX(-50%)', width: mapCard.width, ...(mobile ? { zIndex: 10000 } : null), fontFamily: 'var(--font-system)' }}>
|
||||
<div ref={panelRef} className="fixed z-50" style={{ bottom: 'calc(var(--bottom-nav-h) + 20px)', left: mapCard.centre, transform: 'translateX(-50%)', width: mapCard.width, ...(mobile ? { zIndex: 10000 } : null), fontFamily: 'var(--font-system)' }}>
|
||||
<div ref={cardRef}
|
||||
className="flex flex-col overflow-hidden rounded-[20px] border border-edge-faint bg-surface-elevated shadow-popover backdrop-blur-[40px] backdrop-saturate-[1.8]"
|
||||
style={{ maxHeight: collapsed ? 'none' : '60vh' }}>
|
||||
|
||||
@@ -158,6 +158,18 @@ function dayHeader(title: string) {
|
||||
}
|
||||
|
||||
describe('DayPlanSidebar day header', () => {
|
||||
it('opens the selected day details while the whole-trip overview is active', async () => {
|
||||
const user = userEvent.setup();
|
||||
const day = buildDay({ id: 10, date: '2025-06-01', title: 'My Day' });
|
||||
const props = makeDefaultProps({ days: [day], selectedDayId: day.id });
|
||||
render(<DayPlanSidebar {...props} openSelectedDayDetail />);
|
||||
|
||||
await user.click(screen.getByText('My Day'));
|
||||
|
||||
expect(props.onSelectDay).toHaveBeenCalledWith(day.id);
|
||||
expect(props.onDayDetail).toHaveBeenCalledWith(day);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-176: a transfer day lists the check-out hotel before the check-in one', async () => {
|
||||
const user = userEvent.setup();
|
||||
const days = [
|
||||
|
||||
@@ -104,6 +104,7 @@ export interface DayPlanSidebarProps {
|
||||
categories: Category[]
|
||||
assignments: AssignmentsMap
|
||||
selectedDayId: number | null
|
||||
openSelectedDayDetail?: boolean
|
||||
selectedPlaceId: number | null
|
||||
selectedAssignmentId: number | null
|
||||
onSelectDay: (dayId: number | null, skipFit?: boolean) => void
|
||||
@@ -1480,12 +1481,11 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
<div className={`scroll-container flex flex-col gap-2 p-2${hasDragged ? '' : ' trek-stagger'}`} style={{ flex: 1, overflowY: 'auto', minHeight: 0 }} ref={scrollContainerRef} onScroll={(e) => onScrollTopChange?.((e.currentTarget as HTMLElement).scrollTop)}>
|
||||
{days.map((day, index) => {
|
||||
const isSelected = selectedDayId === day.id
|
||||
// Shared by the click and the key handler so the two can never drift
|
||||
// apart — pressing Enter on the row has to toggle, not just select.
|
||||
// Named for the selection, not the expand/collapse `toggleDay` above.
|
||||
// An already-selected day can reopen its details from the overview.
|
||||
const toggleDaySelection = () => {
|
||||
if (isSelected) { onSelectDay(null); if (onDayDetail) onDayDetail(null) }
|
||||
else { onSelectDay(day.id); if (onDayDetail) onDayDetail(day) }
|
||||
const dayToOpen = isSelected && !props.openSelectedDayDetail ? null : day
|
||||
onSelectDay(dayToOpen?.id ?? null)
|
||||
onDayDetail?.(dayToOpen)
|
||||
}
|
||||
const isExpanded = expandedDays.has(day.id)
|
||||
const da = getDayAssignments(day.id)
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
displayTitle,
|
||||
groupReservations,
|
||||
groupTransports,
|
||||
hasPassed,
|
||||
onTravelers,
|
||||
parseMeta,
|
||||
phaseOf,
|
||||
@@ -394,4 +395,48 @@ describe('onTravelers and the shared type colours', () => {
|
||||
expect(groups.transit.map(r => r.id)).toEqual([1]);
|
||||
expect(sortReservations([later, transit, open, sooner], days, 'date', 'asc', label).map(r => r.id)).toEqual([1, 3, 2, 4]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-044: hasPassed reads the end, else the start, in local wall-clock time', () => {
|
||||
const now = new Date(2025, 5, 2, 12, 0);
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T11:00' }), now)).toBe(true);
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T13:00' }), now)).toBe(false);
|
||||
// The end counts: a flight that left in the morning and lands this afternoon is not over.
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T08:00', reservation_end_time: '2025-06-02T15:00' }), now)).toBe(false);
|
||||
// An end time without a date is on the start's day.
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T08:00', reservation_end_time: '11:30' }), now)).toBe(true);
|
||||
// A date without a time lasts until the day is over.
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02' }), now)).toBe(false);
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-01' }), now)).toBe(true);
|
||||
// Without any date nothing says it is over.
|
||||
expect(hasPassed(buildReservation({ reservation_time: null, day_id: null }), now)).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-045: groupTransports moves what is over into past, latest first, only when given the time', () => {
|
||||
const early = buildReservation({ id: 1, type: 'train', status: 'confirmed', reservation_time: '2025-06-01T09:00' });
|
||||
const lastNight = buildReservation({ id: 2, type: 'transit', status: 'pending', reservation_time: '2025-06-01T21:00' });
|
||||
const ahead = buildReservation({ id: 3, type: 'bus', status: 'confirmed', reservation_time: '2025-06-03T09:00' });
|
||||
const now = new Date(2025, 5, 2, 12, 0);
|
||||
const groups = groupTransports([ahead, early, lastNight], days, now);
|
||||
expect(groups.confirmed.map(r => r.id)).toEqual([3]);
|
||||
expect(groups.transit).toEqual([]);
|
||||
expect(groups.past.map(r => r.id)).toEqual([2, 1]);
|
||||
expect(groupTransports([ahead, early, lastNight], days).past).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-046: hasPassed takes the linked days when a booking carries no date of its own', () => {
|
||||
const now = new Date(2025, 5, 3, 12, 0);
|
||||
const hotel = buildReservation({ id: 1, type: 'hotel', status: 'confirmed', reservation_time: null, reservation_end_time: null, accommodation_start_day_id: 501, accommodation_end_day_id: 502 });
|
||||
const stillThere = buildReservation({ id: 2, type: 'hotel', status: 'confirmed', reservation_time: null, reservation_end_time: null, accommodation_start_day_id: 502, accommodation_end_day_id: 503 });
|
||||
const train = buildReservation({ id: 3, type: 'train', status: 'confirmed', reservation_time: '09:00', reservation_end_time: '11:00', day_id: 503 });
|
||||
const lateTrain = buildReservation({ id: 4, type: 'train', status: 'confirmed', reservation_time: '13:00', day_id: 503 });
|
||||
const overnight = buildReservation({ id: 5, type: 'bus', status: 'confirmed', reservation_time: '22:00', reservation_end_time: '06:00', day_id: 502, end_day_id: 503 });
|
||||
expect(hasPassed(hotel, now, days)).toBe(true);
|
||||
expect(hasPassed(stillThere, now, days)).toBe(false);
|
||||
expect(hasPassed(train, now, days)).toBe(true);
|
||||
expect(hasPassed(lateTrain, now, days)).toBe(false);
|
||||
expect(hasPassed(overnight, now, days)).toBe(true);
|
||||
const groups = groupTransports([hotel, stillThere, train, lateTrain, overnight], days, now);
|
||||
expect(groups.past.map(r => r.id)).toEqual([3, 5, 1]);
|
||||
expect(groups.confirmed.map(r => r.id)).toEqual([2, 4]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -252,21 +252,49 @@ export interface StatusGroups {
|
||||
confirmed: Reservation[]
|
||||
pending: Reservation[]
|
||||
transit: Reservation[]
|
||||
/** What is over already (#3156), latest first; empty unless the caller passes the time. */
|
||||
past: Reservation[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone tabs' three sections, each in date order: confirmed and pending, and
|
||||
* Whether a booking is over: its end, or its start where it has none, lies
|
||||
* before `now`. The times are local wall-clock values, as everywhere a booking
|
||||
* is read. An end time without a date is on the start's day, and a date
|
||||
* without a time counts until that day is over. A booking that carries no date
|
||||
* of its own takes them from bookingDates, so a hotel ends on its stay's last
|
||||
* day and a day-linked transport on its day. Without any date it is never over.
|
||||
*/
|
||||
export function hasPassed(r: Reservation, now: Date, days: Day[] = []): boolean {
|
||||
const start = splitReservationDateTime(r.reservation_time)
|
||||
const end = r.reservation_end_time ? splitReservationDateTime(r.reservation_end_time) : null
|
||||
const own = end?.date || start.date
|
||||
const linked = own ? null : bookingDates(r, days)
|
||||
const endDate = own ? end?.date : linked?.end
|
||||
const date = endDate || (own ? start.date : linked?.start)
|
||||
if (!date) return false
|
||||
const time = endDate || end?.time ? (end?.time ?? null) : start.time
|
||||
const [y, m, d] = date.split('-').map(Number)
|
||||
const [hh, mm] = time ? time.split(':').map(Number) : [23, 59]
|
||||
return new Date(y, m - 1, d, hh, mm) < now
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone tabs' sections, each in date order: confirmed and pending, and
|
||||
* transit (automated public transport, #1065) on its own whatever its status.
|
||||
* A booking type never matches `transit`, so the split fits the bookings tab too.
|
||||
* Given the time, what is over leaves those and stands in `past` (#3156).
|
||||
*/
|
||||
export function groupTransports(list: Reservation[], days: Day[]): StatusGroups {
|
||||
export function groupTransports(list: Reservation[], days: Day[], now?: Date): StatusGroups {
|
||||
const sorted = sortReservations(list, days, 'date', 'asc', () => '')
|
||||
const transit = sorted.filter(r => r.type === 'transit')
|
||||
const nonTransit = sorted.filter(r => r.type !== 'transit')
|
||||
const isPast = (r: Reservation) => !!now && hasPassed(r, now, days)
|
||||
const current = sorted.filter(r => !isPast(r))
|
||||
const transit = current.filter(r => r.type === 'transit')
|
||||
const nonTransit = current.filter(r => r.type !== 'transit')
|
||||
return {
|
||||
confirmed: nonTransit.filter(r => r.status === 'confirmed'),
|
||||
pending: nonTransit.filter(r => r.status !== 'confirmed'),
|
||||
transit,
|
||||
past: sorted.filter(isPast).reverse(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// FE-PLANNER-RESLISTFILTER-001 to -004: the traveller filter and folded sections
|
||||
// FE-PLANNER-RESLISTFILTER-001 to -005: the traveller filter and folded sections
|
||||
// of the phone's bookings and transports tabs.
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildDay, buildReservation } from '../../../../tests/helpers/factories';
|
||||
import type { Reservation } from '../../../types';
|
||||
@@ -24,6 +24,14 @@ const bob = buildReservation({
|
||||
const ride = buildReservation({ id: 12, type: 'transit', status: 'confirmed', reservation_time: '2026-03-01T07:00' });
|
||||
const ALL = [ann, bob, ride];
|
||||
|
||||
// The day before the trip: every booking above is still ahead.
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ['Date'], now: new Date(2026, 1, 28, 12, 0) });
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('useReservationListFilter', () => {
|
||||
it('FE-PLANNER-RESLISTFILTER-001: without a filter every booking lands in its status section', () => {
|
||||
const { result } = renderHook(() => useReservationListFilter(ALL, days, 2));
|
||||
@@ -37,7 +45,7 @@ describe('useReservationListFilter', () => {
|
||||
const { result } = renderHook(() => useReservationListFilter(ALL, days, 2));
|
||||
act(() => result.current.toggleTravelerFilter(2));
|
||||
expect([...result.current.travelerFilter]).toEqual([2]);
|
||||
expect(result.current.groups).toEqual({ confirmed: [], pending: [bob], transit: [] });
|
||||
expect(result.current.groups).toEqual({ confirmed: [], pending: [bob], transit: [], past: [] });
|
||||
|
||||
act(() => result.current.toggleTravelerFilter(1));
|
||||
expect(result.current.groups.confirmed.map((r) => r.id)).toEqual([10]);
|
||||
@@ -58,9 +66,24 @@ describe('useReservationListFilter', () => {
|
||||
it('FE-PLANNER-RESLISTFILTER-004: a section folds and unfolds on its own', () => {
|
||||
const { result } = renderHook(() => useReservationListFilter(ALL, days, 2));
|
||||
act(() => result.current.toggleSection('pending'));
|
||||
expect(result.current.collapsed).toEqual({ pending: true });
|
||||
expect(result.current.collapsed).toEqual({ pending: true, past: true });
|
||||
act(() => result.current.toggleSection('confirmed'));
|
||||
act(() => result.current.toggleSection('pending'));
|
||||
expect(result.current.collapsed).toEqual({ pending: false, confirmed: true });
|
||||
expect(result.current.collapsed).toEqual({ pending: false, confirmed: true, past: true });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESLISTFILTER-005: what is over goes to Past, folded while something is ahead and open once all is over', () => {
|
||||
vi.setSystemTime(new Date(2026, 2, 1, 12, 0));
|
||||
const midTrip = renderHook(() => useReservationListFilter(ALL, days, 2)).result;
|
||||
expect(midTrip.current.groups.past.map((r) => r.id)).toEqual([11, 12]);
|
||||
expect(midTrip.current.groups.confirmed.map((r) => r.id)).toEqual([10]);
|
||||
expect(midTrip.current.collapsed.past).toBe(true);
|
||||
act(() => midTrip.current.toggleSection('past'));
|
||||
expect(midTrip.current.collapsed.past).toBe(false);
|
||||
|
||||
vi.setSystemTime(new Date(2026, 2, 3, 12, 0));
|
||||
const afterTrip = renderHook(() => useReservationListFilter(ALL, days, 2)).result;
|
||||
expect(afterTrip.current.groups.past.map((r) => r.id)).toEqual([10, 11, 12]);
|
||||
expect(afterTrip.current.collapsed.past).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import type { Day, Reservation } from '../../../types';
|
||||
import { groupTransports, onTravelers } from './bookingsModel';
|
||||
import { groupTransports, onTravelers, type StatusGroups } from './bookingsModel';
|
||||
|
||||
/**
|
||||
* The status sections both tabs list, in their order, leaving out the empty ones.
|
||||
* Bookings never fill `transit`, so that section only ever shows among transports.
|
||||
*/
|
||||
export function listSections(groups: StatusGroups, t: (key: string) => string) {
|
||||
return [
|
||||
{ id: 'confirmed', label: t('reservations.confirmed'), rows: groups.confirmed },
|
||||
{ id: 'pending', label: t('reservations.pending'), rows: groups.pending },
|
||||
{ id: 'transit', label: t('reservations.type.transit'), rows: groups.transit },
|
||||
{ id: 'past', label: t('reservations.past'), rows: groups.past },
|
||||
].filter((s) => s.rows.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* The traveller filter and the folded sections of the phone's bookings and
|
||||
@@ -15,9 +28,13 @@ import { groupTransports, onTravelers } from './bookingsModel';
|
||||
*/
|
||||
export function useReservationListFilter(all: Reservation[], days: Day[], memberCount: number) {
|
||||
const [travelerFilter, setTravelerFilter] = useState<Set<number>>(new Set());
|
||||
// The moment the tab opened: what was over by then moves into the folded Past
|
||||
// section (#3156). Taken once, so a list does not reshuffle while it is read.
|
||||
const [now] = useState(() => new Date());
|
||||
const groups = groupTransports(
|
||||
all.filter((r) => onTravelers(r, travelerFilter)),
|
||||
days
|
||||
days,
|
||||
now
|
||||
);
|
||||
const showTravelerFilter = memberCount > 1 && all.some((r) => (r.travelers || []).length > 0);
|
||||
const toggleTravelerFilter = (id: number) =>
|
||||
@@ -29,8 +46,12 @@ export function useReservationListFilter(all: Reservation[], days: Day[], member
|
||||
});
|
||||
const clearTravelerFilter = () => setTravelerFilter(new Set());
|
||||
|
||||
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
|
||||
const toggleSection = (id: string) => setCollapsed((c) => ({ ...c, [id]: !c[id] }));
|
||||
const [folded, setFolded] = useState<Record<string, boolean>>({});
|
||||
// Past starts folded while something is still ahead, since mid-trip that is
|
||||
// what counts; once the whole trip is over it opens, to look back on.
|
||||
const ahead = groups.confirmed.length + groups.pending.length + groups.transit.length > 0;
|
||||
const collapsed: Record<string, boolean> = { ...folded, past: folded.past ?? ahead };
|
||||
const toggleSection = (id: string) => setFolded((c) => ({ ...c, [id]: !collapsed[id] }));
|
||||
|
||||
return {
|
||||
travelerFilter,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { BookingImportPreviewItem } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { parsedItemToDraft } from './parsedItemToDraft';
|
||||
|
||||
const item = (metadata?: Record<string, unknown>): BookingImportPreviewItem => ({
|
||||
type: 'flight',
|
||||
title: 'Kuala Lumpur to Bangkok',
|
||||
metadata,
|
||||
source: { fileName: 'airasia.eml', index: 0 },
|
||||
});
|
||||
|
||||
describe('parsedItemToDraft', () => {
|
||||
// #3238: the review form opens with the status the document states.
|
||||
it('FE-PARSED-DRAFT-001: a booking the document calls confirmed opens confirmed, anything else pending', () => {
|
||||
expect(parsedItemToDraft(item({ reservationStatus: 'confirmed' })).status).toBe('confirmed');
|
||||
expect(parsedItemToDraft(item({ reservationStatus: 'cancelled' })).status).toBe('pending');
|
||||
expect(parsedItemToDraft(item({ reservationStatus: 'pending' })).status).toBe('pending');
|
||||
expect(parsedItemToDraft(item()).status).toBe('pending');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BookingImportPreviewItem, Reservation, ReservationEndpoint } from '@trek/shared'
|
||||
import { importedReservationStatus, type BookingImportPreviewItem, type Reservation, type ReservationEndpoint } from '@trek/shared'
|
||||
|
||||
/**
|
||||
* A pre-fill draft for the reservation/transport edit modals built from a parsed
|
||||
@@ -29,7 +29,8 @@ export function parsedItemToDraft(item: BookingImportPreviewItem): BookingReview
|
||||
return {
|
||||
type: item.type,
|
||||
title: item.title,
|
||||
status: 'pending',
|
||||
// Confirmed when the document said so, pending otherwise (#3238).
|
||||
status: importedReservationStatus(item.metadata),
|
||||
reservation_time: item.reservation_time ?? null,
|
||||
reservation_end_time: item.reservation_end_time ?? null,
|
||||
location: item.location ?? item._venue?.address ?? item._venue?.name ?? null,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// FE-PLANNER-STOPNUM-001 to -002: the one stop count the map's pins and the plan's rows read (#2584).
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { Assignment } from '../../types';
|
||||
import { stopNumbersOfDay } from './stopNumbers';
|
||||
|
||||
const stop = (id: number, order_index: number, place: Partial<NonNullable<Assignment['place']>> | null = {}) =>
|
||||
({ id, order_index, place: place && { id: id * 10, ...place } }) as unknown as Assignment;
|
||||
|
||||
describe('stopNumbersOfDay', () => {
|
||||
it('FE-PLANNER-STOPNUM-001: numbers the stops from 1 in their stored order', () => {
|
||||
const numbers = stopNumbersOfDay([stop(3, 2), stop(1, 0), stop(2, 1)]);
|
||||
expect([...numbers.entries()]).toEqual([
|
||||
[1, 1],
|
||||
[2, 2],
|
||||
[3, 3],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-STOPNUM-002: passes over service stops and rows without a place', () => {
|
||||
const numbers = stopNumbersOfDay([stop(1, 0), stop(2, 1, { stop_type: 'fuel' }), stop(3, 2, null), stop(4, 3)]);
|
||||
expect(numbers.get(1)).toBe(1);
|
||||
expect(numbers.has(2)).toBe(false);
|
||||
expect(numbers.has(3)).toBe(false);
|
||||
expect(numbers.get(4)).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Assignment } from '../../types';
|
||||
import { isServiceStopType } from '../Roadtrip/roadtripModel';
|
||||
|
||||
/**
|
||||
* The number each stop of a day carries, by assignment id: counted from 1 in the
|
||||
* day's stored order. A service stop is passed over rather than counted: the map
|
||||
* draws it without a badge and the rail gives it no number, so a number spent on
|
||||
* it left the pin after a fuel stop wearing "3" where the rail said "2".
|
||||
*
|
||||
* The one count the map's pins and the plan's rows both read (#2584), so the
|
||||
* number beside a stop in the list is the one on its pin.
|
||||
*/
|
||||
export function stopNumbersOfDay(dayAssignments: readonly Assignment[]): Map<number, number> {
|
||||
const numbers = new Map<number, number>();
|
||||
let counted = 0;
|
||||
for (const a of [...dayAssignments].sort((x, y) => x.order_index - y.order_index)) {
|
||||
if (!a.place?.id || isServiceStopType(a.place.stop_type)) continue;
|
||||
counted += 1;
|
||||
numbers.set(a.id, counted);
|
||||
}
|
||||
return numbers;
|
||||
}
|
||||
@@ -60,6 +60,8 @@ export interface PlaceSearchOptions {
|
||||
* search ends the billing session, and a pick clears the typed-ahead list too.
|
||||
*/
|
||||
variant: 'dialog' | 'sheet';
|
||||
/** What the field starts with, such as a map link shared to the app (#2582). */
|
||||
initialQuery?: string;
|
||||
/** Where the trip is happening: autocomplete is biased to the box, the full search to its centre. */
|
||||
locationBias: LocationBiasBox | undefined;
|
||||
t: ReturnType<typeof useTranslation>['t'];
|
||||
@@ -101,6 +103,7 @@ export function usePlaceSearch({
|
||||
onMapLink,
|
||||
onCoordinates,
|
||||
onResolvingChange,
|
||||
initialQuery,
|
||||
}: PlaceSearchOptions) {
|
||||
const sheet = variant === 'sheet';
|
||||
// Place names in the language the user picked for them, the app's otherwise (#1799).
|
||||
@@ -110,7 +113,7 @@ export function usePlaceSearch({
|
||||
// The same hint autocomplete gets, as a point instead of a box.
|
||||
const biasPoint = pointFromBox(locationBias);
|
||||
|
||||
const [query, setQuery] = useState('');
|
||||
const [query, setQuery] = useState(initialQuery ?? '');
|
||||
const [results, setResults] = useState<MapsSearchRow[]>([]);
|
||||
/** What answered the last full search. Only a fallback: a merged list carries the source per place. */
|
||||
const [searchSource, setSearchSource] = useState('');
|
||||
@@ -265,11 +268,12 @@ export function usePlaceSearch({
|
||||
const pickPlace = (place: MapsPlace, pick?: PlaceSearchPick) =>
|
||||
take(place, pick, sourceLabel(place, pick?.mode === 'search' ? searchSource : ''));
|
||||
|
||||
const runSearch = async (provider?: 'google') => {
|
||||
const runSearch = async (provider?: 'google', text?: string) => {
|
||||
// The retry sends the query the list came from, not the field: the list
|
||||
// stays on screen while the field is edited or cleared, and the line under
|
||||
// it promises the same query.
|
||||
const trimmed = provider ? (searchMetaRef.current?.query ?? '') : query.trim();
|
||||
// it promises the same query. A link shared into an open sheet is searched
|
||||
// as given, before the field shows it.
|
||||
const trimmed = provider ? (searchMetaRef.current?.query ?? '') : (text ?? query).trim();
|
||||
if (!trimmed) return;
|
||||
if (sheet) {
|
||||
setSuggestions([]);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// FE-COMP-PLUGIN-USERSET-001 to -012: the per plugin user settings logic both settings shells share.
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { locationAt } from '../../../tests/helpers/location';
|
||||
import { pluginsApi, type PluginAction, type PluginUserSettingField } from '../../api/client';
|
||||
import { SECRET_MASK } from './settingsForm';
|
||||
import { usePluginOAuth, usePluginUserSettings } from './usePluginUserSettings';
|
||||
@@ -150,7 +151,7 @@ describe('usePluginOAuth', () => {
|
||||
|
||||
it('FE-COMP-PLUGIN-USERSET-012: a connect hands off to the provider and keeps the button busy', async () => {
|
||||
const realLocation = window.location;
|
||||
const loc = { href: 'http://localhost/settings' };
|
||||
const loc = locationAt('/settings');
|
||||
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: loc });
|
||||
try {
|
||||
vi.spyOn(pluginsApi, 'oauthConnect').mockResolvedValue({
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-008
|
||||
// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-006
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import MSettingsServer from '../../mobile/screens/settings/MSettingsServer';
|
||||
import { nativeServerHost } from '../../native/platform';
|
||||
import { TrekShell } from '../../native/trekShell';
|
||||
import NativeServerLink from '../../pages/login/NativeServerLink';
|
||||
import NativeServerSection from './NativeServerSection';
|
||||
|
||||
vi.mock('../../native/platform', () => ({ nativeServerHost: vi.fn() }));
|
||||
@@ -40,18 +39,3 @@ describe.each([
|
||||
expect(link).toHaveAttribute('target', '_blank');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the sign-in screen link', () => {
|
||||
it('renders nothing in a browser', () => {
|
||||
vi.mocked(nativeServerHost).mockReturnValue(null);
|
||||
const { container } = render(<NativeServerLink />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('leads back to the address screen in the app', () => {
|
||||
vi.mocked(nativeServerHost).mockReturnValue('trek.example.com');
|
||||
render(<NativeServerLink />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change server' }));
|
||||
expect(TrekShell.resetServer).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { locationAt } from '../../../tests/helpers/location';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore';
|
||||
import type { PluginAction, PluginUserSettingField } from '../../api/client';
|
||||
@@ -367,7 +368,7 @@ describe('PluginSettingsTab', () => {
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-020: an OAuth-only plugin gets a card and Connect hands off to the provider', async () => {
|
||||
const user = userEvent.setup();
|
||||
const loc = { href: 'http://localhost/settings', origin: 'http://localhost', pathname: '/settings' };
|
||||
const loc = locationAt('/settings');
|
||||
vi.stubGlobal('location', loc);
|
||||
serve('weather', {}, { configured: true, connected: false });
|
||||
server.use(http.post('/api/plugin-oauth/weather/connect', () =>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// FE-SETTINGS-TRIPOFFLINE-001: where a trip stands on this device, for its menu (#1580).
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { tripOfflineState } from './useTripOfflineStatus';
|
||||
|
||||
describe('tripOfflineState', () => {
|
||||
it('FE-SETTINGS-TRIPOFFLINE-001: off when switched off or not kept, saved as of the last sync, else pending', () => {
|
||||
expect(tripOfflineState(false, true, 1000)).toEqual({ kind: 'off' });
|
||||
expect(tripOfflineState(true, false, 1000)).toEqual({ kind: 'off' });
|
||||
expect(tripOfflineState(true, true, 1000)).toEqual({ kind: 'saved', at: 1000 });
|
||||
expect(tripOfflineState(true, true, null)).toEqual({ kind: 'pending' });
|
||||
expect(tripOfflineState(true, true, undefined)).toEqual({ kind: 'pending' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { offlineDb } from '../../db/offlineDb';
|
||||
import { isTripOfflineEnabled, isTripPinned } from '../../sync/offlinePrefs';
|
||||
import { isDateEligible } from '../../sync/tripSyncManager';
|
||||
import type { Trip } from '../../types';
|
||||
|
||||
/** Where a trip stands on this device (#1580), as the trip's own menu says it. */
|
||||
export type TripOfflineState = { kind: 'saved'; at: number } | { kind: 'pending' } | { kind: 'off' };
|
||||
|
||||
/**
|
||||
* The trip's state from what decides it: switched off, or kept by neither the
|
||||
* date rule nor a pin, it is not on the device; synced before, it is, as of then;
|
||||
* otherwise the next sync brings it.
|
||||
*/
|
||||
export function tripOfflineState(
|
||||
enabled: boolean,
|
||||
kept: boolean,
|
||||
lastSyncedAt: number | null | undefined
|
||||
): TripOfflineState {
|
||||
if (!enabled || !kept) return { kind: 'off' };
|
||||
if (lastSyncedAt) return { kind: 'saved', at: lastSyncedAt };
|
||||
return { kind: 'pending' };
|
||||
}
|
||||
|
||||
/**
|
||||
* The offline state of one trip, read again each time `active` turns on (the
|
||||
* menu opening), so it shows the last sync rather than the one before it.
|
||||
*/
|
||||
export function useTripOfflineStatus(trip: Trip | null | undefined, active: boolean): TripOfflineState | null {
|
||||
const [state, setState] = useState<TripOfflineState | null>(null);
|
||||
useEffect(() => {
|
||||
if (!active || !trip) return;
|
||||
let cancelled = false;
|
||||
const enabled = isTripOfflineEnabled(trip.id);
|
||||
const kept = isTripPinned(trip.id) || isDateEligible(trip);
|
||||
void offlineDb.syncMeta.get(trip.id).then(
|
||||
(meta) => {
|
||||
if (!cancelled) setState(tripOfflineState(enabled, kept, meta?.lastSyncedAt));
|
||||
},
|
||||
// An unreadable store says nothing about the trip: the line stays away.
|
||||
() => {
|
||||
if (!cancelled) setState(null);
|
||||
}
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [trip, active]);
|
||||
return state;
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import type { Day } from '../../../types'
|
||||
import { toggleTourPlacing } from '../../../store/tourPlaceToolStore'
|
||||
import { publishTourFerrataCrossings } from '../../../store/tourFerrataCrossingStore'
|
||||
import { TourPlannerRail, TourPlannerToursRail } from './TourPlannerPanels'
|
||||
import { hikePlannerDefaults } from '../../../../tests/helpers/tourPlannerStub'
|
||||
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../../tests/helpers/tourPlannerStub'
|
||||
import { tourRepo } from '../../../repo/tourRepo'
|
||||
import { useTripStore } from '../../../store/tripStore'
|
||||
import type { TourStage } from '../stages/tourStages'
|
||||
@@ -132,6 +132,12 @@ beforeEach(() => {
|
||||
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
|
||||
})
|
||||
|
||||
function openDifficulty() {
|
||||
const trigger = screen.getByRole('button', { name: 'Maximum trail difficulty' })
|
||||
mockTourEditorLayout(trigger.parentElement ?? trigger)
|
||||
fireEvent.click(trigger)
|
||||
}
|
||||
|
||||
describe('TourPlannerToursRail', () => {
|
||||
it('MDT-02: a multi-day tour unfolds its stages in the list, a day tour has nothing to unfold', async () => {
|
||||
vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour, waypoints: [] })
|
||||
@@ -702,6 +708,7 @@ describe('TourPlannerRail', () => {
|
||||
render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
expect(screen.getByLabelText('Tour name')).toBeDisabled()
|
||||
expect(screen.getByTestId('tour-type-select')).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Maximum trail difficulty' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Back to Tours' })).toBeDisabled()
|
||||
@@ -765,7 +772,7 @@ describe('TourPlannerRail', () => {
|
||||
const controller = planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty, acknowledgeAlpine: acknowledge })
|
||||
const { unmount } = render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
openDifficulty()
|
||||
fireEvent.click(screen.getByRole('button', { name: /T4: Alpine hiking/ }))
|
||||
expect(screen.getByRole('heading', { name: 'Enable alpine routing?' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Enable alpine routing' }))
|
||||
@@ -775,7 +782,7 @@ describe('TourPlannerRail', () => {
|
||||
|
||||
// The planner remembers the answer, so a rail that mounts anew does not ask again.
|
||||
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty, alpineAcknowledged: true })} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
openDifficulty()
|
||||
fireEvent.click(screen.getByRole('button', { name: /T5: Demanding alpine hiking/ }))
|
||||
expect(screen.queryByRole('heading', { name: 'Enable alpine routing?' })).not.toBeInTheDocument()
|
||||
expect(setDifficulty).toHaveBeenLastCalledWith(5)
|
||||
@@ -785,7 +792,7 @@ describe('TourPlannerRail', () => {
|
||||
const setDifficulty = vi.fn()
|
||||
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty })} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
openDifficulty()
|
||||
fireEvent.click(screen.getByRole('button', { name: /T4: Alpine hiking/ }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(setDifficulty).not.toHaveBeenCalled()
|
||||
@@ -802,7 +809,7 @@ describe('TourPlannerRail', () => {
|
||||
})} />
|
||||
}
|
||||
render(<StatefulDifficultyRail />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
openDifficulty()
|
||||
|
||||
for (const label of [
|
||||
'T1: Hiking',
|
||||
@@ -818,6 +825,22 @@ describe('TourPlannerRail', () => {
|
||||
expect(screen.getAllByRole('status').some(el => /T3 routes may include exposed/.test(el.textContent ?? ''))).toBe(true)
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-024: an open tour type list closes when saving locks the editor', () => {
|
||||
const controller = planner({ mode: { type: 'new-draft' } })
|
||||
const { rerender } = render(<TourPlannerRail planner={controller} />)
|
||||
const trigger = screen.getByTestId('tour-type-select')
|
||||
mockTourEditorLayout(trigger)
|
||||
fireEvent.click(trigger)
|
||||
expect(screen.getByRole('group', { name: 'Tour type' })).toBeInTheDocument()
|
||||
|
||||
rerender(<TourPlannerRail planner={{ ...controller, isSaving: true }} />)
|
||||
expect(trigger).toBeDisabled()
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(screen.queryByTestId('tour-type-option-hike')).not.toBeInTheDocument()
|
||||
rerender(<TourPlannerRail planner={controller} />)
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'false')
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-009: neutral shows only the Plan new entry and new-draft guidance hides after the first waypoint', () => {
|
||||
const controller = planner({ mode: { type: 'neutral' } })
|
||||
const { rerender } = render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useRailHeadProps } from './railHead'
|
||||
import EmptyState from '../../shared/EmptyState'
|
||||
import { useToast } from '../../shared/Toast'
|
||||
import { Tooltip } from '../../shared/Tooltip'
|
||||
import { PopoverBoundary } from '../../shared/useAnchoredPopover'
|
||||
import { BOX } from '../../Planner/bookings/bookingParts'
|
||||
import { BarButton, SoftPill } from '../../Planner/planParts'
|
||||
import TourListRow from '../TourListRow'
|
||||
@@ -335,6 +336,7 @@ export function TourPlannerRail({ planner,
|
||||
const { t } = useTranslation()
|
||||
const [confirmDiscard, setConfirmDiscard] = useState(false)
|
||||
const [pendingDifficulty, setPendingDifficulty] = useState<1 | 2 | 3 | 4 | 5 | 6 | null>(null)
|
||||
const editorScrollRef = useRef<HTMLDivElement>(null)
|
||||
const isSaving = planner.isSaving
|
||||
// Nothing in the editor changes while the viewer may not edit or a save is in flight.
|
||||
const locked = !canEdit || isSaving
|
||||
@@ -389,44 +391,46 @@ export function TourPlannerRail({ planner,
|
||||
</BarButton>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
|
||||
<TourRemoteChangeNotice planner={planner} />
|
||||
<WalkImportDraftNotice planner={planner} />
|
||||
<WalkRoutePendingNotice planner={planner} />
|
||||
<TourNameField planner={planner} locked={locked} />
|
||||
<div ref={editorScrollRef} data-testid="tour-planner-editor-scroll" className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
|
||||
<PopoverBoundary value={editorScrollRef}>
|
||||
<TourRemoteChangeNotice planner={planner} />
|
||||
<WalkImportDraftNotice planner={planner} />
|
||||
<WalkRoutePendingNotice planner={planner} />
|
||||
<TourNameField planner={planner} locked={locked} />
|
||||
|
||||
<TourTypeFields planner={planner} locked={locked} />
|
||||
<TourTypeFields planner={planner} locked={locked} />
|
||||
|
||||
<TourStageModeField planner={planner} locked={locked} />
|
||||
<TourStageModeField planner={planner} locked={locked} />
|
||||
|
||||
{recordedTrack?.available && <RecordedTrackCard recordedTrack={recordedTrack} disabled={isSaving} />}
|
||||
{recordedTrack?.available && <RecordedTrackCard recordedTrack={recordedTrack} disabled={isSaving} />}
|
||||
|
||||
<UnreachableNotice planner={planner} />
|
||||
<WalkFerryNotice planner={planner} />
|
||||
<UnreachableNotice planner={planner} />
|
||||
<WalkFerryNotice planner={planner} />
|
||||
|
||||
<TourStageLossNotice planner={planner} />
|
||||
<TourStageDayNotice planner={planner} />
|
||||
<TourStageLossNotice planner={planner} />
|
||||
<TourStageDayNotice planner={planner} />
|
||||
|
||||
<TourWaypointList planner={planner} canEdit={canEdit} isSaving={isSaving} tourPlaceIds={tourPlaceIds} />
|
||||
<TourWaypointList planner={planner} canEdit={canEdit} isSaving={isSaving} tourPlaceIds={tourPlaceIds} />
|
||||
|
||||
<BikeWaysCard planner={planner} />
|
||||
<BikeWaysCard planner={planner} />
|
||||
|
||||
<RunWaysCard planner={planner} />
|
||||
<RunWaysCard planner={planner} />
|
||||
|
||||
<HorseRoutesCard planner={planner} />
|
||||
<HorseRoutesCard planner={planner} />
|
||||
|
||||
<SkiPlannerSummary planner={planner} />
|
||||
<SkiPlannerSummary planner={planner} />
|
||||
|
||||
{planner.tourType === 'hike' && (
|
||||
<HikeWaysCard tripId={planner.tripId} route={planner.route} routeCurrent={planner.routeCurrent}
|
||||
routingLimit={planner.maxHikingDifficulty} />
|
||||
)}
|
||||
{planner.tourType === 'hike' && (
|
||||
<HikeWaysCard tripId={planner.tripId} route={planner.route} routeCurrent={planner.routeCurrent}
|
||||
routingLimit={planner.maxHikingDifficulty} />
|
||||
)}
|
||||
|
||||
<TourPoiSearchCard planner={planner} />
|
||||
<TourPoiSearchCard planner={planner} />
|
||||
|
||||
<PaddleEditorCards planner={planner} locked={locked} checklist={paddleChecklist} />
|
||||
<PaddleEditorCards planner={planner} locked={locked} checklist={paddleChecklist} />
|
||||
|
||||
<TourDetailsSection planner={planner} locked={locked} onDifficultyChange={changeDifficulty} />
|
||||
<TourDetailsSection planner={planner} locked={locked} onDifficultyChange={changeDifficulty} />
|
||||
</PopoverBoundary>
|
||||
</div>
|
||||
|
||||
<TourEditorRailFooter planner={planner} canEdit={canEdit} locked={locked} isSavedEdit={isSavedEdit} onDiscard={requestClose} />
|
||||
|
||||
@@ -111,7 +111,7 @@ function BikeProfileField({ planner }: { planner: TourPlannerController }) {
|
||||
* discipline and, for cross-country, the technique, then what the piste router
|
||||
* is asked for. A short line says how its legs are laid.
|
||||
*/
|
||||
function SkiFields({ planner }: { planner: TourPlannerController }) {
|
||||
function SkiFields({ planner, locked }: TourTypeFieldsProps) {
|
||||
const { t } = useTranslation();
|
||||
const { choice } = planner.ski;
|
||||
return (
|
||||
@@ -121,7 +121,12 @@ function SkiFields({ planner }: { planner: TourPlannerController }) {
|
||||
{t('tours.ski.plannedHint')}
|
||||
</span>
|
||||
{choice.discipline !== null && (
|
||||
<SkiRouteOptions discipline={choice.discipline} options={choice.options} onChange={planner.ski.setOption} />
|
||||
<SkiRouteOptions
|
||||
discipline={choice.discipline}
|
||||
options={choice.options}
|
||||
onChange={planner.ski.setOption}
|
||||
locked={locked}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -157,7 +162,7 @@ export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) {
|
||||
|
||||
{planner.isRun && <RunFields planner={planner} locked={locked} />}
|
||||
|
||||
{planner.isSki && <SkiFields planner={planner} />}
|
||||
{planner.isSki && <SkiFields planner={planner} locked={locked} />}
|
||||
|
||||
{planner.isPaddle && (
|
||||
<div data-testid="tour-planner-paddle-fields" className="flex min-w-0 flex-col gap-3">
|
||||
|
||||
@@ -47,7 +47,10 @@ export function TourTypeSelect<T extends ImportableTourType = PlannableTourType>
|
||||
const { t } = useTranslation();
|
||||
const valueId = useId();
|
||||
const offered: readonly ImportableTourType[] = types ?? PLANNER_TOUR_TYPES;
|
||||
const list = usePopoverList(offered.indexOf(value), { estimatedHeight: 50 * offered.length + 20 });
|
||||
const list = usePopoverList(offered.indexOf(value), {
|
||||
estimatedHeight: 50 * offered.length + 20,
|
||||
disabled,
|
||||
});
|
||||
const { open, toggle, triggerRef, listId } = list;
|
||||
const label = t('tours.planner.tourType');
|
||||
const pick = (type: T) => {
|
||||
|
||||
@@ -47,6 +47,7 @@ interface SkiRouteOptionsProps {
|
||||
discipline: SkiDiscipline;
|
||||
options: SkiRouteOptionsInput | null | undefined;
|
||||
onChange: (patch: Partial<SkiRouteOptionsInput>) => void;
|
||||
locked?: boolean;
|
||||
}
|
||||
|
||||
/** One switch of the piste router on its own row, its label beside it. */
|
||||
@@ -102,7 +103,7 @@ function LiftClasses({ avoided, onChange }: { avoided: SkiLiftClass[]; onChange:
|
||||
* weigh most for a downhill skier, groomed and lit trails for cross-country,
|
||||
* the lifts for anyone who rides them. Every change plans the tour again.
|
||||
*/
|
||||
export function SkiRouteOptions({ discipline, options, onChange }: SkiRouteOptionsProps) {
|
||||
export function SkiRouteOptions({ discipline, options, onChange, locked }: SkiRouteOptionsProps) {
|
||||
const { t } = useTranslation();
|
||||
const read = new Set(skiOptionsReadBy(discipline));
|
||||
const current: Options = { ...DEFAULT_SKI_ROUTE_OPTIONS, ...options };
|
||||
@@ -119,6 +120,7 @@ export function SkiRouteOptions({ discipline, options, onChange }: SkiRouteOptio
|
||||
<CustomSelect
|
||||
id="tour-planner-ski-difficulty"
|
||||
ariaLabel={t('tours.ski.options.maxDifficulty')}
|
||||
disabled={locked}
|
||||
size="sm"
|
||||
value={current.max_difficulty}
|
||||
onChange={(value) => onChange({ max_difficulty: value as SkiDifficulty })}
|
||||
|
||||
@@ -11,7 +11,7 @@ import { analyzeRouteGeometry } from '../../utils/routeGeometry'
|
||||
import TourListRow from './TourListRow'
|
||||
import { TourPlannerRail, TourPlannerToursRail } from './planner/TourPlannerPanels'
|
||||
import type { TourPlannerController } from './planner/useTourPlanner'
|
||||
import { hikePlannerDefaults } from '../../../tests/helpers/tourPlannerStub'
|
||||
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../tests/helpers/tourPlannerStub'
|
||||
|
||||
vi.mock('../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
|
||||
vi.mock('../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
|
||||
@@ -151,7 +151,9 @@ describe('Tours English and German copy', () => {
|
||||
}
|
||||
rerender(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, status: 'ready', error: 'save' })} />)
|
||||
expect(screen.getByLabelText(toursText(de, 'tours.planner.status.saveFailed'))).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.maxDifficulty') }))
|
||||
const difficulty = screen.getByRole('button', { name: toursText(de, 'tours.planner.maxDifficulty') })
|
||||
mockTourEditorLayout(difficulty.parentElement ?? difficulty)
|
||||
fireEvent.click(difficulty)
|
||||
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.difficulty.t4') }))
|
||||
expect(screen.getByRole('heading', { name: toursText(de, 'tours.planner.difficulty.alpineTitle') })).toBeInTheDocument()
|
||||
expect(screen.getByText(toursText(de, 'tours.planner.difficulty.alpineBody'))).toBeInTheDocument()
|
||||
@@ -187,4 +189,4 @@ describe('Tours English and German copy', () => {
|
||||
expect(await screen.findByText(toursText(fr, 'tours.planner.neutralTitle'))).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -284,6 +284,43 @@ describe('WalkStationsCard', () => {
|
||||
expect(within(cafe).queryByText(/Open/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens what the linked place has to tell under its stop, and leaves a stop without it as it is (#3205)', async () => {
|
||||
seedStore(useTripStore, {
|
||||
places: [
|
||||
buildPlace({
|
||||
id: 77,
|
||||
name: 'Lenbachhaus',
|
||||
description: 'Blue Rider collection',
|
||||
address: 'Luisenstrasse 33',
|
||||
website: 'https://lenbachhaus.de',
|
||||
}),
|
||||
],
|
||||
});
|
||||
vi.mocked(tourRepo.detail).mockImplementation(() =>
|
||||
detail([
|
||||
{ lat: 48, lng: 11, role: 'start', sequence: 0, key: 'stop-01', linked_place_id: 77, stay_minutes: 60 },
|
||||
{ lat: 48.002, lng: 11, role: 'end', sequence: 1, key: 'stop-02', name: 'Cafe', stay_minutes: 0 },
|
||||
])
|
||||
);
|
||||
card();
|
||||
|
||||
const museum = await rowOf('Lenbachhaus');
|
||||
const toggle = within(museum).getByRole('button', { name: /Lenbachhaus/ });
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(within(museum).queryByText('Blue Rider collection')).not.toBeInTheDocument();
|
||||
fireEvent.click(toggle);
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'true');
|
||||
expect(within(museum).getByText('Blue Rider collection')).toBeInTheDocument();
|
||||
expect(within(museum).getByText('Luisenstrasse 33')).toBeInTheDocument();
|
||||
expect(within(museum).getByRole('link', { name: 'Open Website' })).toHaveAttribute(
|
||||
'href',
|
||||
'https://lenbachhaus.de'
|
||||
);
|
||||
|
||||
const cafe = await rowOf('Cafe');
|
||||
expect(within(cafe).queryByRole('button', { name: /Cafe/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the times in the 12 hour format where the user chose it', async () => {
|
||||
seedStore(useSettingsStore, { settings: { time_format: '12h' } });
|
||||
card(onMonday());
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import type { TourListItem, TourVisitStatus } from '@trek/shared';
|
||||
import { Check, CheckCheck, Info, Redo2, SkipForward, Undo2 } from 'lucide-react';
|
||||
import type { Place, TourListItem, TourVisitStatus } from '@trek/shared';
|
||||
import { Check, CheckCheck, ChevronDown, ExternalLink, Info, MapPin, Redo2, SkipForward, Undo2 } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { useTourVisitStore } from '../../../store/tourVisitStore';
|
||||
import type { Assignment, AssignmentsMap, Day } from '../../../types';
|
||||
import { safeHttpUrl } from '../../../utils/safeUrl';
|
||||
import { SoftPill } from '../../Planner/planParts';
|
||||
import { DialogSection, fs } from '../../shared/DialogShell';
|
||||
import MarkdownText from '../../shared/MarkdownText';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import { stationMarkNote, stationRingClass } from '../planner/stationMarks';
|
||||
import { StationPills, StationShield } from '../planner/stationParts';
|
||||
@@ -83,23 +86,62 @@ function StatusActions({
|
||||
* trip place it stands for), stay, the day's arrival and opening hours, and
|
||||
* what can be marked.
|
||||
*/
|
||||
/** What a station's linked place has to tell (#3205): its description, address and website. */
|
||||
function placeDetailsOf(place: Place | null | undefined) {
|
||||
if (!place) return null;
|
||||
const description = place.description?.trim() || '';
|
||||
const address = place.address?.trim() || '';
|
||||
const website = safeHttpUrl(place.website);
|
||||
return description || address || website ? { description, address, website } : null;
|
||||
}
|
||||
|
||||
/** The linked place's details, opened under its station without leaving the walk. */
|
||||
function StationDetails({ details }: { details: NonNullable<ReturnType<typeof placeDetailsOf>> }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<span className="flex flex-col gap-1 text-content-secondary" style={fs(11.5, 'body')}>
|
||||
{details.description && <MarkdownText className="leading-[1.5]">{details.description}</MarkdownText>}
|
||||
{details.address && (
|
||||
<span className="flex items-start gap-1">
|
||||
<MapPin size={11} strokeWidth={2.2} aria-hidden="true" className="mt-[2px] flex-none text-content-faint" />
|
||||
<bdi className="min-w-0 [overflow-wrap:anywhere]">{details.address}</bdi>
|
||||
</span>
|
||||
)}
|
||||
{details.website && (
|
||||
<a
|
||||
href={details.website}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 self-start font-semibold text-content underline-offset-2 hover:underline"
|
||||
>
|
||||
<ExternalLink size={11} strokeWidth={2.2} aria-hidden="true" />
|
||||
{t('inspector.website')}
|
||||
</a>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function StationRow({
|
||||
station,
|
||||
index,
|
||||
status,
|
||||
placeName,
|
||||
place,
|
||||
schedule,
|
||||
onMark,
|
||||
}: {
|
||||
station: TourPlannerWaypoint;
|
||||
index: number;
|
||||
status: TourVisitStatus | undefined;
|
||||
placeName: string | undefined;
|
||||
place: Place | null;
|
||||
schedule: StationSchedule | undefined;
|
||||
onMark: ((status: TourVisitStatus | 'planned') => void) | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const name = station.name ?? placeName ?? t('tours.walk.stationNumbered', { number: index + 1 });
|
||||
const [open, setOpen] = useState(false);
|
||||
const details = placeDetailsOf(place);
|
||||
const name = station.name ?? place?.name ?? t('tours.walk.stationNumbered', { number: index + 1 });
|
||||
const nameClass = `truncate font-semibold text-content ${status === 'skipped' ? 'line-through' : ''}`;
|
||||
return (
|
||||
<li
|
||||
data-testid="walk-station"
|
||||
@@ -121,13 +163,31 @@ function StationRow({
|
||||
{station.protected && <StationShield />}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<span
|
||||
className={`truncate font-semibold text-content ${status === 'skipped' ? 'line-through' : ''}`}
|
||||
style={fs(12.5, 'body')}
|
||||
>
|
||||
{name}
|
||||
</span>
|
||||
{details ? (
|
||||
// A station that has more to tell opens it in place (#3205).
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
aria-expanded={open}
|
||||
className="flex min-w-0 items-center gap-1 self-start text-start"
|
||||
>
|
||||
<span className={nameClass} style={fs(12.5, 'body')}>
|
||||
{name}
|
||||
</span>
|
||||
<ChevronDown
|
||||
size={13}
|
||||
strokeWidth={2.2}
|
||||
aria-hidden="true"
|
||||
className={`flex-none text-content-faint transition-transform ${open ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<span className={nameClass} style={fs(12.5, 'body')}>
|
||||
{name}
|
||||
</span>
|
||||
)}
|
||||
<StationPills point={station} />
|
||||
{open && details && <StationDetails details={details} />}
|
||||
<StationScheduleLine schedule={schedule} name={name} />
|
||||
{status && (
|
||||
<span className="text-content-faint" style={fs(11, 'body')}>
|
||||
@@ -252,7 +312,7 @@ export function WalkStationsCard({
|
||||
station={station}
|
||||
index={index}
|
||||
status={station.key ? visits?.[station.key] : undefined}
|
||||
placeName={placeOf(station)?.name}
|
||||
place={placeOf(station)}
|
||||
schedule={schedule.byStation.get(station.id)}
|
||||
onMark={marking === 'ready' && station.key ? (next) => onMark(station.key ?? '', next) : null}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useTranslation } from '../../i18n';
|
||||
|
||||
/**
|
||||
* What the waiting states show while the app hands over from its address
|
||||
* screen (native/appBoot.ts): that screen's ground and its spinner, which only
|
||||
* comes up when the wait is long enough to notice. Styled in native/nativeApp.css.
|
||||
*/
|
||||
export default function AppBootScreen() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="app-boot" role="status" aria-label={t('common.loading')}>
|
||||
<span aria-hidden="true" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import type { TourPlannerController } from '../Tours/planner/useTourPlanner'
|
||||
import ToursSidebar from '../Tours/ToursSidebar'
|
||||
import type { Day } from '../../types'
|
||||
import CustomSelect from './CustomSelect'
|
||||
import { hikePlannerDefaults } from '../../../tests/helpers/tourPlannerStub'
|
||||
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../tests/helpers/tourPlannerStub'
|
||||
|
||||
vi.mock('../../repo/tourRepo', () => ({ tourRepo: {} }))
|
||||
vi.mock('../../store/settingsStore', () => ({
|
||||
@@ -57,6 +57,7 @@ describe('CustomSelect consumer contracts', () => {
|
||||
expect(screen.getByLabelText('Maximum trail difficulty')).toBe(trigger)
|
||||
expect(trigger).toHaveAttribute('id', 'tour-planner-difficulty')
|
||||
expect(document.querySelectorAll('[id="tour-planner-difficulty"]')).toHaveLength(1)
|
||||
mockTourEditorLayout(trigger.parentElement ?? trigger)
|
||||
await user.click(trigger)
|
||||
const menu = within(document.getElementById(trigger.getAttribute('aria-controls')!)!)
|
||||
for (const difficulty of [1, 2, 3, 4, 5, 6]) {
|
||||
@@ -132,4 +133,4 @@ describe('CustomSelect consumer contracts', () => {
|
||||
await user.click(screen.getByRole('button', { name: /^Planned\s*1$/ }))
|
||||
expect(setFilter).toHaveBeenLastCalledWith('planned')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import React, { useState, useRef, useEffect, useId } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { ChevronDown, Check } from 'lucide-react'
|
||||
import { useAnchoredPosition, scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
|
||||
import { scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { selectionHaptic } from '../../native/haptics'
|
||||
import { useAnchoredPopover } from './useAnchoredPopover'
|
||||
|
||||
interface SelectOption {
|
||||
// Callers use both string keys and numeric ids (e.g. day/place ids) as values, and
|
||||
@@ -85,7 +86,6 @@ export default function CustomSelect({
|
||||
menuFit = 'anchor',
|
||||
id,
|
||||
}: CustomSelectProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [search, setSearch] = useState('')
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
@@ -97,23 +97,24 @@ export default function CustomSelect({
|
||||
|
||||
// Follows the trigger while the sheet scrolls and while the on-screen keyboard
|
||||
// resizes the viewport, instead of freezing at the rect measured on open (#1999).
|
||||
const anchored = useAnchoredPosition(ref, open)
|
||||
const { open, bounded, box: anchored, setOpen } = useAnchoredPopover(ref, { disabled })
|
||||
const menuOpen = open && (!bounded || !!anchored)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !searchable || !searchRef.current) return
|
||||
if (!menuOpen || !searchable || !searchRef.current) return
|
||||
if (!keyboardDirection.current) searchRef.current.focus()
|
||||
// Focusing raises the keyboard on a phone; scroll the trigger up so the list
|
||||
// it just opened is not left underneath it (#2000).
|
||||
scrollAnchorIntoView(ref.current)
|
||||
}, [open, searchable])
|
||||
}, [menuOpen, searchable])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !keyboardDirection.current) return
|
||||
if (!menuOpen || !keyboardDirection.current) return
|
||||
const buttons = dropRef.current?.querySelectorAll<HTMLButtonElement>('button')
|
||||
const direction = keyboardDirection.current
|
||||
keyboardDirection.current = null
|
||||
if (buttons?.length) buttons[direction === 'last' ? buttons.length - 1 : 0].focus()
|
||||
}, [open])
|
||||
}, [menuOpen])
|
||||
|
||||
useEffect(() => {
|
||||
const handleClick = (e: MouseEvent) => {
|
||||
@@ -123,7 +124,7 @@ export default function CustomSelect({
|
||||
}
|
||||
if (open) document.addEventListener('mousedown', handleClick)
|
||||
return () => document.removeEventListener('mousedown', handleClick)
|
||||
}, [open])
|
||||
}, [open, setOpen])
|
||||
|
||||
const selected = options.find(o => sameValue(value, o.value))
|
||||
const filtered = searchable && search
|
||||
@@ -152,6 +153,8 @@ export default function CustomSelect({
|
||||
: options
|
||||
|
||||
const sm = size === 'sm'
|
||||
const availableOptionsHeight = (anchored?.maxHeight ?? 220) - (searchable ? 38 : 0)
|
||||
const optionsHeight = bounded ? Math.max(0, availableOptionsHeight - 2) : Math.max(96, availableOptionsHeight)
|
||||
|
||||
const closeMenu = () => {
|
||||
setOpen(false)
|
||||
@@ -223,7 +226,7 @@ export default function CustomSelect({
|
||||
</button>
|
||||
|
||||
{/* Dropdown */}
|
||||
{open && createPortal(
|
||||
{menuOpen && createPortal(
|
||||
<div ref={dropRef} id={menuId} role="group" aria-label={ariaLabel || selected?.label || placeholder || undefined} onKeyDown={handleKeyDown} style={{
|
||||
position: 'fixed',
|
||||
...(anchored
|
||||
@@ -233,7 +236,7 @@ export default function CustomSelect({
|
||||
// Never narrower than the trigger, and never past the right-hand edge of
|
||||
// the window. The cap is read at render time rather than measured, and
|
||||
// that is enough: every reason the anchor moved already re-renders this.
|
||||
...(menuFit === 'content'
|
||||
...(!bounded && menuFit === 'content'
|
||||
? {
|
||||
minWidth: anchored.width,
|
||||
width: 'max-content',
|
||||
@@ -251,6 +254,7 @@ export default function CustomSelect({
|
||||
boxShadow: '0 8px 32px rgba(0,0,0,0.12)',
|
||||
overflow: 'hidden',
|
||||
animation: 'trek-menu-enter 200ms cubic-bezier(0.23, 1, 0.32, 1)',
|
||||
overflowWrap: bounded ? 'anywhere' : undefined,
|
||||
transformOrigin: anchored?.flipped ? 'bottom center' : 'top center',
|
||||
willChange: 'transform, opacity',
|
||||
}}>
|
||||
@@ -277,7 +281,7 @@ export default function CustomSelect({
|
||||
{/* Options — capped at whatever the viewport still shows, so a list opened
|
||||
beside an on-screen keyboard shrinks instead of hiding under it (#2000). */}
|
||||
<div style={{
|
||||
maxHeight: Math.min(220, Math.max(96, (anchored?.maxHeight ?? 220) - (searchable ? 38 : 0))),
|
||||
maxHeight: Math.min(220, optionsHeight),
|
||||
overflowY: 'auto',
|
||||
// The panel is portaled to document.body and positioned fixed, so its
|
||||
// scroll chain runs to the viewport rather than to the sheet it looks
|
||||
|
||||
@@ -161,12 +161,15 @@ export function PopoverListPanel({ list, label, className = '', children }: {
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
const { open, box, menuRef, listId, onListKey } = list
|
||||
const { open, box, bounded, menuRef, listId, onListKey } = list
|
||||
if (!open || !box) return null
|
||||
return createPortal(
|
||||
<div ref={menuRef} id={listId} role="group" aria-label={label} onKeyDown={onListKey}
|
||||
className={`fixed z-[var(--z-toast)] overflow-y-auto ${className}`}
|
||||
style={{ ...POPOVER, top: box.top, bottom: box.bottom, left: box.left, maxHeight: box.maxHeight }}>
|
||||
className={`fixed z-[var(--z-toast)] overflow-y-auto ${bounded ? 'overflow-x-hidden overscroll-contain [overflow-wrap:anywhere] [&>button]:shrink-0' : ''} ${className}`}
|
||||
style={{
|
||||
...POPOVER, top: box.top, bottom: box.bottom, left: box.left, width: box.width || undefined, maxHeight: box.maxHeight,
|
||||
minWidth: bounded ? 0 : undefined,
|
||||
}}>
|
||||
{children}
|
||||
</div>,
|
||||
document.body,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { createContext, use, useCallback, useState, type RefObject } from 'react';
|
||||
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition';
|
||||
|
||||
/** The scrolling content that contains a panel's dropdown triggers. */
|
||||
export const PopoverBoundary = createContext<RefObject<HTMLElement | null> | null>(null);
|
||||
|
||||
export function useAnchoredPopover(
|
||||
anchorRef: RefObject<HTMLElement | null>,
|
||||
{
|
||||
disabled = false,
|
||||
estimatedHeight,
|
||||
matchWidth = true,
|
||||
}: {
|
||||
disabled?: boolean;
|
||||
estimatedHeight?: number;
|
||||
matchWidth?: boolean;
|
||||
}
|
||||
) {
|
||||
const boundaryRef = use(PopoverBoundary);
|
||||
const bounded = !!boundaryRef;
|
||||
const unavailable = bounded && disabled;
|
||||
const [expanded, setOpen] = useState(false);
|
||||
if (unavailable && expanded) setOpen(false);
|
||||
const open = expanded && !unavailable;
|
||||
const hide = useCallback(() => setOpen(false), []);
|
||||
const box = useAnchoredPosition(anchorRef, open, {
|
||||
matchWidth: bounded || matchWidth,
|
||||
estimatedHeight,
|
||||
boundary: boundaryRef ? { ref: boundaryRef, onAnchorHidden: hide } : undefined,
|
||||
});
|
||||
return { open, box, bounded, setOpen };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition';
|
||||
import { useEffect, useId, useLayoutEffect, useRef, type KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import { useAnchoredPopover } from './useAnchoredPopover';
|
||||
|
||||
const itemsOf = (list: HTMLElement | null) => Array.from(list?.querySelectorAll('button') ?? []);
|
||||
|
||||
@@ -13,38 +13,47 @@ const EDGE = 8;
|
||||
* it and goes on from the button; a click beside it closes it. The caller draws
|
||||
* the button and the list and hands `currentIndex`, the choice held now.
|
||||
*/
|
||||
export function usePopoverList(currentIndex: number, options: { estimatedHeight?: number } = {}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
export function usePopoverList(
|
||||
currentIndex: number,
|
||||
{
|
||||
estimatedHeight = 320,
|
||||
disabled,
|
||||
}: {
|
||||
estimatedHeight?: number;
|
||||
disabled?: boolean;
|
||||
} = {}
|
||||
) {
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const startAt = useRef(0);
|
||||
const listId = useId();
|
||||
const box = useAnchoredPosition(triggerRef, open, {
|
||||
const { open, box, bounded, setOpen } = useAnchoredPopover(triggerRef, {
|
||||
matchWidth: false,
|
||||
estimatedHeight: options.estimatedHeight ?? 320,
|
||||
estimatedHeight,
|
||||
disabled,
|
||||
});
|
||||
const listShown = open && !!box;
|
||||
|
||||
const toggle = () => {
|
||||
if (!open) startAt.current = Math.max(0, currentIndex);
|
||||
setOpen((o) => !o);
|
||||
setOpen((value) => !value);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (listShown) itemsOf(menuRef.current)[startAt.current]?.focus({ preventScroll: true });
|
||||
}, [listShown]);
|
||||
if (listShown) itemsOf(menuRef.current)[startAt.current]?.focus({ preventScroll: !bounded });
|
||||
}, [listShown, bounded]);
|
||||
|
||||
// The list opens from its button's start; one wider than the room beside a button near the
|
||||
// window's side moves back inside, as far as it must, before it is painted.
|
||||
useLayoutEffect(() => {
|
||||
const menu = menuRef.current;
|
||||
if (!listShown || !menu) return;
|
||||
if (!listShown || !menu || bounded) return;
|
||||
menu.style.translate = '';
|
||||
const rect = menu.getBoundingClientRect();
|
||||
let shift = Math.min(0, window.innerWidth - EDGE - rect.right);
|
||||
if (rect.left + shift < EDGE) shift = EDGE - rect.left;
|
||||
if (shift) menu.style.translate = `${Math.round(shift)}px 0`;
|
||||
}, [listShown, box]);
|
||||
}, [listShown, box, bounded]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -66,7 +75,7 @@ export function usePopoverList(currentIndex: number, options: { estimatedHeight?
|
||||
document.removeEventListener('mousedown', onDown);
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
};
|
||||
}, [open]);
|
||||
}, [open, setOpen]);
|
||||
|
||||
/** Closes the list after a choice and hands the focus back to the button. */
|
||||
const close = () => {
|
||||
@@ -94,5 +103,5 @@ export function usePopoverList(currentIndex: number, options: { estimatedHeight?
|
||||
items[next]?.focus();
|
||||
};
|
||||
|
||||
return { open, box, toggle, close, onListKey, triggerRef, menuRef, listId };
|
||||
return { open, box, bounded, toggle, close, onListKey, triggerRef, menuRef, listId };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useLayoutEffect, useState } from 'react'
|
||||
|
||||
export interface AnchoredBox {
|
||||
/** Distance from the viewport top, when the panel hangs below the trigger. */
|
||||
@@ -22,8 +22,38 @@ interface AnchoredOptions {
|
||||
padding?: number
|
||||
/** Adopt the trigger's width (selects) instead of measuring only its position. */
|
||||
matchWidth?: boolean
|
||||
/** Keep the panel inside a scroll area and dismiss it when the anchor leaves. */
|
||||
boundary?: {
|
||||
ref: React.RefObject<HTMLElement | null>
|
||||
onAnchorHidden: () => void
|
||||
}
|
||||
}
|
||||
|
||||
function viewportBounds() {
|
||||
// visualViewport excludes the area covered by an on-screen keyboard.
|
||||
const viewport = window.visualViewport
|
||||
const top = viewport?.offsetTop ?? 0
|
||||
const left = viewport?.offsetLeft ?? 0
|
||||
return { top, left, bottom: top + (viewport?.height ?? window.innerHeight), right: left + (viewport?.width ?? window.innerWidth) }
|
||||
}
|
||||
|
||||
function anchorLimits(anchor: DOMRect, boundaryRef?: React.RefObject<HTMLElement | null>) {
|
||||
const viewport = viewportBounds()
|
||||
const rect = boundaryRef?.current?.getBoundingClientRect()
|
||||
if (!rect) return { top: viewport.top, bottom: viewport.bottom, left: anchor.left, width: anchor.width, bounded: false }
|
||||
const left = Math.max(anchor.left, rect.left, viewport.left)
|
||||
return {
|
||||
top: Math.max(viewport.top, rect.top),
|
||||
bottom: Math.min(viewport.bottom, rect.bottom),
|
||||
left,
|
||||
width: Math.min(anchor.right, rect.right, viewport.right) - left,
|
||||
bounded: true,
|
||||
}
|
||||
}
|
||||
|
||||
/** Below this much room, the list would barely display its own border and padding. */
|
||||
const MIN_BOUNDED_HEIGHT = 24
|
||||
|
||||
/** How much the viewport must shrink before we treat it as an on-screen keyboard. */
|
||||
const KEYBOARD_THRESHOLD = 120
|
||||
|
||||
@@ -47,37 +77,35 @@ const KEYBOARD_THRESHOLD = 120
|
||||
export function useAnchoredPosition(
|
||||
anchorRef: React.RefObject<HTMLElement | null>,
|
||||
open: boolean,
|
||||
{ estimatedHeight = 220, offset = 4, padding = 8, matchWidth = true }: AnchoredOptions = {},
|
||||
{ estimatedHeight = 220, offset = 4, padding = 8, matchWidth = true, boundary }: AnchoredOptions = {},
|
||||
): AnchoredBox | null {
|
||||
const [box, setBox] = useState<AnchoredBox | null>(null)
|
||||
// Read in the measure callback so it stays stable across renders.
|
||||
const optsRef = useRef({ estimatedHeight, offset, padding, matchWidth })
|
||||
optsRef.current = { estimatedHeight, offset, padding, matchWidth }
|
||||
const boundaryRef = boundary?.ref
|
||||
const onAnchorHidden = boundary?.onAnchorHidden
|
||||
|
||||
const measure = useCallback(() => {
|
||||
const el = anchorRef.current
|
||||
if (!el) return
|
||||
const { estimatedHeight: wanted, offset: gap, padding: pad, matchWidth: match } = optsRef.current
|
||||
const r = el.getBoundingClientRect()
|
||||
// visualViewport is the part still visible next to an open keyboard; its
|
||||
// offsetTop is how far the browser scrolled the layout viewport up to keep
|
||||
// the focused field in sight, which shifts where "the bottom" really is.
|
||||
const vv = typeof window !== 'undefined' ? window.visualViewport : null
|
||||
const viewTop = typeof vv?.offsetTop === 'number' ? vv.offsetTop : 0
|
||||
const viewHeight = typeof vv?.height === 'number' ? vv.height : window.innerHeight
|
||||
const viewBottom = viewTop + viewHeight
|
||||
|
||||
const spaceBelow = viewBottom - r.bottom - gap - pad
|
||||
const spaceAbove = r.top - viewTop - gap - pad
|
||||
const limits = anchorLimits(r, boundaryRef)
|
||||
const spaceBelow = limits.bottom - r.bottom - offset - padding
|
||||
const spaceAbove = r.top - limits.top - offset - padding
|
||||
// Only flip when below genuinely cannot hold the panel and above is roomier,
|
||||
// which keeps the familiar downward direction in the ordinary case.
|
||||
const flipped = spaceBelow < Math.min(wanted, 160) && spaceAbove > spaceBelow
|
||||
const maxHeight = Math.max(96, Math.floor(flipped ? spaceAbove : spaceBelow))
|
||||
const flipped = spaceBelow < Math.min(estimatedHeight, 160) && spaceAbove > spaceBelow
|
||||
const availableHeight = Math.floor(flipped ? spaceAbove : spaceBelow)
|
||||
if (limits.bounded && (r.bottom <= limits.top || r.top >= limits.bottom || limits.width <= 0 || availableHeight < MIN_BOUNDED_HEIGHT)) {
|
||||
setBox(null)
|
||||
onAnchorHidden?.()
|
||||
return
|
||||
}
|
||||
const maxHeight = limits.bounded ? availableHeight : Math.max(96, availableHeight)
|
||||
const { left } = limits
|
||||
const width = matchWidth ? limits.width : 0
|
||||
|
||||
const next: AnchoredBox = flipped
|
||||
? { bottom: Math.round(window.innerHeight - r.top + gap), left: r.left, width: r.width, maxHeight, flipped }
|
||||
: { top: Math.round(r.bottom + gap), left: r.left, width: r.width, maxHeight, flipped }
|
||||
if (!match) next.width = 0
|
||||
? { bottom: Math.round(window.innerHeight - r.top + offset), left, width, maxHeight, flipped }
|
||||
: { top: Math.round(r.bottom + offset), left, width, maxHeight, flipped }
|
||||
|
||||
setBox(prev =>
|
||||
prev
|
||||
@@ -87,7 +115,7 @@ export function useAnchoredPosition(
|
||||
? prev
|
||||
: next,
|
||||
)
|
||||
}, [anchorRef])
|
||||
}, [anchorRef, boundaryRef, estimatedHeight, matchWidth, offset, onAnchorHidden, padding])
|
||||
|
||||
// Measure before paint so the panel never shows up at a stale spot first.
|
||||
useLayoutEffect(() => {
|
||||
@@ -110,6 +138,8 @@ export function useAnchoredPosition(
|
||||
// The trigger can change size on its own (a select whose label grows).
|
||||
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null
|
||||
if (el && ro) ro.observe(el)
|
||||
const boundaryEl = boundaryRef?.current
|
||||
if (boundaryEl && ro) ro.observe(boundaryEl)
|
||||
return () => {
|
||||
window.removeEventListener('scroll', measure, true)
|
||||
window.removeEventListener('resize', measure)
|
||||
@@ -117,7 +147,7 @@ export function useAnchoredPosition(
|
||||
vv?.removeEventListener('scroll', measure)
|
||||
ro?.disconnect()
|
||||
}
|
||||
}, [open, measure, anchorRef])
|
||||
}, [open, measure, anchorRef, boundaryRef])
|
||||
|
||||
return box
|
||||
}
|
||||
|
||||
@@ -146,6 +146,7 @@ export function useResizablePanels() {
|
||||
// dragged on a big screen comes back untouched once there is room for it again.
|
||||
leftWidth: shownLeft,
|
||||
rightWidth: shownRight,
|
||||
viewportWidth,
|
||||
leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed,
|
||||
leftHidden, rightHidden, toggleLeft, toggleRight, narrow,
|
||||
startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { useWritesInOrder } from './useWritesInOrder';
|
||||
|
||||
/** A write that only finishes when the test says so, and notes when it starts and ends. */
|
||||
function heldWrite(log: string[], name: string) {
|
||||
let finish!: () => void;
|
||||
let fail!: (err: Error) => void;
|
||||
const done = new Promise<void>((resolve, reject) => {
|
||||
finish = resolve;
|
||||
fail = reject;
|
||||
});
|
||||
const write = async () => {
|
||||
log.push(`${name} start`);
|
||||
await done;
|
||||
log.push(`${name} end`);
|
||||
};
|
||||
return { write, finish, fail };
|
||||
}
|
||||
|
||||
describe('useWritesInOrder', () => {
|
||||
it('FE-HOOK-WRITES-001: a write starts only once the one before it has finished', async () => {
|
||||
const { result } = renderHook(() => useWritesInOrder());
|
||||
const log: string[] = [];
|
||||
const first = heldWrite(log, 'first');
|
||||
const second = heldWrite(log, 'second');
|
||||
|
||||
const firstDone = result.current(first.write);
|
||||
const secondDone = result.current(second.write);
|
||||
await Promise.resolve();
|
||||
expect(log).toEqual(['first start']);
|
||||
|
||||
second.finish();
|
||||
first.finish();
|
||||
await Promise.all([firstDone, secondDone]);
|
||||
expect(log).toEqual(['first start', 'first end', 'second start', 'second end']);
|
||||
});
|
||||
|
||||
it('FE-HOOK-WRITES-002: a failed write does not hold up the next one, and its caller sees the failure', async () => {
|
||||
const { result } = renderHook(() => useWritesInOrder());
|
||||
const log: string[] = [];
|
||||
const first = heldWrite(log, 'first');
|
||||
const second = heldWrite(log, 'second');
|
||||
|
||||
const firstDone = result.current(first.write);
|
||||
const secondDone = result.current(second.write);
|
||||
first.fail(new Error('offline'));
|
||||
await expect(firstDone).rejects.toThrow('offline');
|
||||
|
||||
second.finish();
|
||||
await secondDone;
|
||||
expect(log).toEqual(['first start', 'second start', 'second end']);
|
||||
});
|
||||
|
||||
it('FE-HOOK-WRITES-003: the order holds across renders of the component using it', async () => {
|
||||
const { result, rerender } = renderHook(() => useWritesInOrder());
|
||||
const log: string[] = [];
|
||||
const first = heldWrite(log, 'first');
|
||||
const second = heldWrite(log, 'second');
|
||||
|
||||
const firstDone = result.current(first.write);
|
||||
rerender();
|
||||
const secondDone = result.current(second.write);
|
||||
await Promise.resolve();
|
||||
expect(log).toEqual(['first start']);
|
||||
|
||||
first.finish();
|
||||
second.finish();
|
||||
await Promise.all([firstDone, secondDone]);
|
||||
expect(log).toEqual(['first start', 'first end', 'second start', 'second end']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useRef } from 'react';
|
||||
|
||||
/**
|
||||
* Runs async writes one after another, in the order they were started.
|
||||
*
|
||||
* Two writes to the same record that leave close together, such as a field saved on
|
||||
* blur and a reset clicked right after it, otherwise race: the server may handle them
|
||||
* in either order, and whichever it handles last is what stays. A write that fails
|
||||
* does not hold up the ones queued behind it.
|
||||
*/
|
||||
export function useWritesInOrder(): (write: () => Promise<void>) => Promise<void> {
|
||||
const tail = useRef<Promise<void>>(Promise.resolve());
|
||||
return (write) => {
|
||||
const next = tail.current.then(write, write);
|
||||
tail.current = next;
|
||||
return next;
|
||||
};
|
||||
}
|
||||
@@ -22,7 +22,7 @@ beforeEach(() => {
|
||||
// A second spyOn returns the first spy with its calls; start every test clean.
|
||||
vi.restoreAllMocks();
|
||||
navigate.mockReset();
|
||||
useSharedImportStore.setState({ file: null, tripId: null, link: null });
|
||||
useSharedImportStore.setState({ file: null, tripId: null, link: null, placeLink: null });
|
||||
useAddonStore.setState({ addons: [{ id: 'collab', enabled: true }] as never, loaded: true });
|
||||
useTripAddonsStore.setState({ trips: {} });
|
||||
// Every trip follows the instance switch unless a test says otherwise; answered at once, so no read outlives its test.
|
||||
@@ -217,6 +217,35 @@ describe('NativeImportSheet', () => {
|
||||
expect(saveSharedLink).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('offers a shared map link as a place first, and hands it to the trip picked (#2582)', async () => {
|
||||
const maps = {
|
||||
url: 'https://www.google.com/maps/place/Time+Out+Market',
|
||||
title: 'Time Out Market',
|
||||
presetTripId: null,
|
||||
};
|
||||
render(<NativeImportSheet />);
|
||||
act(() => useSharedImportStore.getState().setFile(page(), maps));
|
||||
const choices = await screen.findAllByRole('button', {
|
||||
name: /Add it as a place|Save to the trip's links|Read a booking/,
|
||||
});
|
||||
expect(choices[0]).toHaveAccessibleName(/Add it as a place/);
|
||||
|
||||
fireEvent.click(choices[0]);
|
||||
expect(screen.getByText('Add the place to which trip?')).toBeInTheDocument();
|
||||
fireEvent.click(await screen.findByRole('button', { name: /Japan/ }));
|
||||
expect(useSharedImportStore.getState().placeLink).toEqual({ tripId: 2, url: maps.url });
|
||||
expect(useSharedImportStore.getState().file).toBeNull();
|
||||
expect(navigate).toHaveBeenCalledWith('/trips/2');
|
||||
expect(saveSharedLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('offers no place for a link that is not a map', async () => {
|
||||
render(<NativeImportSheet />);
|
||||
act(() => useSharedImportStore.getState().setFile(page(), link()));
|
||||
await screen.findByText('What should TREK do with this link?');
|
||||
expect(screen.queryByRole('button', { name: /Add it as a place/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('stays closed with nothing shared', () => {
|
||||
render(<NativeImportSheet />);
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
|
||||
@@ -7,11 +7,14 @@
|
||||
* (Collaboration, Links), or read as a booking. A bare link, whose page the phone
|
||||
* could not read, can only be kept; with Collaboration off, a page can only be read.
|
||||
* Collaboration counts per trip: a link goes only to a trip that has it on.
|
||||
* A map link (Google Maps, Amap) can also become a place of the
|
||||
* trip (#2582): the trip's new place sheet opens and looks the link up.
|
||||
*/
|
||||
import { ChevronRight, FileText, Link2, ScanText } from 'lucide-react';
|
||||
import { ChevronRight, FileText, Link2, MapPin, ScanText } from 'lucide-react';
|
||||
import React, { useEffect, useEffectEvent, useRef, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { isMapUrl } from '../../components/Planner/PlaceFormModal.helpers';
|
||||
import { useToast } from '../../components/shared/Toast';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { saveSharedLink, useSharedImportStore, type SharedLink } from '../../native/sharedFiles';
|
||||
@@ -31,11 +34,15 @@ interface TripRow {
|
||||
end_date?: string | null;
|
||||
}
|
||||
|
||||
type LinkChoice = 'link' | 'booking';
|
||||
type LinkChoice = 'link' | 'booking' | 'place';
|
||||
|
||||
/** What to offer for a shared link: the links when Collaboration is on, the import when there is a page to read. */
|
||||
function linkChoicesOf(file: File, collabOn: boolean): LinkChoice[] {
|
||||
/**
|
||||
* What to offer for a shared link: a place first when it points at a map, the links
|
||||
* when Collaboration is on, the import when there is a page to read.
|
||||
*/
|
||||
function linkChoicesOf(file: File, collabOn: boolean, url: string): LinkChoice[] {
|
||||
const choices: LinkChoice[] = [];
|
||||
if (isMapUrl(url)) choices.push('place');
|
||||
if (collabOn) choices.push('link');
|
||||
if (file.type !== 'text/uri-list') choices.push('booking');
|
||||
return choices;
|
||||
@@ -54,19 +61,22 @@ interface StageInput {
|
||||
|
||||
/** Where the sheet stands for the shared item: what it asks, and what a tap on a trip does. */
|
||||
function stageOf({ file, link, collabOn, picked, presetFailed, settled }: StageInput) {
|
||||
if (!file || !link) return { choice: 'booking' as LinkChoice | null, asking: false, nowhere: false, showTrips: true };
|
||||
if (!settled) return { choice: null, asking: false, nowhere: false, showTrips: false };
|
||||
const choices = linkChoicesOf(file, collabOn);
|
||||
const none: LinkChoice[] = [];
|
||||
if (!file || !link)
|
||||
return { choice: 'booking' as LinkChoice | null, asking: false, nowhere: false, choices: none, showTrips: true };
|
||||
if (!settled) return { choice: null, asking: false, nowhere: false, choices: none, showTrips: false };
|
||||
const choices = linkChoicesOf(file, collabOn, link.url);
|
||||
const choice = picked ?? (choices.length === 1 ? choices[0] : null);
|
||||
const asking = choice == null && choices.length > 1;
|
||||
const nowhere = choices.length === 0;
|
||||
// While the share sheet's trip takes the link there is nothing to choose.
|
||||
const presetTakes = link.presetTripId != null && choice === 'link' && !presetFailed;
|
||||
return { choice, asking, nowhere, showTrips: !asking && !nowhere && !presetTakes };
|
||||
return { choice, asking, nowhere, choices, showTrips: !asking && !nowhere && !presetTakes };
|
||||
}
|
||||
|
||||
function sheetTitle(t: (key: string) => string, asking: boolean, choice: LinkChoice | null): string {
|
||||
if (asking) return t('native.share.linkTitle');
|
||||
if (choice === 'place') return t('native.share.placeTrip');
|
||||
return choice === 'link' ? t('native.share.linkTrip') : t('native.share.title');
|
||||
}
|
||||
|
||||
@@ -151,6 +161,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
const tripId = useSharedImportStore((s) => s.tripId);
|
||||
const link = useSharedImportStore((s) => s.link);
|
||||
const chooseTrip = useSharedImportStore((s) => s.chooseTrip);
|
||||
const choosePlaceTrip = useSharedImportStore((s) => s.choosePlaceTrip);
|
||||
const setFile = useSharedImportStore((s) => s.setFile);
|
||||
const instanceCollab = useAddonStore((s) => s.isEnabled('collab'));
|
||||
const open = !!file && tripId == null;
|
||||
@@ -164,7 +175,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
// The save in flight, kept off the state: it guards a second tap, it is not shown.
|
||||
const savingRef = useRef<File | null>(null);
|
||||
const picked = pick && pick.file === file ? pick.choice : null;
|
||||
const { choice, asking, nowhere, showTrips } = stageOf({
|
||||
const { choice, asking, nowhere, choices, showTrips } = stageOf({
|
||||
file,
|
||||
link,
|
||||
collabOn,
|
||||
@@ -198,17 +209,28 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
);
|
||||
};
|
||||
|
||||
// The trip's new place sheet takes the map link from here (MTripShell, MPlaceEditSheet).
|
||||
const addPlace = (id: number) => {
|
||||
choosePlaceTrip(id);
|
||||
void navigate(`/trips/${id}`);
|
||||
};
|
||||
|
||||
// The trip the share sheet picked, used as soon as it is clear what the link is for.
|
||||
const preset = link?.presetTripId ?? null;
|
||||
const applyPreset = useEffectEvent((id: number, use: LinkChoice) => {
|
||||
if (use === 'booking') chooseTrip(id);
|
||||
else if (use === 'place') addPlace(id);
|
||||
else if (failedFile !== file) saveLink(id);
|
||||
});
|
||||
useEffect(() => {
|
||||
if (preset != null && choice != null && file) applyPreset(preset, choice);
|
||||
}, [preset, choice, file]);
|
||||
|
||||
const pickTrip = (id: number) => (choice === 'link' ? saveLink(id) : chooseTrip(id));
|
||||
const pickTrip = (id: number) => {
|
||||
if (choice === 'link') saveLink(id);
|
||||
else if (choice === 'place') addPlace(id);
|
||||
else chooseTrip(id);
|
||||
};
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={() => setFile(null)} variant="bottom" ariaLabel={t('native.share.title')}>
|
||||
@@ -222,7 +244,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
</div>
|
||||
{asking && file && <LinkQuestion onPick={(use) => setPick({ file, choice: use })} />}
|
||||
{asking && file && <LinkQuestion choices={choices} onPick={(use) => setPick({ file, choice: use })} />}
|
||||
{nowhere && (
|
||||
<p className="px-1 text-[length:calc(12px*var(--fs-scale-body,1))] text-m-muted">
|
||||
{t('native.share.linkUnsupported')}
|
||||
@@ -234,22 +256,40 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
);
|
||||
}
|
||||
|
||||
function LinkQuestion({ onPick }: { onPick: (choice: LinkChoice) => void }): React.ReactElement {
|
||||
function LinkQuestion({
|
||||
choices,
|
||||
onPick,
|
||||
}: {
|
||||
choices: LinkChoice[];
|
||||
onPick: (choice: LinkChoice) => void;
|
||||
}): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<ChoiceRow
|
||||
icon={<Link2 size={17} strokeWidth={2} />}
|
||||
label={t('native.share.saveLink')}
|
||||
hint={t('native.share.saveLinkHint')}
|
||||
onClick={() => onPick('link')}
|
||||
/>
|
||||
<ChoiceRow
|
||||
icon={<ScanText size={17} strokeWidth={2} />}
|
||||
label={t('native.share.readBooking')}
|
||||
hint={t('native.share.readBookingHint')}
|
||||
onClick={() => onPick('booking')}
|
||||
/>
|
||||
{choices.includes('place') && (
|
||||
<ChoiceRow
|
||||
icon={<MapPin size={17} strokeWidth={2} />}
|
||||
label={t('native.share.addPlace')}
|
||||
hint={t('native.share.addPlaceHint')}
|
||||
onClick={() => onPick('place')}
|
||||
/>
|
||||
)}
|
||||
{choices.includes('link') && (
|
||||
<ChoiceRow
|
||||
icon={<Link2 size={17} strokeWidth={2} />}
|
||||
label={t('native.share.saveLink')}
|
||||
hint={t('native.share.saveLinkHint')}
|
||||
onClick={() => onPick('link')}
|
||||
/>
|
||||
)}
|
||||
{choices.includes('booking') && (
|
||||
<ChoiceRow
|
||||
icon={<ScanText size={17} strokeWidth={2} />}
|
||||
label={t('native.share.readBooking')}
|
||||
hint={t('native.share.readBookingHint')}
|
||||
onClick={() => onPick('booking')}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -925,3 +925,23 @@ html:has(.m-shell) ::-webkit-scrollbar {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
/* A stop's number in the plan, as its pin on the map carries it (#2584):
|
||||
at the foot of its picture, on the trailing side. */
|
||||
.m-root .m-stop-num {
|
||||
position: absolute;
|
||||
inset-inline-end: -4px;
|
||||
bottom: -3px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-width: 16px;
|
||||
height: 16px;
|
||||
padding-inline: 4px;
|
||||
border-radius: 999px;
|
||||
background: var(--m-act);
|
||||
color: var(--m-actfg);
|
||||
box-shadow: 0 0 0 1.5px var(--m-bg);
|
||||
font: 700 0.5625rem/1 'Geist Sans', Poppins, system-ui, sans-serif;
|
||||
font-variant-numeric: tabular-nums;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ interface MCollPlaceSheetProps {
|
||||
labels: CollectionLabel[]
|
||||
onClose: () => void
|
||||
onSetStatus: (status: CollectionStatus) => void
|
||||
onSave: (patch: { name?: string; description?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; address?: string | null }) => Promise<void>
|
||||
onSave: (patch: { name?: string; description?: string | null; notes?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; address?: string | null }) => Promise<void>
|
||||
onUploadImage?: (file: File) => Promise<void>
|
||||
onCopyToTrip: () => void
|
||||
onRemove: () => void
|
||||
@@ -57,7 +57,7 @@ export default function MCollPlaceSheet({
|
||||
const [navOpen, setNavOpen] = useState(false)
|
||||
const navBtnRef = useRef<HTMLButtonElement | null>(null)
|
||||
const {
|
||||
shown: held, editing, setEditing, name, setName, address, setAddress, categoryId, setCategoryId, description, setDescription,
|
||||
shown: held, editing, setEditing, name, setName, address, setAddress, categoryId, setCategoryId, description, setDescription, notes, setNotes,
|
||||
links, setLinks, labelIds, toggleLabel, saving, imgBusy, cover, assignedLabels, handleImagePick, handleImageRemove, cancelEdit, save,
|
||||
} = useCollectionPlaceForm({
|
||||
place, labels, onSave, onUploadImage, t, normalizeLinkUrl, holdLastPlace: true, dropPhotoOnPlaceUpdate: true,
|
||||
@@ -195,6 +195,8 @@ export default function MCollPlaceSheet({
|
||||
)}
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.description').toUpperCase()}</Eyebrow>
|
||||
<textarea rows={4} value={description} onChange={e => setDescription(e.target.value)} placeholder={t('collections.descriptionPlaceholder')} className={TEXTAREA_CLS} />
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.notes').toUpperCase()}</Eyebrow>
|
||||
<textarea rows={3} value={notes} onChange={e => setNotes(e.target.value)} placeholder={t('collections.notesPlaceholder')} className={TEXTAREA_CLS} />
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.links').toUpperCase()}</Eyebrow>
|
||||
<MCollLinksEditor links={links} onChange={setLinks} t={t} />
|
||||
<div className="mt-4 flex items-center gap-2">
|
||||
@@ -228,6 +230,15 @@ export default function MCollPlaceSheet({
|
||||
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]}>{held.description}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
{/* The traveller's own notes (#3168), the way the place sheet of a trip shows them. */}
|
||||
{held.notes?.trim() && (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.notes').toUpperCase()}</Eyebrow>
|
||||
<p className="m-0 whitespace-pre-wrap rounded-[14px] bg-m-card px-[13px] py-[10px] font-geist text-caption leading-[1.55] text-m-muted [overflow-wrap:anywhere]">
|
||||
{held.notes}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
{held.links && held.links.length > 0 && (
|
||||
<div className="mt-3 flex flex-wrap gap-[6px]">
|
||||
{held.links.map((l, i) => (
|
||||
|
||||
@@ -138,6 +138,13 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
[current?.entries, hideSkeletons],
|
||||
)
|
||||
|
||||
// An existing entry opens to be read, also for those who may edit it (#3007);
|
||||
// the pencil in its sheet switches to the editor. New entries and suggestions
|
||||
// open in the editor straight away.
|
||||
const [editEntryId, setEditEntryId] = useState<number | null>(null)
|
||||
const readingEntry = !!editingEntry && canEditEntries && editingEntry.id !== 0
|
||||
&& editingEntry.type !== 'skeleton' && editEntryId !== editingEntry.id
|
||||
|
||||
const {
|
||||
mapRef, carouselRef, cardRefs, activeIndex, focusIndex, setActiveIndex, scrubberDays,
|
||||
syncMapToCard, handleMarkerClick, handleCardTap, openEntryById, jumpToDay,
|
||||
@@ -698,7 +705,8 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
entry={editingEntry}
|
||||
galleryPhotos={gallery}
|
||||
quickCapture={editingEntry.id === 0}
|
||||
readOnly={!canEditEntries}
|
||||
readOnly={!canEditEntries || readingEntry}
|
||||
onEdit={readingEntry ? () => setEditEntryId(editingEntry.id) : undefined}
|
||||
showVerdict={current.show_verdict !== 0}
|
||||
showMood={current.show_mood !== 0}
|
||||
showWeather={current.show_weather !== 0}
|
||||
@@ -706,12 +714,12 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
trips={current.trips}
|
||||
photoProviders={availableProviders}
|
||||
onMoveEarlier={
|
||||
canEditEntries && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveUp
|
||||
canEditEntries && !readingEntry && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveUp
|
||||
? () => { void moveWithinDay(editingEntry, -1) }
|
||||
: undefined
|
||||
}
|
||||
onMoveLater={
|
||||
canEditEntries && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveDown
|
||||
canEditEntries && !readingEntry && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveDown
|
||||
? () => { void moveWithinDay(editingEntry, 1) }
|
||||
: undefined
|
||||
}
|
||||
@@ -720,7 +728,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
? () => { setEditingEntry(null); void dismissSuggestion(editingEntry) }
|
||||
: undefined
|
||||
}
|
||||
onClose={() => setEditingEntry(null)}
|
||||
onClose={() => { setEditingEntry(null); setEditEntryId(null) }}
|
||||
onSave={async (data, existingEntryId) => {
|
||||
// existingEntryId is what the sheet already persisted in an earlier
|
||||
// save attempt — without it a retry would create a second entry.
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { useRef, useState, type CSSProperties } from 'react'
|
||||
import { Briefcase, Camera, Plus, Image, Images, X, MapPin, Locate, Trash2, CheckCircle2, MinusCircle, ChevronUp, ChevronDown, EyeOff, Play, NotebookPen } from 'lucide-react'
|
||||
import { Briefcase, Camera, Plus, Image, Images, X, MapPin, Locate, Trash2, CheckCircle2, MinusCircle, ChevronUp, ChevronDown, EyeOff, Play, NotebookPen, Pencil } from 'lucide-react'
|
||||
import { useIsTouch } from '../../../hooks/useIsTouch'
|
||||
import { useTouchDragBridge } from '../../../hooks/useTouchDragBridge'
|
||||
import { useSettingsStore } from '../../../store/settingsStore'
|
||||
import { formatClockTime } from '../../../utils/formatters'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import MToggle from '../../components/MToggle'
|
||||
@@ -48,6 +52,11 @@ interface MJourneyEntrySheetProps {
|
||||
galleryPhotos: GalleryPhoto[]
|
||||
quickCapture?: boolean
|
||||
readOnly?: boolean
|
||||
/**
|
||||
* Given to an editor reading an entry (#3007): the sheet opens as the read view
|
||||
* and a pencil in its header switches to the editor, without closing it.
|
||||
*/
|
||||
onEdit?: () => void
|
||||
userId?: number
|
||||
trips?: JourneyTrip[]
|
||||
/**
|
||||
@@ -87,16 +96,16 @@ interface MJourneyEntrySheetProps {
|
||||
*/
|
||||
export default function MJourneyEntrySheet({
|
||||
entry, galleryPhotos, quickCapture = false, readOnly = false, userId = 0, trips = [], photoProviders: providers = NO_PROVIDERS,
|
||||
showVerdict = true, showMood = true, showWeather = true, onMoveEarlier, onMoveLater, onDismiss,
|
||||
showVerdict = true, showMood = true, showWeather = true, onEdit, onMoveEarlier, onMoveLater, onDismiss,
|
||||
onClose, onSave, onUploadPhotos, onAddProviderPhotos, onDelete, onDone,
|
||||
}: MJourneyEntrySheetProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t, language } = useTranslation()
|
||||
const {
|
||||
title, setTitle, story, setStory, entryDate, setEntryDate, entryTime, setEntryTime,
|
||||
locationName, locationLat, locationQuery, locationResults, showLocationResults, setShowLocationResults,
|
||||
locating, locationError, mood, setMood, weather, setWeather, statsExcluded, setStatsExcluded, tripSuggestion,
|
||||
isDraft, setIsDraft, pros, setPros, cons, setCons, tags, setTags, tagInput, setTagInput, saving, uploadProgress,
|
||||
photos, photoOrder, pendingFiles, setPendingFiles, pendingPreviews, setPendingProviderGroups,
|
||||
photos, photoOrder, canReorder, pendingFiles, setPendingFiles, pendingPreviews, setPendingProviderGroups,
|
||||
showGalleryPick, setShowGalleryPick, isDirty, availableGalleryPhotos, queuedProviderPhotos, providerAssetIds,
|
||||
contextLocation, offersStatsToggle, addVerdictRow, verdictRowRef, addTag, handleSave, handleFileChange,
|
||||
pickGalleryPhoto, removePhoto, searchLocation, pickLocation, handleUseCurrentLocation,
|
||||
@@ -104,6 +113,11 @@ export default function MJourneyEntrySheet({
|
||||
entry, journeyId: entry.journey_id, trips, galleryPhotos, onSave, onUploadPhotos, onAddProviderPhotos, onDone,
|
||||
readOnly, quickCapture, withTags: true, inlineLocateError: true,
|
||||
})
|
||||
// A long press picks a photo up and a drag sets its place (#2851), on the
|
||||
// touch bridge the plan's rows use: a finger never starts an HTML5 drag.
|
||||
const sortable = canReorder && !readOnly
|
||||
const isTouch = useIsTouch()
|
||||
useTouchDragBridge(isTouch && sortable)
|
||||
const [showExternal, setShowExternal] = useState(false)
|
||||
const [externalProvider, setExternalProvider] = useState<string | null>(null)
|
||||
const [captureOnly, setCaptureOnly] = useState(quickCapture)
|
||||
@@ -121,6 +135,20 @@ export default function MJourneyEntrySheet({
|
||||
onClose()
|
||||
}
|
||||
|
||||
// An editor reading the entry: the read view, with the way into the editor.
|
||||
const reading = readOnly && !!onEdit
|
||||
const is12h = useSettingsStore(s => s.settings.time_format === '12h')
|
||||
// Read, the date and time head the entry instead of standing in locked fields.
|
||||
const readingWhen = reading && entryDate
|
||||
? [
|
||||
new Date(`${entryDate}T00:00:00Z`).toLocaleDateString(language, { weekday: 'short', day: 'numeric', month: 'long', timeZone: 'UTC' }),
|
||||
entryTime ? formatClockTime(entryTime, is12h) : '',
|
||||
].filter(Boolean).join(', ')
|
||||
: ''
|
||||
const heading = entry.id === 0
|
||||
? t('journey.detail.newEntry')
|
||||
: readingWhen || t('journey.detail.editEntry')
|
||||
|
||||
const eyebrow = 'font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-faint'
|
||||
const fieldShell = 'rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]'
|
||||
|
||||
@@ -130,7 +158,7 @@ export default function MJourneyEntrySheet({
|
||||
onClose={handleClose}
|
||||
variant="card"
|
||||
form
|
||||
ariaLabel={entry.id === 0 ? t('journey.detail.newEntry') : t('journey.detail.editEntry')}
|
||||
ariaLabel={heading}
|
||||
>
|
||||
{/* FormSheetHeader's shape, with the move buttons between the title and the close. */}
|
||||
<div className="m-fs-head flex flex-none items-center gap-3 px-[18px] pb-2 pt-4">
|
||||
@@ -138,8 +166,13 @@ export default function MJourneyEntrySheet({
|
||||
<NotebookPen size={19} strokeWidth={1.8} />
|
||||
</span>
|
||||
<span className="line-clamp-2 min-w-0 flex-1 break-words text-[1.0625rem] font-bold leading-tight">
|
||||
{entry.id === 0 ? t('journey.detail.newEntry') : t('journey.detail.editEntry')}
|
||||
{heading}
|
||||
</span>
|
||||
{reading && (
|
||||
<MIconBtn variant="neutral" size={34} onClick={onEdit} ariaLabel={t('common.edit')} className="me-1">
|
||||
<Pencil size={15} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
)}
|
||||
{(onMoveEarlier || onMoveLater) && (
|
||||
<span className="me-1 flex items-center gap-1">
|
||||
<MIconBtn variant="neutral" size={34} onClick={() => onMoveEarlier?.()} disabled={!onMoveEarlier} ariaLabel={t('dayplan.moveUp')}>
|
||||
@@ -348,9 +381,15 @@ export default function MJourneyEntrySheet({
|
||||
)}
|
||||
|
||||
{(photos.length > 0 || pendingFiles.length > 0) && (
|
||||
<div className="mt-[10px] flex flex-wrap gap-2">
|
||||
<div className="mt-[10px] flex flex-wrap gap-2" data-touch-drag={sortable ? '' : undefined}>
|
||||
{photos.map((p, idx) => (
|
||||
<div key={p.id} className="relative h-16 w-16 overflow-hidden rounded-[13px]">
|
||||
<div
|
||||
key={p.id}
|
||||
{...(sortable ? photoOrder.dragProps(idx) : {})}
|
||||
className={`relative h-16 w-16 overflow-hidden rounded-[13px] transition-opacity ${
|
||||
photoOrder.dragIndex === idx ? 'opacity-40' : ''
|
||||
} ${photoOrder.overIndex === idx && photoOrder.dragIndex !== idx ? 'ring-2 ring-[color:var(--m-act)]' : ''}`}
|
||||
>
|
||||
{posterlessVideo(p) ? (
|
||||
<ClipTile />
|
||||
) : (
|
||||
@@ -514,7 +553,7 @@ export default function MJourneyEntrySheet({
|
||||
|
||||
{/* Date + Time. Split in the date's favour: a localized date needs the
|
||||
room ("10. Sept. 2026"), a clock never does. */}
|
||||
<div className="mt-3 grid grid-cols-[minmax(0,1fr)_104px] gap-2">
|
||||
{!reading && <div className="mt-3 grid grid-cols-[minmax(0,1fr)_104px] gap-2">
|
||||
<div className="min-w-0">
|
||||
<div className={`${eyebrow} mb-[5px]`}>{t('journey.editor.date')}</div>
|
||||
{/* TREK's own picker, like the time field beside it: a native
|
||||
@@ -529,9 +568,9 @@ export default function MJourneyEntrySheet({
|
||||
brings its own shell, so fieldShell goes with the input. */}
|
||||
<CustomTimePicker value={entryTime} onChange={setEntryTime} disabled={readOnly} />
|
||||
</div>
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{tripSuggestion.trip && (
|
||||
{!reading && tripSuggestion.trip && (
|
||||
<div className={`mt-3 flex items-center gap-3 px-3 py-[10px] ${fieldShell}`}>
|
||||
<Briefcase size={15} strokeWidth={2} className="flex-none text-m-muted" />
|
||||
<div className="min-w-0 flex-1">
|
||||
@@ -545,7 +584,13 @@ export default function MJourneyEntrySheet({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Location */}
|
||||
{/* Location: read, a line under the story rather than a locked field. */}
|
||||
{reading ? (locationName && (
|
||||
<div className="mt-3 flex items-center gap-2 text-body font-semibold text-m-ink">
|
||||
<MapPin size={14} strokeWidth={2.2} className="flex-none text-m-muted" />
|
||||
<bdi className="min-w-0 [overflow-wrap:anywhere]">{locationName}</bdi>
|
||||
</div>
|
||||
)) : (
|
||||
<div className="relative mt-3">
|
||||
<div className={`${eyebrow} mb-[5px]`}>{t('journey.editor.location')}</div>
|
||||
<div className={`flex items-center gap-2 px-3 py-[10px] ${fieldShell}`}>
|
||||
@@ -594,11 +639,13 @@ export default function MJourneyEntrySheet({
|
||||
{locating && <div className="mt-[5px] font-geist text-[0.65625rem] text-m-muted">{t('common.loading')}</div>}
|
||||
{locationError && <div className="mt-[5px] font-geist text-[0.65625rem] text-[color:var(--m-st-danger)]">{locationError}</div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Off the route: the same switch the desktop editor and the Studio
|
||||
travel panel offer (#2064). Read-only keeps it visible but locked,
|
||||
like the date and the mood above and below it. */}
|
||||
{offersStatsToggle && (
|
||||
{/* Settings of the entry, not its content: an editor reading it does not need them locked in view. */}
|
||||
{offersStatsToggle && !reading && (
|
||||
<div className={`mt-3 flex items-center gap-3 px-3 py-[10px] ${fieldShell}`}>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.75rem] font-semibold text-m-ink">{t('journey.editor.statsExcluded')}</div>
|
||||
@@ -609,19 +656,22 @@ export default function MJourneyEntrySheet({
|
||||
)}
|
||||
|
||||
{/* Kept among the contributors until it is ready (#696). */}
|
||||
<div className={`mt-3 flex items-center gap-3 px-3 py-[10px] ${fieldShell}`}>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.75rem] font-semibold text-m-ink">{t('journey.editor.draft')}</div>
|
||||
<div className="mt-[2px] font-geist text-[0.65625rem] leading-[1.4] text-m-muted">{t('journey.editor.draftHint')}</div>
|
||||
{!reading && (
|
||||
<div className={`mt-3 flex items-center gap-3 px-3 py-[10px] ${fieldShell}`}>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.75rem] font-semibold text-m-ink">{t('journey.editor.draft')}</div>
|
||||
<div className="mt-[2px] font-geist text-[0.65625rem] leading-[1.4] text-m-muted">{t('journey.editor.draftHint')}</div>
|
||||
</div>
|
||||
<MToggle checked={isDraft} onChange={setIsDraft} disabled={readOnly} ariaLabel={t('journey.editor.draft')} />
|
||||
</div>
|
||||
<MToggle checked={isDraft} onChange={setIsDraft} disabled={readOnly} ariaLabel={t('journey.editor.draft')} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mood */}
|
||||
{showMood && !captureOnly && <>
|
||||
{/* Read, only what was chosen shows, and nothing when nothing was. */}
|
||||
{showMood && !captureOnly && (!reading || MOBILE_MOODS.some(m => m.id === mood)) && <>
|
||||
<div className={`${eyebrow} mb-[6px] mt-3`}>{t('journey.editor.mood')}</div>
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{MOBILE_MOODS.map(m => {
|
||||
{(reading ? MOBILE_MOODS.filter(m => m.id === mood) : MOBILE_MOODS).map(m => {
|
||||
const active = mood === m.id
|
||||
return (
|
||||
<button
|
||||
@@ -644,10 +694,10 @@ export default function MJourneyEntrySheet({
|
||||
</>}
|
||||
|
||||
{/* Weather */}
|
||||
{showWeather && <>
|
||||
{showWeather && (!reading || MOBILE_WEATHERS.some(w => w.id === weather)) && <>
|
||||
<div className={`${eyebrow} mb-[6px] mt-3`}>{t('journey.editor.weather')}</div>
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{MOBILE_WEATHERS.map(w => {
|
||||
{(reading ? MOBILE_WEATHERS.filter(w => w.id === weather) : MOBILE_WEATHERS).map(w => {
|
||||
const active = weather === w.id
|
||||
return (
|
||||
<button
|
||||
@@ -746,7 +796,7 @@ export default function MJourneyEntrySheet({
|
||||
onClick={handleClose}
|
||||
className={`${SHEET_SECONDARY} ms-auto`}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
{t(reading ? 'common.close' : 'common.cancel')}
|
||||
</button>
|
||||
{!readOnly && (
|
||||
<button
|
||||
|
||||
@@ -9,7 +9,7 @@ import { pickDockTabs } from './dockTabs'
|
||||
import MBadge from '../../components/MBadge'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import { useActivePill } from '../../components/useActivePill'
|
||||
import { useSharedImportStore } from '../../../native/sharedFiles'
|
||||
import { useSharedIntoTrip } from '../../../native/useSharedIntoTrip'
|
||||
import MPlanTimeline from './plan/MPlanTimeline'
|
||||
import MMapArea from './map/MMapArea'
|
||||
import MPlacesBrowser from './places/MPlacesBrowser'
|
||||
@@ -316,14 +316,11 @@ export default function MTripShell({
|
||||
})
|
||||
}, [railDayId, days, dayRail])
|
||||
// The active day's pill glides to the next chip rather than jumping there.
|
||||
// A booking document shared to TREK, and this trip picked for it: open the import.
|
||||
const sharedTripId = useSharedImportStore(s => s.tripId)
|
||||
const { setBookingImportKind, setShowBookingImport } = planner
|
||||
useEffect(() => {
|
||||
if (sharedTripId == null || sharedTripId !== Number(tripId)) return
|
||||
setBookingImportKind('bookings')
|
||||
setShowBookingImport(true)
|
||||
}, [sharedTripId, tripId, setBookingImportKind, setShowBookingImport])
|
||||
// Something shared to TREK and sent to this trip: the booking import, or a new place (#2582).
|
||||
useSharedIntoTrip(Number(tripId), {
|
||||
bookingImport: () => { planner.setBookingImportKind('bookings'); planner.setShowBookingImport(true) },
|
||||
newPlace: () => { planner.setEditingPlace(null); planner.setEditingAssignmentId(null); planner.setPrefillCoords(null); planner.setShowPlaceForm(true) },
|
||||
})
|
||||
// The day strip says when it runs on past an edge (a long trip, a narrow pane).
|
||||
const dayFade = useEdgeFade(dayRail)
|
||||
const dayPill = useActivePill(dayRail, '[aria-current="true"]', `${railDayId}:${days.map(d => d.id).join(',')}:${language}`)
|
||||
@@ -481,7 +478,10 @@ export default function MTripShell({
|
||||
return () => clearTimeout(timer)
|
||||
}, [boxKey, frameDayId])
|
||||
|
||||
const openSheet = (id: string, payload?: unknown) => setSheet({ id, payload })
|
||||
const openSheet = (id: string, payload?: unknown) => {
|
||||
if (id === 'day' && trTab === 'plan') planner.hideOverview()
|
||||
setSheet({ id, payload })
|
||||
}
|
||||
const closeSheet = () => setSheet(null)
|
||||
|
||||
// A hardware keyboard: ⌘1 to ⌘9 for the trip's sections in rail order, ⌥← and
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useEffect, useState, type MouseEvent } from 'react'
|
||||
import { useEffect, useMemo, useState, type MouseEvent } from 'react'
|
||||
import { ArrowRight, BedDouble, CalendarDays, CalendarRange, ChevronRight, LogIn, LogOut, Map as MapIcon, MapPin, Pencil, PencilLine, Route, Ticket, TrainFront, Undo2 } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { useContextMenu, ContextMenu } from '../../../../components/shared/ContextMenu'
|
||||
import MarkdownText from '../../../../components/shared/MarkdownText'
|
||||
import { fmtTransitDuration } from '../../../../components/Planner/transitDisplay'
|
||||
import { stopNumbersOfDay } from '../../../../components/Planner/stopNumbers'
|
||||
import { legModeMenuItems, transitOnlyMenuItems } from '../../../../components/Planner/useLegModeActions'
|
||||
import { formatTime } from '../../../../utils/formatters'
|
||||
import { useMPlanTimeline, type MPlanTimelineController } from './useMPlanTimeline'
|
||||
@@ -197,6 +198,9 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen
|
||||
}
|
||||
|
||||
const chrome = { editing, t, language: tl.language, timeFormat: tl.timeFormat }
|
||||
// The numbers the map's pins carry, beside each stop (#2584).
|
||||
const dayAssignments = planner.assignments[String(pageDayId)]
|
||||
const stopNumbers = useMemo(() => stopNumbersOfDay(dayAssignments || []), [dayAssignments])
|
||||
const [cardScroll, setCardScroll] = useState<HTMLDivElement | null>(null)
|
||||
const cardFade = useEdgeFade(cardScroll, 'y')
|
||||
|
||||
@@ -273,6 +277,7 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen
|
||||
<Fragment key={row.key}>
|
||||
<PlaceRow
|
||||
assignment={row.assignment}
|
||||
stopNumber={stopNumbers.get(row.assignment.id)}
|
||||
tour={planner.toursEnabled ? planner.tours.find(tour => tour.place_id === row.assignment.place_id) : undefined}
|
||||
fullPlace={tl.fullPlaceOf(row.assignment)}
|
||||
linkedReservations={row.linkedReservations}
|
||||
|
||||
@@ -129,8 +129,10 @@ const ROW_CODE = 'flex-none whitespace-nowrap font-geist text-[0.71875rem] text-
|
||||
|
||||
// ── b3) Place row ────────────────────────────────────────────────────────────
|
||||
|
||||
export function PlaceRow({ assignment, fullPlace, tour, linkedReservations, chrome, reorder, drag, onOpen, onEdit, onRemove, overrun }: {
|
||||
export function PlaceRow({ assignment, stopNumber, fullPlace, tour, linkedReservations, chrome, reorder, drag, onOpen, onEdit, onRemove, overrun }: {
|
||||
assignment: Assignment
|
||||
/** Its number on the map (#2584); none for a service stop. */
|
||||
stopNumber?: number
|
||||
fullPlace: Place | undefined
|
||||
tour?: TourListItem
|
||||
/** TIME-02: the day's next timed item this tour runs into, or null. */
|
||||
@@ -182,6 +184,7 @@ export function PlaceRow({ assignment, fullPlace, tour, linkedReservations, chro
|
||||
className={`flex cursor-pointer items-center gap-2.5 py-1.5 ${dragClass(drag)}`}
|
||||
>
|
||||
{!chrome.editing && (
|
||||
<span className="relative flex-none">
|
||||
<AvatarRing className="shadow-[0_3px_8px_-3px_rgba(0,0,0,.4)]">
|
||||
{tour ? <TourDayRowIcon type={tour.tour_type} /> : <PlaceAvatar
|
||||
place={fullPlace ?? {
|
||||
@@ -197,6 +200,8 @@ export function PlaceRow({ assignment, fullPlace, tour, linkedReservations, chro
|
||||
category={place?.category ? { color: place.category.color ?? undefined, icon: place.category.icon ?? undefined } : null}
|
||||
/>}
|
||||
</AvatarRing>
|
||||
{stopNumber != null && <span className="m-stop-num" aria-hidden="true">{stopNumber}</span>}
|
||||
</span>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ChevronRight, FileDown, Settings, Settings2, Sparkles } from 'lucide-react'
|
||||
import { ChevronRight, CloudDownload, FileDown, Settings, Settings2, Sparkles } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import { edgeFadeClass, useEdgeFade } from '../../../components/useEdgeFade'
|
||||
import type { MTripSheetsProps } from '../MTripShell'
|
||||
@@ -9,6 +10,8 @@ import { useIsWide } from '../../../../hooks/sizeClass'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import { useAssistantAsk } from '../../../../components/Assistant/useAssistantAsk'
|
||||
import { useAssistantHints } from '../../../../components/Assistant/useAssistantHints'
|
||||
import { useTripOfflineStatus, type TripOfflineState } from '../../../../components/Settings/useTripOfflineStatus'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
|
||||
/** Demo tile tints per legacy tab id; plugins share the files neutral. */
|
||||
const TILE_COLORS: Record<string, string> = {
|
||||
@@ -27,9 +30,25 @@ const TILE_COLORS: Record<string, string> = {
|
||||
* transparent scrim. Grid of the trip sections that did not fit the dock
|
||||
* (files/collab/plugins, with short stats) plus the share/export/settings rows.
|
||||
*/
|
||||
/** The offline line under the trip's own menu entry (#1580): saved as of when, or why not. */
|
||||
function offlineLine(state: TripOfflineState | null, t: (key: string, params?: Record<string, string>) => string, language: string, is12h: boolean): string | undefined {
|
||||
if (!state) return undefined
|
||||
if (state.kind === 'off') return t('mobileTrip.offlineOff')
|
||||
if (state.kind === 'pending') return t('mobileTrip.offlineNotSaved')
|
||||
const at = new Date(state.at)
|
||||
const today = new Date().toDateString() === at.toDateString()
|
||||
const time = today
|
||||
? at.toLocaleTimeString(language, { hour: 'numeric', minute: '2-digit', hour12: is12h })
|
||||
: at.toLocaleDateString(language, { day: 'numeric', month: 'short' })
|
||||
return t('mobileTrip.offlineSaved', { time })
|
||||
}
|
||||
|
||||
export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t, language } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const open = shell.sheet?.id === 'mehr'
|
||||
const offline = useTripOfflineStatus(planner.trip, open)
|
||||
const is12h = useSettingsStore(s => s.settings.time_format === '12h')
|
||||
const canEditTrip = planner.can('trip_edit', planner.trip)
|
||||
const assistant = useAssistantAsk(planner.tripId)
|
||||
// Warnings not shown yet turn the tile's line into a count; the dock gets no dot.
|
||||
@@ -61,9 +80,20 @@ export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
|
||||
shell.setTrTab(id)
|
||||
}
|
||||
|
||||
const actions: { id: string; icon: LucideIcon; label: string; go: () => void }[] = [
|
||||
const actions: { id: string; icon: LucideIcon; label: string; sub?: string; go: () => void }[] = [
|
||||
{ id: 'members', icon: Settings2, label: t('trip.settings.title'), go: () => shell.openSheet('members') },
|
||||
{ id: 'export', icon: FileDown, label: t('mobileTrip.export'), go: () => shell.openSheet('export') },
|
||||
// Whether this trip is on the device, without a trip to the settings to find out (#1580).
|
||||
{
|
||||
id: 'offline',
|
||||
icon: CloudDownload,
|
||||
label: t('settings.tabs.offline'),
|
||||
sub: offlineLine(offline, t, language, is12h),
|
||||
go: () => {
|
||||
shell.closeSheet()
|
||||
void navigate('/settings?tab=offline')
|
||||
},
|
||||
},
|
||||
...(canEditTrip
|
||||
? [{ id: 'tripedit', icon: Settings, label: t('dashboard.editTrip'), go: () => shell.openSheet('tripedit') }]
|
||||
: []),
|
||||
@@ -139,7 +169,10 @@ export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
|
||||
<div className="flex h-[34px] w-[34px] flex-none items-center justify-center rounded-[10px] bg-[color:var(--m-ic)]">
|
||||
<action.icon size={17} strokeWidth={1.9} />
|
||||
</div>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.875rem] font-semibold">{action.label}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[0.875rem] font-semibold">{action.label}</span>
|
||||
{action.sub && <span className="block truncate text-caption text-m-muted">{action.sub}</span>}
|
||||
</span>
|
||||
<ChevronRight size={16} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -34,6 +34,7 @@ import { usePlaceImageField } from '../../../../components/Planner/usePlaceImage
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import { useAuthStore } from '../../../../store/authStore'
|
||||
import { useSettingsStore } from '../../../../store/settingsStore'
|
||||
import { useSharedImportStore } from '../../../../native/sharedFiles'
|
||||
import type { Assignment, AssignmentsMap, Place } from '../../../../types'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
import { useLocationBias } from '../../../../hooks/useLocationBias'
|
||||
@@ -103,6 +104,9 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
const tagField = usePlaceTags({ tripId: planner.tripId, place: sheetPlace, tags: form.tags, setForm, t, toast })
|
||||
|
||||
const placesEnrichEnabled = useAuthStore(s => s.placesEnrichEnabled)
|
||||
// A map link shared to TREK for this trip (#2582): a new place starts from it.
|
||||
const sharedPlaceUrl = useSharedImportStore(s => (s.placeLink?.tripId === planner.tripId ? s.placeLink.url : null))
|
||||
const clearSharedPlace = useSharedImportStore(s => s.clearPlaceLink)
|
||||
const { language, locale } = useTranslation()
|
||||
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
|
||||
|
||||
@@ -266,6 +270,8 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
onPick={applyPick}
|
||||
onSuggestionName={name => setForm(prev => ({ ...prev, name }))}
|
||||
onResolvingChange={setResolvingPick}
|
||||
initialQuery={!sheetPlace && sharedPlaceUrl ? sharedPlaceUrl : undefined}
|
||||
onInitialQueryRun={clearSharedPlace}
|
||||
/>
|
||||
|
||||
{placesEnrichEnabled && (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import { useMemo, useRef, useState, type KeyboardEvent } from 'react'
|
||||
import DawarichIcon from '../../../../components/shared/DawarichIcon'
|
||||
import {
|
||||
Bookmark, ChevronRight, ExternalLink, Map as MapIcon, MapPinOff, Navigation, Paperclip,
|
||||
ArrowLeftRight, Bookmark, ChevronRight, ExternalLink, Map as MapIcon, MapPinOff, Navigation, Paperclip,
|
||||
Pencil, Phone, Plus, Route, RouteOff, Sparkles, Trash2, Upload, X,
|
||||
} from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
@@ -26,7 +26,7 @@ import { filesForPlace } from '../../../../utils/placeFiles'
|
||||
import { navigationTargetLabel, getNavigationTargets, openNavigationTarget } from '../../../../components/Planner/placeNavigation'
|
||||
import { addressWithoutCoordinates } from '../../../../components/Planner/placeCoordinates'
|
||||
import { NavigationMenu } from '../../../../components/shared/NavigationMenu'
|
||||
import { getPlaceBookings } from '../../../../utils/dayMerge'
|
||||
import { getPlaceBookings, timedSlot } from '../../../../utils/dayMerge'
|
||||
import type { Assignment, Day, Reservation, TripMember } from '../../../../types'
|
||||
import PlacePhotoGallery from '../../../../components/Planner/PlacePhotoGallery'
|
||||
import { ActionCircle, Eyebrow, INNER_CLS } from './MTripSheetUi'
|
||||
@@ -61,6 +61,9 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
uploading, filesExpanded, setFilesExpanded, fileInputRef, handleUpload,
|
||||
} = usePlaceFileUpload(place && !isTourPlace ? place.id : null, fd => planner.tripActions.addFile(planner.tripId, fd), planner.toast)
|
||||
const [dayPickerOpen, setDayPickerOpen] = useState(false)
|
||||
// A day of this place picked to move from (#2583): the day list then moves it there instead of adding it.
|
||||
// Only the ids are kept, so a stop a collaborator moved or removed meanwhile is read as it is now.
|
||||
const [movingIds, setMovingIds] = useState<{ placeId: number; assignmentId: number } | null>(null)
|
||||
const [participantPickerOpen, setParticipantPickerOpen] = useState(false)
|
||||
const [navOpen, setNavOpen] = useState(false)
|
||||
const navBtnRef = useRef<HTMLButtonElement>(null)
|
||||
@@ -70,6 +73,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
planner.setSelectedPlaceId(null)
|
||||
setFilesExpanded(false)
|
||||
setDayPickerOpen(false)
|
||||
setMovingIds(null)
|
||||
setParticipantPickerOpen(false)
|
||||
setColorPickerOpen(false)
|
||||
}
|
||||
@@ -91,7 +95,20 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
return rows
|
||||
}, [place, planner.days, planner.assignments])
|
||||
|
||||
const moving = movingIds && movingIds.placeId === place?.id
|
||||
? placeAssignments.find(r => r.assignment.id === movingIds.assignmentId) ?? null
|
||||
: null
|
||||
if (movingIds && !moving) setMovingIds(null)
|
||||
|
||||
const unassignedDays = planner.days.filter(d => !placeAssignments.some(r => r.day.id === d.id))
|
||||
const dayLabel = (d: Day) => d.title || t('planner.dayN', { n: (d.day_number ?? planner.days.indexOf(d) + 1) || '?' })
|
||||
// Lands where its time belongs on the new day, as a move on the desktop does;
|
||||
// without a time it goes to the end.
|
||||
const moveToDay = ({ assignment, day }: { assignment: Assignment; day: Day }, toDayId: number) => {
|
||||
const slot = timedSlot(planner.storedAssignments[String(toDayId)] || [], planner.tripAccommodations, assignment.place?.place_time) ?? undefined
|
||||
planner.handleMoveToDay(assignment.id, day.id, toDayId, slot)
|
||||
.catch((err: unknown) => planner.toast.error(err instanceof Error ? err.message : t('common.unknownError')))
|
||||
}
|
||||
|
||||
// Participants belong to the assignment in the selected day (desktop parity).
|
||||
const dayAssignments = planner.selectedDayId ? (planner.assignments[String(planner.selectedDayId)] || []) : []
|
||||
@@ -220,8 +237,28 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{/* A tap on the address opens directions, as the navigation button does:
|
||||
on the road the address is what the eye lands on. */}
|
||||
{place.address && (
|
||||
<div className="mt-[2px] font-geist text-[0.6875rem] leading-[1.4] text-m-muted"><bdi>{place.address}</bdi></div>
|
||||
<div
|
||||
className={`mt-[2px] font-geist text-[0.6875rem] leading-[1.4] text-m-muted${navTargets.length > 0 ? ' cursor-pointer underline decoration-dotted underline-offset-2' : ''}`}
|
||||
{...(navTargets.length > 0
|
||||
? {
|
||||
role: 'button',
|
||||
tabIndex: 0,
|
||||
'aria-label': `${navTargets.length === 1 ? navigationTargetLabel(navTargets[0], t) : t('inspector.navigation')}: ${place.address}`,
|
||||
onClick: openDirections,
|
||||
onKeyDown: (e: KeyboardEvent) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
openDirections()
|
||||
}
|
||||
},
|
||||
}
|
||||
: {})}
|
||||
>
|
||||
<bdi>{place.address}</bdi>
|
||||
</div>
|
||||
)}
|
||||
{/* A typed address that never got coordinates: no marker, and the sheet says why (#2837). */}
|
||||
{addressWithoutCoordinates(place) && (
|
||||
@@ -328,7 +365,20 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
key={assignment.id}
|
||||
className={`flex items-center gap-1 rounded-full py-1 ps-[10px] text-[0.75rem] font-semibold ${INNER_CLS} ${canEditDays ? 'pe-1' : 'pe-[10px]'}`}
|
||||
>
|
||||
{day.title || t('planner.dayN', { n: (day.day_number ?? planner.days.indexOf(day) + 1) || '?' })}
|
||||
{canEditDays && unassignedDays.length > 0 ? (
|
||||
// The day itself moves the stop to another one, keeping its time
|
||||
// and notes, where removing and adding it again would lose them.
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setDayPickerOpen(false); setMovingIds(moving?.assignment.id === assignment.id ? null : { placeId: place.id, assignmentId: assignment.id }) }}
|
||||
aria-label={t('mobileTrip.moveToDay')}
|
||||
aria-expanded={moving?.assignment.id === assignment.id}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
{dayLabel(day)}
|
||||
<ArrowLeftRight size={10} strokeWidth={2.4} aria-hidden="true" className="text-m-muted" />
|
||||
</button>
|
||||
) : dayLabel(day)}
|
||||
{canEditDays && !isTourPlace && place.lat != null && place.lng != null && (
|
||||
// In or out of that day's route (#2532); the icon says which it is.
|
||||
<button
|
||||
@@ -356,7 +406,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
{canEditDays && unassignedDays.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDayPickerOpen(v => !v)}
|
||||
onClick={() => { setMovingIds(null); setDayPickerOpen(v => !v) }}
|
||||
aria-label={t('inspector.addToDay')}
|
||||
aria-expanded={dayPickerOpen}
|
||||
className="flex h-[26px] w-[26px] items-center justify-center rounded-full border-[1.5px] border-dashed border-[color:var(--m-faint)] text-m-muted"
|
||||
@@ -365,18 +415,22 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{dayPickerOpen && (
|
||||
{(dayPickerOpen || moving) && (
|
||||
<div className="mt-[6px] max-h-[180px] overflow-y-auto rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] p-[6px]">
|
||||
{moving && <Eyebrow className="px-[10px] pb-1 pt-[6px] uppercase">{t('mobileTrip.moveToDay')}</Eyebrow>}
|
||||
{unassignedDays.map(d => (
|
||||
<button
|
||||
key={d.id}
|
||||
type="button"
|
||||
onClick={() => { planner.handleAssignToDay(place.id, d.id); setDayPickerOpen(false) }}
|
||||
onClick={() => {
|
||||
if (moving) moveToDay(moving, d.id)
|
||||
else planner.handleAssignToDay(place.id, d.id)
|
||||
setDayPickerOpen(false)
|
||||
setMovingIds(null)
|
||||
}}
|
||||
className="flex w-full items-center gap-2 rounded-[10px] px-[10px] py-[9px] text-start text-[0.78125rem] font-semibold"
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{d.title || t('planner.dayN', { n: (d.day_number ?? planner.days.indexOf(d) + 1) || '?' })}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate">{dayLabel(d)}</span>
|
||||
{d.date && (
|
||||
<span className="flex-none font-geist text-[0.65625rem] text-m-faint">
|
||||
{new Date(`${d.date.slice(0, 10)}T00:00:00Z`).toLocaleDateString(planner.language, { day: 'numeric', month: 'short', timeZone: 'UTC' })}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Loader2, RotateCcw, Search } from 'lucide-react'
|
||||
import { useEffect, useEffectEvent } from 'react'
|
||||
import { offersGoogleRetry } from '../../../../utils/placeSource'
|
||||
import { usePlaceSearch, type MapsPlace } from '../../../../components/Planner/usePlaceSearch'
|
||||
import { FIELD_CLS } from './PlSheetChrome'
|
||||
@@ -48,6 +49,10 @@ interface PlPlaceSearchProps {
|
||||
onSuggestionName: (name: string) => void
|
||||
/** True while a suggestion's details are being resolved (name spinner). */
|
||||
onResolvingChange?: (resolving: boolean) => void
|
||||
/** A query the field starts with and runs once, such as a shared map link (#2582). */
|
||||
initialQuery?: string
|
||||
/** The starting query was sent, so whoever held it can let it go. */
|
||||
onInitialQueryRun?: () => void
|
||||
}
|
||||
|
||||
function placeToPick(place: MapsPlace): PlSearchPick {
|
||||
@@ -73,7 +78,7 @@ function placeToPick(place: MapsPlace): PlSearchPick {
|
||||
* detection — the mobile counterpart of PlaceFormModal's search block, on the
|
||||
* same search logic (usePlaceSearch).
|
||||
*/
|
||||
export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggestionName, onResolvingChange }: PlPlaceSearchProps) {
|
||||
export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggestionName, onResolvingChange, initialQuery, onInitialQueryRun }: PlPlaceSearchProps) {
|
||||
const { t, toast } = planner
|
||||
const {
|
||||
query, setQuery, results, suggestions, setSuggestions, acSource, searchSource, searching, googleAnswers,
|
||||
@@ -94,8 +99,21 @@ export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggest
|
||||
}),
|
||||
onCoordinates: (lat, lng) => onPick({ lat, lng }),
|
||||
onResolvingChange,
|
||||
initialQuery,
|
||||
})
|
||||
|
||||
// A map link shared to the app (#2582) is looked up as soon as the sheet opens,
|
||||
// as if it had been pasted and searched. The sheet may be open already, its
|
||||
// field holding something else, so the link itself is what is searched.
|
||||
const runInitial = useEffectEvent((link: string) => {
|
||||
setQuery(link)
|
||||
void handleSearch(undefined, link)
|
||||
onInitialQueryRun?.()
|
||||
})
|
||||
useEffect(() => {
|
||||
if (initialQuery) runInitial(initialQuery)
|
||||
}, [initialQuery])
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { MapPin } from 'lucide-react'
|
||||
import { MapPin, Navigation } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import MDancingTrek from '../../../components/MDancingTrek'
|
||||
import { RES_ICONS } from '../../../../components/Planner/DayPlanSidebar.constants'
|
||||
import { formatTime, formatPriceText } from '../../../../utils/formatters'
|
||||
@@ -9,10 +10,12 @@ import { CardGrid, Field, ReservationPluginSlots, SectionHeader, StatusDot, TabS
|
||||
import { STATUS_COLOR, type MTabScreenProps } from './tabModel'
|
||||
import { cardWhen, parseTransportMeta, timeRange } from './transportsModel'
|
||||
import { BOOKING_TYPE_COLOR, hotelStayTimes } from '../../../../components/Planner/bookings/bookingsModel'
|
||||
import { useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
|
||||
import { listSections, useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
|
||||
import { useReservationCard } from '../../../../components/Planner/bookings/useReservationCard'
|
||||
import { orderedEndpoints, seatCells } from '../../../../utils/flightLegs'
|
||||
import { filesFor } from '../../../../utils/reservationFiles'
|
||||
import { getNavigationTargets, openNavigationTarget } from '../../../../components/Planner/placeNavigation'
|
||||
import { NavigationMenu } from '../../../../components/shared/NavigationMenu'
|
||||
|
||||
/**
|
||||
* Tab 2 — Buchungen. Real `planner.reservations` filtered to the non-transport
|
||||
@@ -30,10 +33,7 @@ export default function MBookingsTab({ planner, shell }: MTabScreenProps) {
|
||||
} = useReservationListFilter(allBookings, days, planner.tripMembers.length)
|
||||
const canEdit = planner.can('reservation_edit', planner.trip)
|
||||
|
||||
const sections = [
|
||||
{ id: 'confirmed', label: t('reservations.confirmed'), rows: groups.confirmed },
|
||||
{ id: 'pending', label: t('reservations.pending'), rows: groups.pending },
|
||||
].filter(s => s.rows.length > 0)
|
||||
const sections = listSections(groups, t)
|
||||
|
||||
return (
|
||||
<TabScroller wide="full">
|
||||
@@ -176,17 +176,16 @@ function BookingCard({ res, planner, canEdit, compact, onView }: {
|
||||
)}
|
||||
|
||||
<TravelerAvatars travelers={res.travelers || []} label={t('reservations.travelers.label')} />
|
||||
|
||||
{res.location && (
|
||||
<div className="mt-2 flex items-center gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px]">
|
||||
<MapPin size={12} strokeWidth={2} className="flex-none text-m-muted" />
|
||||
<span dir="auto" className="truncate text-[0.71875rem] font-semibold text-m-ink">{res.location}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<CardNotes notes={res.notes} />
|
||||
</button>
|
||||
|
||||
<CardLocation location={res.location} />
|
||||
|
||||
{res.notes?.trim() && (
|
||||
<button type="button" onClick={onView} className="block w-full text-start">
|
||||
<CardNotes notes={res.notes} />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<CardFiles files={files} card={card} t={t} />
|
||||
</div>
|
||||
)}
|
||||
@@ -196,3 +195,40 @@ function BookingCard({ res, planner, canEdit, compact, onView }: {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the booking is (the hotel, the rental desk): a tap opens directions to
|
||||
* it, as the address of a place does, in the traveller's map app or with the
|
||||
* same choice of apps.
|
||||
*/
|
||||
function CardLocation({ location }: { location: string | null | undefined }) {
|
||||
const { t } = useTranslation()
|
||||
const [anchor, setAnchor] = useState<HTMLButtonElement | null>(null)
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const text = location?.trim()
|
||||
if (!text) return null
|
||||
const targets = getNavigationTargets({ name: text, address: text, lat: null, lng: null, google_place_id: null, google_ftid: null })
|
||||
const openDirections = () => {
|
||||
if (targets.length === 1) openNavigationTarget(targets[0])
|
||||
else if (targets.length > 1) setMenuOpen(true)
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={setAnchor}
|
||||
type="button"
|
||||
onClick={openDirections}
|
||||
disabled={targets.length === 0}
|
||||
aria-label={`${t('inspector.navigation')}: ${text}`}
|
||||
className="mt-2 flex w-full items-center gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px] text-start"
|
||||
>
|
||||
<MapPin size={12} strokeWidth={2} className="flex-none text-m-muted" />
|
||||
<span dir="auto" className="min-w-0 flex-1 truncate text-[0.71875rem] font-semibold text-m-ink">{text}</span>
|
||||
{targets.length > 0 && <Navigation size={12} strokeWidth={2} aria-hidden="true" className="flex-none text-m-muted" />}
|
||||
</button>
|
||||
{menuOpen && (
|
||||
<NavigationMenu targets={targets} anchor={anchor} onClose={() => setMenuOpen(false)} title={t('inspector.openWith')} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -45,13 +45,20 @@ export default function MFileLightbox({ files, index, onIndexChange, onClose, t
|
||||
// tap-to-dismiss. Escape / arrow keys and the header buttons are the
|
||||
// keyboard equivalents, wired up in useMediaLightbox.
|
||||
role="presentation"
|
||||
className="m-root fixed inset-0 z-[65] flex flex-col bg-black/[.92]"
|
||||
className="m-root fixed inset-0 z-[65] flex flex-col bg-black/[.92] pb-[env(safe-area-inset-bottom,0px)]"
|
||||
onClick={onClose}
|
||||
onTouchStart={onTouchStart}
|
||||
onTouchEnd={onTouchEnd}
|
||||
>
|
||||
{/* Header */}
|
||||
<div role="presentation" className="flex flex-none items-center justify-between px-4 py-[10px]" onClick={e => e.stopPropagation()}>
|
||||
{/* Below the status bar and a notch, and clear of a side inset in landscape,
|
||||
so the close button is always there to tap. The insets are the screen's
|
||||
sides, so right to left takes them the other way round. */}
|
||||
<div
|
||||
role="presentation"
|
||||
className="flex flex-none items-center justify-between gap-2 pb-[10px] pe-[calc(var(--m-safe-r)+12px)] ps-[calc(var(--m-safe-l)+16px)] pt-[calc(var(--m-safe-t)+10px)] rtl:pe-[calc(var(--m-safe-l)+12px)] rtl:ps-[calc(var(--m-safe-r)+16px)]"
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate font-geist text-[0.75rem] text-white/70">
|
||||
{file.original_name}
|
||||
<span className="ms-2 text-white/40">{index + 1} / {files.length}</span>
|
||||
@@ -73,8 +80,13 @@ export default function MFileLightbox({ files, index, onIndexChange, onClose, t
|
||||
>
|
||||
<Download size={16} strokeWidth={2} />
|
||||
</button>
|
||||
<button type="button" onClick={onClose} aria-label={t('common.close')} className="flex h-8 w-8 items-center justify-center text-white/70">
|
||||
<X size={18} strokeWidth={2.2} />
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label={t('common.close')}
|
||||
className="ms-1 flex h-10 w-10 items-center justify-center rounded-full bg-[var(--m-viewer-btn)] text-[var(--m-viewer-ink)]"
|
||||
>
|
||||
<X size={20} strokeWidth={2.2} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -8,7 +8,7 @@ import { CardGrid, Field, ReservationPluginSlots, SectionHeader, StatusDot, TabS
|
||||
import { STATUS_COLOR, type MTabScreenProps } from './tabModel'
|
||||
import { cardWhen, parseTransportMeta } from './transportsModel'
|
||||
import { TRANSPORT_TYPE_COLOR } from '../../../../components/Planner/bookings/bookingsModel'
|
||||
import { useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
|
||||
import { listSections, useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
|
||||
import { useReservationCard } from '../../../../components/Planner/bookings/useReservationCard'
|
||||
import { orderedEndpoints, seatCells } from '../../../../utils/flightLegs'
|
||||
import { filesFor } from '../../../../utils/reservationFiles'
|
||||
@@ -30,11 +30,7 @@ export default function MTransportsTab({ planner, shell }: MTabScreenProps) {
|
||||
} = useReservationListFilter(allTransports, days, planner.tripMembers.length)
|
||||
const canEdit = planner.can('day_edit', planner.trip)
|
||||
|
||||
const sections = [
|
||||
{ id: 'confirmed', label: t('reservations.confirmed'), rows: groups.confirmed },
|
||||
{ id: 'pending', label: t('reservations.pending'), rows: groups.pending },
|
||||
{ id: 'transit', label: t('reservations.type.transit'), rows: groups.transit },
|
||||
].filter(s => s.rows.length > 0)
|
||||
const sections = listSections(groups, t)
|
||||
|
||||
return (
|
||||
<TabScroller wide="full">
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// FE-NATIVE-APPBOOT-001 to FE-NATIVE-APPBOOT-006
|
||||
import { StatusBar, Style } from '@capacitor/status-bar';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { endAppBoot, handOverToApp, isAppBoot, lightStatusBarIcons, pageUnderStatusBar } from './appBoot';
|
||||
import { isNativeAndroid, isNativeApp } from './platform';
|
||||
|
||||
vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeAndroid: vi.fn() }));
|
||||
vi.mock('@capacitor/status-bar', () => ({
|
||||
StatusBar: { setStyle: vi.fn(async () => {}) },
|
||||
Style: { Dark: 'DARK', Light: 'LIGHT' },
|
||||
}));
|
||||
|
||||
const root = document.documentElement;
|
||||
const realAgent = Object.getOwnPropertyDescriptor(window.navigator, 'userAgent');
|
||||
|
||||
function webViewVersion(major: number) {
|
||||
Object.defineProperty(window.navigator, 'userAgent', {
|
||||
configurable: true,
|
||||
get: () => `Mozilla/5.0 (Linux; Android 16; wv) AppleWebKit/537.36 Chrome/${major}.0.0.0 Mobile Safari/537.36`,
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(isNativeApp).mockReturnValue(true);
|
||||
vi.mocked(isNativeAndroid).mockReturnValue(false);
|
||||
vi.mocked(StatusBar.setStyle).mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
for (const name of ['data-app-boot', 'data-app-handover', 'data-app-enter']) root.removeAttribute(name);
|
||||
root.style.removeProperty('background-color');
|
||||
root.classList.remove('dark');
|
||||
if (realAgent) Object.defineProperty(window.navigator, 'userAgent', realAgent);
|
||||
});
|
||||
|
||||
describe('appBoot', () => {
|
||||
it('FE-NATIVE-APPBOOT-001: ends the handover colour once someone is signed in', () => {
|
||||
root.setAttribute('data-app-boot', '');
|
||||
root.style.backgroundColor = '#fffaf5';
|
||||
expect(isAppBoot()).toBe(true);
|
||||
|
||||
endAppBoot();
|
||||
expect(isAppBoot()).toBe(false);
|
||||
expect(root.style.backgroundColor).toBe('');
|
||||
});
|
||||
|
||||
it('FE-NATIVE-APPBOOT-002: leaves a page alone that never was in the handover', () => {
|
||||
root.style.backgroundColor = 'red';
|
||||
endAppBoot();
|
||||
expect(root.style.backgroundColor).toBe('red');
|
||||
});
|
||||
|
||||
it('FE-NATIVE-APPBOOT-003: lets the app rise in after the sign-in screen stepped back', async () => {
|
||||
vi.useFakeTimers();
|
||||
const go = vi.fn();
|
||||
const done = handOverToApp(Promise.resolve(), go);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(400);
|
||||
expect(go).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
await done;
|
||||
expect(go).toHaveBeenCalledTimes(1);
|
||||
|
||||
endAppBoot();
|
||||
expect(root.hasAttribute('data-app-enter')).toBe(true);
|
||||
expect(root.style.backgroundColor).not.toBe('');
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
expect(root.hasAttribute('data-app-enter')).toBe(false);
|
||||
expect(root.style.backgroundColor).toBe('');
|
||||
});
|
||||
|
||||
it('FE-NATIVE-APPBOOT-004: does not wait for settings that never come, nor stop on ones that fail', async () => {
|
||||
vi.useFakeTimers();
|
||||
const hanging = vi.fn();
|
||||
void handOverToApp(new Promise(() => {}), hanging);
|
||||
await vi.advanceTimersByTimeAsync(1600);
|
||||
expect(hanging).toHaveBeenCalled();
|
||||
|
||||
const failing = vi.fn();
|
||||
void handOverToApp(Promise.reject(new Error('offline')), failing);
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(failing).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-APPBOOT-005: knows where the page reaches under the status bar', () => {
|
||||
expect(pageUnderStatusBar()).toBe(true);
|
||||
vi.mocked(isNativeAndroid).mockReturnValue(true);
|
||||
webViewVersion(133);
|
||||
expect(pageUnderStatusBar()).toBe(false);
|
||||
webViewVersion(142);
|
||||
expect(pageUnderStatusBar()).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-NATIVE-APPBOOT-006: turns the status bar icons light over the landscape and back after', () => {
|
||||
root.classList.add('dark');
|
||||
const restore = lightStatusBarIcons();
|
||||
expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Dark });
|
||||
root.classList.remove('dark');
|
||||
restore();
|
||||
expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Light });
|
||||
|
||||
vi.mocked(StatusBar.setStyle).mockClear();
|
||||
vi.mocked(isNativeAndroid).mockReturnValue(true);
|
||||
webViewVersion(133);
|
||||
lightStatusBarIcons()();
|
||||
expect(StatusBar.setStyle).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { StatusBar, Style } from '@capacitor/status-bar';
|
||||
import { isNativeAndroid, isNativeApp } from './platform';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
import { isUnimplemented } from './trekShell';
|
||||
|
||||
/**
|
||||
* The handover from the app's address screen to this server's UI.
|
||||
*
|
||||
* The app picks a server, restarts its view on it, and the page then needs a
|
||||
* moment for its scripts, the session check and the sign-in chunk. Each of
|
||||
* those used to paint its own surface (a blank page, a grey spinner, an empty
|
||||
* fallback), so the step from the warm address screen to the sign-in screen
|
||||
* flashed white several times. public/theme-boot.js marks <html> with
|
||||
* data-app-boot before the first paint, when the page runs inside the app and
|
||||
* nobody has signed in on this server from here yet (no appearance snapshot):
|
||||
* the page then starts on the address screen's own colour, the waiting states
|
||||
* show the address screen's spinner on it (AppBootScreen), and the sign-in
|
||||
* screen fades in on the same ground. The mark goes once someone is signed in,
|
||||
* and the UI's own appearance takes over.
|
||||
*/
|
||||
const ATTRIBUTE = 'data-app-boot';
|
||||
|
||||
export function isAppBoot(): boolean {
|
||||
return typeof document !== 'undefined' && document.documentElement.hasAttribute(ATTRIBUTE);
|
||||
}
|
||||
|
||||
/** Set once the sign-in screen hands over, so the app rises in instead of cutting in. */
|
||||
const HANDOVER = 'data-app-handover';
|
||||
/** Set while the app rises in (native/nativeApp.css). */
|
||||
const ENTER = 'data-app-enter';
|
||||
/** The sign-in screen stepping back (appLogin.css .al-leaving). */
|
||||
const LEAVE_MS = 420;
|
||||
/** How long the handover waits for the settings before it goes anyway. */
|
||||
const SETTINGS_WAIT_MS = 1500;
|
||||
const ENTER_MS = 520;
|
||||
/** The address screen's page colour (native-shell/shell.css --page), as public/theme-boot.js paints it. */
|
||||
const PAGE_COLOUR = '#fffaf5';
|
||||
|
||||
const wait = (ms: number): Promise<void> => new Promise((resolve) => window.setTimeout(resolve, ms));
|
||||
|
||||
/**
|
||||
* Signed in from the app's sign-in screen: it steps back into the page colour
|
||||
* while the settings load (the start page depends on them), then `go` opens
|
||||
* the app, which rises in once its first screen is there (endAppBoot).
|
||||
*/
|
||||
export function handOverToApp(settings: Promise<unknown>, go: () => void): Promise<void> {
|
||||
// allSettled: settings that fail to load must not hold the app back either.
|
||||
const ready = Promise.race([Promise.allSettled([settings]), wait(SETTINGS_WAIT_MS)]);
|
||||
return Promise.all([ready, wait(LEAVE_MS)]).then(() => {
|
||||
document.documentElement.setAttribute(HANDOVER, '');
|
||||
go();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Back to the UI's own appearance, once a signed-in screen is up.
|
||||
* theme-boot.js painted the page itself, so this clears that too; after a
|
||||
* handover the app first rises in on the page colour.
|
||||
*/
|
||||
export function endAppBoot(): void {
|
||||
const root = document.documentElement;
|
||||
const handover = root.hasAttribute(HANDOVER);
|
||||
if (!isAppBoot() && !handover) return;
|
||||
root.removeAttribute(ATTRIBUTE);
|
||||
if (!handover) {
|
||||
root.style.removeProperty('background-color');
|
||||
return;
|
||||
}
|
||||
// The page colour stays under the app while it rises in, whatever scheme the
|
||||
// account brings, so nothing flashes between the two.
|
||||
root.removeAttribute(HANDOVER);
|
||||
root.style.backgroundColor = PAGE_COLOUR;
|
||||
root.setAttribute(ENTER, '');
|
||||
window.setTimeout(() => {
|
||||
root.removeAttribute(ENTER);
|
||||
root.style.removeProperty('background-color');
|
||||
}, ENTER_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the page reaches under the status bar. iOS always lays it out there.
|
||||
* Android does once the system WebView is 140 or newer (Capacitor's SystemBars
|
||||
* hands the insets through from that version on); an older one sits between
|
||||
* the bars, on the window's plain colour (MainActivity), where light icons
|
||||
* would vanish. Shared with the address screen (native-shell/main.ts).
|
||||
*/
|
||||
export function pageUnderStatusBar(): boolean {
|
||||
if (!isNativeAndroid()) return true;
|
||||
const chrome = /Chrome\/(\d+)/.exec(navigator.userAgent);
|
||||
return !!chrome && Number(chrome[1]) >= ANDROID_WEBVIEW_UNDER_BARS;
|
||||
}
|
||||
const ANDROID_WEBVIEW_UNDER_BARS = 140;
|
||||
|
||||
/**
|
||||
* The sign-in screen has the landscape under the status bar, as the address
|
||||
* screen does, so the clock and icons turn light while it is up. The returned
|
||||
* function puts them back to the scheme's own (native/nativeApp.ts keeps them
|
||||
* following it from then on). Where the page stops below the bar, the icons
|
||||
* stay as they are, readable on the plain colour there.
|
||||
*/
|
||||
export function lightStatusBarIcons(): () => void {
|
||||
if (!isNativeApp() || !pageUnderStatusBar()) return () => undefined;
|
||||
setStatusBarStyle(Style.Dark);
|
||||
return () => {
|
||||
const dark = document.documentElement.classList.contains('dark');
|
||||
setStatusBarStyle(dark ? Style.Dark : Style.Light);
|
||||
};
|
||||
}
|
||||
|
||||
/** Where there is no status bar to style (a build without the plugin) nothing is wrong. */
|
||||
function setStatusBarStyle(style: Style): void {
|
||||
StatusBar.setStyle({ style }).catch((err: unknown) => {
|
||||
if (!isUnimplemented(err)) reportNativeFailure(err);
|
||||
});
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user