mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 15:40:06 +00:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 30914a4d6c | |||
| 793be249a2 | |||
| 2dc505eff2 | |||
| 39d2196a14 |
@@ -107,9 +107,8 @@ jobs:
|
||||
|
||||
# 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.
|
||||
# to liketrek/trek-android for Obtainium (wiki/Native-Apps.md). 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:
|
||||
|
||||
@@ -35,7 +35,7 @@ permissions:
|
||||
# Server tests i/10 one slice of the server suite, with coverage
|
||||
# Server coverage merges the slices, checks the per-domain
|
||||
# thresholds, uploads lcov
|
||||
# Server Postgres 14 i/3, Server Postgres 18 i/3
|
||||
# Server Postgres 14 i/3, Server Postgres 19 i/3
|
||||
# per supported major, in three slices: the probe
|
||||
# (the repository SQL against Postgres, first slice
|
||||
# only), then a slice of the lane (every suite that
|
||||
@@ -55,7 +55,7 @@ permissions:
|
||||
# Client e2e i/2 one slice of the browser flows in Chromium and
|
||||
# WebKit, in the Playwright container
|
||||
# Docker and Helm builds the image and boots it until ready, on
|
||||
# SQLite and on Postgres 18; lints and renders the
|
||||
# SQLite and on Postgres 19; lints and renders the
|
||||
# Helm chart and checks the compose files
|
||||
# Sonar SonarCloud analysis, not required
|
||||
# ci-ok the one required check (below)
|
||||
@@ -639,7 +639,7 @@ jobs:
|
||||
retention-days: 1
|
||||
|
||||
# TREK on Postgres, once per supported major: the oldest (14) and the newest
|
||||
# (18). Both steps run against the same service, the probe on an empty
|
||||
# (19). Both steps run against the same service, the probe on an empty
|
||||
# database of its own, the lane on databases it creates and drops.
|
||||
#
|
||||
# The probe (server/scripts/pg-probe.ts): against an empty Postgres it
|
||||
@@ -696,7 +696,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
postgres: [14, 18]
|
||||
postgres: [14, 19]
|
||||
shard: [1, 2, 3]
|
||||
services:
|
||||
postgres:
|
||||
@@ -757,14 +757,14 @@ jobs:
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
# The image ships the 18 client tools, which write settings a 14 server
|
||||
# The image ships the 19 client tools, which write settings a 14 server
|
||||
# does not know; the backup round trip runs with the same tools here.
|
||||
- name: Install the PostgreSQL 18 client tools
|
||||
- name: Install the PostgreSQL 19 client tools
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y >/dev/null
|
||||
sudo apt-get install -y --no-install-recommends postgresql-client-18 >/dev/null
|
||||
/usr/lib/postgresql/18/bin/pg_restore --version
|
||||
sudo apt-get install -y --no-install-recommends postgresql-client-19 >/dev/null
|
||||
/usr/lib/postgresql/19/bin/pg_restore --version
|
||||
|
||||
- name: Run the Postgres lane
|
||||
if: ${{ !cancelled() }}
|
||||
@@ -1347,7 +1347,7 @@ jobs:
|
||||
set -euo pipefail
|
||||
docker network create trek-ci-pg
|
||||
docker run -d --name trek-ci-db --network trek-ci-pg \
|
||||
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:18
|
||||
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:19
|
||||
for _ in $(seq 1 30); do
|
||||
docker exec trek-ci-db pg_isready -U postgres -d trek >/dev/null 2>&1 && break
|
||||
sleep 2
|
||||
|
||||
@@ -137,7 +137,7 @@ These principles come out of a full-repo audit and shape all new code:
|
||||
|
||||
## Quality gates in CI
|
||||
|
||||
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 18, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 18, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
|
||||
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 19, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 19, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
|
||||
|
||||
- **Job names read "<Area> <what>[ <variant>][ i/n]"** (`Server tests 3/10`, `Server Postgres 14 2/3`, `Docker and Helm`): the area first, one of Changes, Shared, Server, Client, Docker or Sonar, then lower case, with no colon, no parentheses and no middle dot, and a slice only at the end, so the checks list sorts by area. The workflow is named `CI`, so a check reads `CI / Server tests 3/10`. Job ids are the names in kebab-case (`server-tests`), the jobs stand in `test.yml` in area order, and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list; `scripts/ci/workflow-jobs.test.mjs` fails on a name outside it. `ci-ok`, `lint` and `check-target` keep their names: the ruleset requires them by name.
|
||||
- **What the folded jobs hold.** `Shared tests` is the plugin SDK's typecheck and coverage, run before the root install so the SDK resolves only its own dependencies, then i18n parity and shared's coverage. `Client types` is the typecheck and the strict ratchet; `Client checks` the source ratchets, then the production build with `check:gl-split`. `Docker and Helm` builds and boots the image when the image area changed and checks the chart and compose files when the deploy area changed. Inside a folded job each group of steps runs after a failure in another, so one red check shows every gate that failed; the step names say which.
|
||||
|
||||
+17
-9
@@ -73,22 +73,30 @@ COPY server/package.json ./server/
|
||||
# The upgrade takes the Debian security fixes the base image was built before
|
||||
# (zlib, 11/2026, failed the image scan until node:24-trixie-slim caught up).
|
||||
#
|
||||
# postgresql-client-18 brings pg_dump, pg_restore and psql to
|
||||
# /usr/lib/postgresql/18/bin, which back up and restore an install on Postgres
|
||||
# postgresql-client-19 brings pg_dump, pg_restore and psql to
|
||||
# /usr/lib/postgresql/19/bin, which back up and restore an install on Postgres
|
||||
# (TREK_DB_URL). A client handles every server up to its own major and refuses
|
||||
# a newer one, so the image carries the newest major TREK supports (14 to 18).
|
||||
# a newer one, so the image carries the newest major TREK supports (14 to 19).
|
||||
# Debian 13 ships 17 only, so it comes from the PostgreSQL project's apt
|
||||
# repository (PGDG): the `18` component lists that major's packages and no
|
||||
# other, and the repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2
|
||||
# 44A0 7FCC 7D46 ACCC 4CF8) is kept beside the entrypoint instead of fetched at
|
||||
# build time. Raise both together when TREK supports a newer major.
|
||||
# repository (PGDG): its `main` component carries every major the project
|
||||
# supports, and the package name pins the one installed. The per-major
|
||||
# components can trail a new release, so the image does not rely on them. The
|
||||
# repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2 44A0 7FCC 7D46
|
||||
# ACCC 4CF8) is kept beside the entrypoint instead of fetched at build time.
|
||||
# Raise the package together with SUPPORTED_SERVER_MAJORS in
|
||||
# server/src/db/engine/postgres/server-checks.ts.
|
||||
# Earlier images carried the version 18 tools, and installs that set
|
||||
# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/18/bin (the old .env.example value)
|
||||
# would lose backups and the pre-migrate snapshot after updating, so that path
|
||||
# stays as a link to the 19 tools, which handle every supported server.
|
||||
COPY server/scripts/pgdg-apt-key.asc /etc/apt/keyrings/pgdg.asc
|
||||
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main 18' \
|
||||
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main' \
|
||||
> /etc/apt/sources.list.d/pgdg.list && \
|
||||
apt-get update && \
|
||||
apt-get upgrade -y --no-install-recommends && \
|
||||
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
|
||||
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \
|
||||
libkitinerary-bin libsqlite3-0 postgresql-client-19 && \
|
||||
mkdir -p /usr/lib/postgresql/18 && ln -s /usr/lib/postgresql/19/bin /usr/lib/postgresql/18/bin && \
|
||||
npm ci --workspace=server --omit=dev --ignore-scripts && \
|
||||
{ ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor || true; } && \
|
||||
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
|
||||
|
||||
@@ -288,7 +288,7 @@ docker compose up -d
|
||||
See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)
|
||||
for the full walkthrough.
|
||||
|
||||
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 18 database instead. The
|
||||
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 19 database instead. The
|
||||
[`docker-compose.postgres.yml`](docker-compose.postgres.yml) example starts one beside TREK, and the
|
||||
[Postgres guide](https://github.com/liketrek/TREK/wiki/Database-Postgres) covers the requirements, the backups and
|
||||
how to move an existing SQLite install to Postgres with the command TREK ships for it.
|
||||
|
||||
@@ -190,7 +190,7 @@ env:
|
||||
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser
|
||||
# (nor a member of one, nor hold a right that reaches the server's files or programs): a
|
||||
# restore runs the backup's SQL as that role and refuses one that could reach the database host. The wiki page shows the
|
||||
# SQL that creates such a role. PostgreSQL 14 to 18 is supported.
|
||||
# SQL that creates such a role. PostgreSQL 14 to 19 is supported.
|
||||
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
|
||||
database:
|
||||
url: ""
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
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;
|
||||
@@ -14,13 +11,11 @@ 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;
|
||||
@@ -31,9 +26,6 @@ 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);
|
||||
@@ -65,33 +57,6 @@ 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(
|
||||
|
||||
@@ -1,234 +0,0 @@
|
||||
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,7 +5,6 @@ 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';
|
||||
@@ -1706,9 +1705,7 @@ function showUnreachable(server: string, cert?: ClientCertDemand, failure?: stri
|
||||
*/
|
||||
async function paintStatusBar(): Promise<void> {
|
||||
try {
|
||||
// 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 });
|
||||
await StatusBar.setStyle({ style: Style.Dark });
|
||||
if (wideLayout.matches) await StatusBar.hide();
|
||||
else await StatusBar.show();
|
||||
} catch {
|
||||
|
||||
+1
-1
@@ -145,7 +145,7 @@
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
"@vitest/coverage-v8": "^5.1.2",
|
||||
"@vitest/coverage-v8": "^4.1.12",
|
||||
"autoprefixer": "^10.7.0",
|
||||
"eslint": "^10.11.0",
|
||||
"eslint-config-flat-gitignore": "^2.4.0",
|
||||
|
||||
@@ -12,16 +12,6 @@
|
||||
(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,7 +8,7 @@
|
||||
"trek/no-swallowed-catch": 126,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 66,
|
||||
"react-hooks/refs": 533,
|
||||
"react-hooks/refs": 534,
|
||||
"react-hooks/set-state-in-effect": 189,
|
||||
"@typescript-eslint/no-floating-promises": 162,
|
||||
"react-hooks/exhaustive-deps": 113,
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
"src/index.css": 1636,
|
||||
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
|
||||
"src/pages/JourneyDetailPage.test.tsx": 3886,
|
||||
"src/pages/LoginPage.tsx": 1273,
|
||||
"src/pages/TripPlannerPage.tsx": 1127,
|
||||
"src/pages/LoginPage.tsx": 1294,
|
||||
"src/pages/TripPlannerPage.tsx": 1128,
|
||||
"src/pages/atlas/useAtlas.ts": 1207,
|
||||
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
|
||||
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
|
||||
|
||||
@@ -45,7 +45,7 @@
|
||||
"components/Journey/JourneyMapGL.tsx": 5,
|
||||
"components/Journey/MobileEntryView.tsx": 94,
|
||||
"components/Journey/MobileMapTimeline.tsx": 8,
|
||||
"components/Journey/PhotoLightbox.tsx": 11,
|
||||
"components/Journey/PhotoLightbox.tsx": 13,
|
||||
"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": 11,
|
||||
"mobile/screens/trip/tabs/MFileLightbox.tsx": 12,
|
||||
"mobile/screens/trip/tabs/MFileLinkSheet.tsx": 2,
|
||||
"mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4,
|
||||
|
||||
+1
-12
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useLayoutEffect, useState, useRef, ReactNode, Suspense } from 'react'
|
||||
import React, { useEffect, 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,8 +17,6 @@ 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'
|
||||
@@ -115,7 +113,6 @@ 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">
|
||||
@@ -289,7 +286,6 @@ 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>
|
||||
@@ -310,7 +306,6 @@ 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">
|
||||
@@ -403,12 +398,6 @@ 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({
|
||||
|
||||
@@ -339,8 +339,6 @@ 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; 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>
|
||||
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>
|
||||
/** 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, notes, setNotes, links, setLinks, setLink,
|
||||
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, 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,11 +226,6 @@ 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>
|
||||
@@ -253,12 +248,6 @@ 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,7 +176,6 @@ 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],
|
||||
@@ -193,7 +192,6 @@ 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],
|
||||
@@ -201,25 +199,6 @@ 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,7 +12,6 @@ import { cleanListLinks } from './useListEditor';
|
||||
export interface CollectionPlacePatch {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
notes?: string | null;
|
||||
links?: CollectionLink[];
|
||||
category_id?: number | null;
|
||||
label_ids?: number[];
|
||||
@@ -85,8 +84,6 @@ 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 ?? '');
|
||||
@@ -104,7 +101,6 @@ 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 ?? '');
|
||||
@@ -193,7 +189,6 @@ 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,
|
||||
@@ -220,8 +215,6 @@ export function useCollectionPlaceForm({
|
||||
setCategoryId,
|
||||
description,
|
||||
setDescription,
|
||||
notes,
|
||||
setNotes,
|
||||
links,
|
||||
setLinks,
|
||||
setLink,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-030
|
||||
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-029
|
||||
|
||||
// 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();
|
||||
render(<PhotoLightbox photos={[]} onClose={onClose} />);
|
||||
const { container } = render(<PhotoLightbox photos={[]} onClose={onClose} />);
|
||||
// Component returns null when photo is undefined (empty array, index 0 is undefined)
|
||||
expect(document.querySelector('img')).not.toBeInTheDocument();
|
||||
expect(container.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', () => {
|
||||
render(<PhotoLightbox photos={samplePhotos} startIndex={2} onClose={vi.fn()} />);
|
||||
const { container } = 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(document.querySelector('img')).toHaveAttribute('src', '/photos/3.jpg');
|
||||
expect(container.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', () => {
|
||||
render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
|
||||
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();
|
||||
render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
|
||||
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();
|
||||
render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
|
||||
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', () => {
|
||||
render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
|
||||
fireEvent.touchStart(surface, { touches: [{ clientX: 100, clientY: 200 }] });
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 200, clientY: 210 }] });
|
||||
@@ -305,13 +305,6 @@ 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,11 +1,9 @@
|
||||
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
|
||||
@@ -36,22 +34,10 @@ 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: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', cursor: 'pointer', flex: 'none',
|
||||
width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', cursor: 'pointer',
|
||||
}
|
||||
|
||||
/** 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)
|
||||
@@ -65,11 +51,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
useEffect(() => {
|
||||
const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
dialogRef.current?.focus()
|
||||
const unlock = lockBodyScroll()
|
||||
return () => {
|
||||
unlock()
|
||||
opener?.focus()
|
||||
}
|
||||
return () => opener?.focus()
|
||||
}, [])
|
||||
|
||||
const photo = photos[idx]
|
||||
@@ -129,9 +111,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
|
||||
if (!photo) return null
|
||||
|
||||
// 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(
|
||||
return (
|
||||
<div
|
||||
ref={dialogRef}
|
||||
role="dialog"
|
||||
@@ -140,28 +120,26 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
tabIndex={-1}
|
||||
style={{
|
||||
outline: 'none',
|
||||
position: 'fixed', inset: 0, zIndex: 'var(--z-modal)',
|
||||
position: 'fixed', inset: 0, zIndex: 10000,
|
||||
background: 'rgba(0,0,0,0.92)', backdropFilter: 'blur(20px)',
|
||||
display: 'flex', flexDirection: 'column',
|
||||
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'),
|
||||
paddingBottom: 'var(--bottom-nav-h)',
|
||||
}}
|
||||
onTouchStart={onTouchStart}
|
||||
onTouchMove={onTouchMove}
|
||||
onTouchEnd={onTouchEnd}
|
||||
>
|
||||
{/* 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 }}>
|
||||
{/* 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 }}>
|
||||
{isImage && (
|
||||
<>
|
||||
<Tooltip label={t('journey.lightbox.zoomOut')}>
|
||||
@@ -184,17 +162,16 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
</Tooltip>
|
||||
</>
|
||||
)}
|
||||
<button type="button" onClick={onClose} aria-label={t('common.close')} style={CLOSE_BTN}>
|
||||
<X size={20} />
|
||||
<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>
|
||||
</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={{
|
||||
@@ -223,7 +200,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
onError={() => setLoadedId(photo.id)}
|
||||
{...zoom.mouse}
|
||||
style={{
|
||||
maxWidth: '100%', maxHeight: '100%',
|
||||
maxWidth: '92vw', maxHeight: '92vh',
|
||||
objectFit: 'contain', borderRadius: 4,
|
||||
animation: 'fadeIn 0.15s ease',
|
||||
userSelect: 'none',
|
||||
@@ -235,7 +212,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: '100%', height: '100%', objectFit: 'contain', borderRadius: 4 }} />
|
||||
<img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '92vw', height: '92vh', objectFit: 'contain', borderRadius: 4 }} />
|
||||
)}
|
||||
<span style={{ ...ROUND_BTN, position: 'absolute', cursor: 'default' }}>
|
||||
<Loader2 size={18} className="animate-spin" />
|
||||
@@ -275,7 +252,6 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -317,8 +317,8 @@ async function valhallaOrOsrmDay(
|
||||
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
|
||||
cacheRoute(keys.plain, plain)
|
||||
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)
|
||||
// A day left before Valhalla answered was never refused by it.
|
||||
if (standInKey && !signal?.aborted) keepStandIn(standInKey, drawn)
|
||||
return drawn
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { Ref } from 'react'
|
||||
import { AlertTriangle, Route } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { MapTogglePill } from './MapTogglePill'
|
||||
@@ -7,9 +6,6 @@ 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.
|
||||
@@ -33,14 +29,13 @@ 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 = TRIP_OVERVIEW_MAX_WIDTH, cardRef }: {
|
||||
export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectDay, maxWidth = 320 }: {
|
||||
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
|
||||
@@ -50,7 +45,6 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={cardRef}
|
||||
data-testid="trip-overview-panel"
|
||||
style={{
|
||||
pointerEvents: 'auto', borderRadius: 14, overflow: 'hidden',
|
||||
|
||||
@@ -35,12 +35,4 @@ 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,7 +18,6 @@ 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.
|
||||
@@ -30,21 +29,13 @@ const PILL_CLEARANCE = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8;
|
||||
export function centredMapCard(
|
||||
leftWidth: number,
|
||||
rightWidth: number,
|
||||
{
|
||||
extent = '100%',
|
||||
clearPill = false,
|
||||
rightGap = EDGE_GAP,
|
||||
}: { extent?: string; clearPill?: boolean; rightGap?: number } = {}
|
||||
{ extent = '100%', clearPill = false }: { extent?: string; clearPill?: boolean } = {}
|
||||
): { centre: string; width: string } {
|
||||
const free = `(${extent} - ${leftWidth}px - ${rightWidth}px)`;
|
||||
const centre = `calc(${leftWidth}px + ${free} / 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})` };
|
||||
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))` };
|
||||
}
|
||||
|
||||
/** How a card that floats over the map is placed there, read by `centredMapCard`. */
|
||||
|
||||
@@ -17,9 +17,6 @@ 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[] = []
|
||||
|
||||
@@ -52,7 +49,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,
|
||||
): PlannedTripRouteOverview {
|
||||
): TripRouteOverview {
|
||||
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).
|
||||
@@ -134,6 +131,5 @@ export function useTripRouteOverview(
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [planKey, tripId, distanceUnit])
|
||||
|
||||
const hasPlannedRoute = plan.length > 0
|
||||
return useMemo(() => ({ ...result, hasPlannedRoute }), [result, hasPlannedRoute])
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -314,21 +314,6 @@ describe('the route cache keeps the engine apart', () => {
|
||||
});
|
||||
|
||||
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,36 +463,6 @@ 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,
|
||||
@@ -1494,8 +1464,7 @@ describe('downloadTripPDF — transport notes', () => {
|
||||
await downloadTripPDF({ ...richArgs, reservations: [{ ...withNote, notes: 'Gate <b>B12</b>' }] })
|
||||
const html = getIframe()!.srcdoc
|
||||
|
||||
// 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).toContain('<div class="note-time transport-note">Gate <b>B12</b></div>')
|
||||
expect(html).not.toContain('pdf-no-transport-notes"')
|
||||
expect(notesToggle()!.getAttribute('aria-checked')).toBe('true')
|
||||
})
|
||||
@@ -1503,7 +1472,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,7 +245,6 @@ 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),
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -304,7 +303,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, ctx)
|
||||
if (item.type === 'note') return noteItem(item.data as DayNote)
|
||||
const a = item.data as Assignment
|
||||
if (!a.place) return ''
|
||||
number++
|
||||
@@ -317,7 +316,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 md">${markdown.html(day.notes.trim())}</div>` : ''
|
||||
const intro = day.notes && day.notes.trim() ? `<div class="day-intro">${escHtml(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,22 +1,15 @@
|
||||
import { createMarkdownHtml } from '../shared/markdownHtml';
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
export function createPdfMarkdown(): {
|
||||
row: (text: string) => string;
|
||||
html: (text: string) => string;
|
||||
dispose: () => void;
|
||||
} {
|
||||
export function createPdfMarkdown(): { row: (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,
|
||||
};
|
||||
}
|
||||
@@ -24,7 +17,6 @@ export function createPdfMarkdown(): {
|
||||
/** 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,7 +50,6 @@ 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,
|
||||
};
|
||||
}
|
||||
@@ -170,7 +169,7 @@ describe('noteItem', () => {
|
||||
icon: 'Ticket',
|
||||
color: '#2563eb',
|
||||
} as DayNote;
|
||||
const tinted = parse(noteItem(note, context()));
|
||||
const tinted = parse(noteItem(note));
|
||||
expect(tinted.querySelector('.note-card')?.className).toBe('note-card note-tinted');
|
||||
expect(tinted.querySelector('.note-card')?.getAttribute('style')).toBe('--note:#2563eb');
|
||||
expect(texts(tinted, '.note-text')).toEqual(['Buy <tickets>']);
|
||||
@@ -178,7 +177,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, context()));
|
||||
const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote));
|
||||
expect(plain.querySelector('.note-card')?.className).toBe('note-card');
|
||||
expect(plain.querySelector('.note-time')).toBeNull();
|
||||
});
|
||||
|
||||
@@ -30,10 +30,8 @@ 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, laid out as an info row. */
|
||||
/** A place's description or notes as sanitized markdown. */
|
||||
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';
|
||||
@@ -216,7 +214,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 md">${ctx.markdownHtml(note)}</div>` : ''}
|
||||
${note ? `<div class="note-time transport-note">${escHtml(note)}</div>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
return item('booking', timeColumn(start, end), bookingIcon(r.type, 11), card, `--kind:${tint}`);
|
||||
@@ -228,16 +226,15 @@ 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, ctx: PdfDayContext): string {
|
||||
export function noteItem(note: DayNote): string {
|
||||
const colour = note.color ? hexColour(note.color, '') : '';
|
||||
// A note's `time` is the free line the day plan prints under its text, not a clock,
|
||||
// so it stays in the card and the time column stays empty. The planner renders it as
|
||||
// markdown, so the card does too (#3236).
|
||||
// so it stays in the card and the time column stays empty.
|
||||
const subtitle = typeof note.time === 'string' ? note.time.trim() : '';
|
||||
const card = `<div class="note-card${colour ? ' note-tinted' : ''}"${colour ? ` style="--note:${colour}"` : ''}>
|
||||
<span class="note-icon">${noteIcon(note.icon)}</span>
|
||||
<div class="note-body"><div class="note-text">${escHtml(note.text)}</div>${
|
||||
subtitle ? `<div class="note-time md">${ctx.markdownHtml(subtitle)}</div>` : ''
|
||||
subtitle ? `<div class="note-time">${escHtml(subtitle)}</div>` : ''
|
||||
}</div>
|
||||
</div>`;
|
||||
return item('note', timeColumn('', ''), '', card);
|
||||
|
||||
@@ -204,9 +204,6 @@ 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
|
||||
/** The create button's hint: what gets saved before the editor opens, "the booking" or "the place". */
|
||||
/** 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,8 +76,6 @@ 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
|
||||
@@ -88,7 +86,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('reservations.importedExpenseHint')}</div>
|
||||
<div className="text-content-faint" style={fs(12, 'body')}>{t(hintKey)}</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,4 +1,4 @@
|
||||
import React, { useEffect, useRef, useId, type ReactNode, type Ref } from 'react'
|
||||
import React, { useEffect, useRef, useId, type ReactNode } 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,8 +53,6 @@ interface DayDetailPanelProps {
|
||||
onAccommodationChange: () => void
|
||||
leftWidth?: number
|
||||
rightWidth?: number
|
||||
rightGap?: number
|
||||
panelRef?: Ref<HTMLDivElement>
|
||||
collapsed?: boolean
|
||||
onToggleCollapse?: () => void
|
||||
mobile?: boolean
|
||||
@@ -75,7 +73,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, rightGap, panelRef, 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, collapsed: collapsedProp = false, onToggleCollapse, mobile = false, onUpdateDayTitle, weatherPlaceName = null, openStayPicker = false, onStayPickerOpened, onOpenBooking }: DayDetailPanelProps) {
|
||||
const { t, language } = useTranslation()
|
||||
const can = useCanDo()
|
||||
const toast = useToast()
|
||||
@@ -186,10 +184,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, rightGap })
|
||||
const mapCard = centredMapCard(leftWidth, rightWidth, { extent: '100vw', clearPill: !mobile })
|
||||
|
||||
return (
|
||||
<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 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,18 +158,6 @@ 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,7 +104,6 @@ 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
|
||||
@@ -1481,11 +1480,12 @@ 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
|
||||
// An already-selected day can reopen its details from the overview.
|
||||
// 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.
|
||||
const toggleDaySelection = () => {
|
||||
const dayToOpen = isSelected && !props.openSelectedDayDetail ? null : day
|
||||
onSelectDay(dayToOpen?.id ?? null)
|
||||
onDayDetail?.(dayToOpen)
|
||||
if (isSelected) { onSelectDay(null); if (onDayDetail) onDayDetail(null) }
|
||||
else { onSelectDay(day.id); if (onDayDetail) onDayDetail(day) }
|
||||
}
|
||||
const isExpanded = expandedDays.has(day.id)
|
||||
const da = getDayAssignments(day.id)
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
displayTitle,
|
||||
groupReservations,
|
||||
groupTransports,
|
||||
hasPassed,
|
||||
onTravelers,
|
||||
parseMeta,
|
||||
phaseOf,
|
||||
@@ -395,48 +394,4 @@ 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,49 +252,21 @@ 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[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* The phone tabs' three 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[], now?: Date): StatusGroups {
|
||||
export function groupTransports(list: Reservation[], days: Day[]): StatusGroups {
|
||||
const sorted = sortReservations(list, days, 'date', 'asc', () => '')
|
||||
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')
|
||||
const transit = sorted.filter(r => r.type === 'transit')
|
||||
const nonTransit = sorted.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 -005: the traveller filter and folded sections
|
||||
// FE-PLANNER-RESLISTFILTER-001 to -004: the traveller filter and folded sections
|
||||
// of the phone's bookings and transports tabs.
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { buildDay, buildReservation } from '../../../../tests/helpers/factories';
|
||||
import type { Reservation } from '../../../types';
|
||||
@@ -24,14 +24,6 @@ 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));
|
||||
@@ -45,7 +37,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: [], past: [] });
|
||||
expect(result.current.groups).toEqual({ confirmed: [], pending: [bob], transit: [] });
|
||||
|
||||
act(() => result.current.toggleTravelerFilter(1));
|
||||
expect(result.current.groups.confirmed.map((r) => r.id)).toEqual([10]);
|
||||
@@ -66,24 +58,9 @@ 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, past: true });
|
||||
expect(result.current.collapsed).toEqual({ pending: true });
|
||||
act(() => result.current.toggleSection('confirmed'));
|
||||
act(() => result.current.toggleSection('pending'));
|
||||
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);
|
||||
expect(result.current.collapsed).toEqual({ pending: false, confirmed: true });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,20 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import type { Day, Reservation } from '../../../types';
|
||||
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);
|
||||
}
|
||||
import { groupTransports, onTravelers } from './bookingsModel';
|
||||
|
||||
/**
|
||||
* The traveller filter and the folded sections of the phone's bookings and
|
||||
@@ -28,13 +15,9 @@ export function listSections(groups: StatusGroups, t: (key: string) => string) {
|
||||
*/
|
||||
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,
|
||||
now
|
||||
days
|
||||
);
|
||||
const showTravelerFilter = memberCount > 1 && all.some((r) => (r.travelers || []).length > 0);
|
||||
const toggleTravelerFilter = (id: number) =>
|
||||
@@ -46,12 +29,8 @@ export function useReservationListFilter(all: Reservation[], days: Day[], member
|
||||
});
|
||||
const clearTravelerFilter = () => setTravelerFilter(new Set());
|
||||
|
||||
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] }));
|
||||
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
|
||||
const toggleSection = (id: string) => setCollapsed((c) => ({ ...c, [id]: !c[id] }));
|
||||
|
||||
return {
|
||||
travelerFilter,
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
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 { importedReservationStatus, type BookingImportPreviewItem, type Reservation, type ReservationEndpoint } from '@trek/shared'
|
||||
import type { BookingImportPreviewItem, Reservation, ReservationEndpoint } from '@trek/shared'
|
||||
|
||||
/**
|
||||
* A pre-fill draft for the reservation/transport edit modals built from a parsed
|
||||
@@ -29,8 +29,7 @@ export function parsedItemToDraft(item: BookingImportPreviewItem): BookingReview
|
||||
return {
|
||||
type: item.type,
|
||||
title: item.title,
|
||||
// Confirmed when the document said so, pending otherwise (#3238).
|
||||
status: importedReservationStatus(item.metadata),
|
||||
status: 'pending',
|
||||
reservation_time: item.reservation_time ?? null,
|
||||
reservation_end_time: item.reservation_end_time ?? null,
|
||||
location: item.location ?? item._venue?.address ?? item._venue?.name ?? null,
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
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,8 +60,6 @@ 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'];
|
||||
@@ -103,7 +101,6 @@ 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).
|
||||
@@ -113,7 +110,7 @@ export function usePlaceSearch({
|
||||
// The same hint autocomplete gets, as a point instead of a box.
|
||||
const biasPoint = pointFromBox(locationBias);
|
||||
|
||||
const [query, setQuery] = useState(initialQuery ?? '');
|
||||
const [query, setQuery] = useState('');
|
||||
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('');
|
||||
@@ -268,12 +265,11 @@ export function usePlaceSearch({
|
||||
const pickPlace = (place: MapsPlace, pick?: PlaceSearchPick) =>
|
||||
take(place, pick, sourceLabel(place, pick?.mode === 'search' ? searchSource : ''));
|
||||
|
||||
const runSearch = async (provider?: 'google', text?: string) => {
|
||||
const runSearch = async (provider?: 'google') => {
|
||||
// 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. 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();
|
||||
// it promises the same query.
|
||||
const trimmed = provider ? (searchMetaRef.current?.query ?? '') : query.trim();
|
||||
if (!trimmed) return;
|
||||
if (sheet) {
|
||||
setSuggestions([]);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-006
|
||||
// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-008
|
||||
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() }));
|
||||
@@ -39,3 +40,18 @@ 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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
// 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' });
|
||||
});
|
||||
});
|
||||
@@ -1,51 +0,0 @@
|
||||
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, mockTourEditorLayout } from '../../../../tests/helpers/tourPlannerStub'
|
||||
import { hikePlannerDefaults } from '../../../../tests/helpers/tourPlannerStub'
|
||||
import { tourRepo } from '../../../repo/tourRepo'
|
||||
import { useTripStore } from '../../../store/tripStore'
|
||||
import type { TourStage } from '../stages/tourStages'
|
||||
@@ -132,12 +132,6 @@ 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: [] })
|
||||
@@ -708,7 +702,6 @@ 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()
|
||||
@@ -772,7 +765,7 @@ describe('TourPlannerRail', () => {
|
||||
const controller = planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty, acknowledgeAlpine: acknowledge })
|
||||
const { unmount } = render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
openDifficulty()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
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' }))
|
||||
@@ -782,7 +775,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 })} />)
|
||||
openDifficulty()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /T5: Demanding alpine hiking/ }))
|
||||
expect(screen.queryByRole('heading', { name: 'Enable alpine routing?' })).not.toBeInTheDocument()
|
||||
expect(setDifficulty).toHaveBeenLastCalledWith(5)
|
||||
@@ -792,7 +785,7 @@ describe('TourPlannerRail', () => {
|
||||
const setDifficulty = vi.fn()
|
||||
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty })} />)
|
||||
|
||||
openDifficulty()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /T4: Alpine hiking/ }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(setDifficulty).not.toHaveBeenCalled()
|
||||
@@ -809,7 +802,7 @@ describe('TourPlannerRail', () => {
|
||||
})} />
|
||||
}
|
||||
render(<StatefulDifficultyRail />)
|
||||
openDifficulty()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
|
||||
for (const label of [
|
||||
'T1: Hiking',
|
||||
@@ -825,22 +818,6 @@ 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,7 +12,6 @@ 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'
|
||||
@@ -336,7 +335,6 @@ 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
|
||||
@@ -391,46 +389,44 @@ export function TourPlannerRail({ planner,
|
||||
</BarButton>
|
||||
</div>
|
||||
|
||||
<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} />
|
||||
<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} />
|
||||
|
||||
<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} />
|
||||
</PopoverBoundary>
|
||||
<TourDetailsSection planner={planner} locked={locked} onDifficultyChange={changeDifficulty} />
|
||||
</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, locked }: TourTypeFieldsProps) {
|
||||
function SkiFields({ planner }: { planner: TourPlannerController }) {
|
||||
const { t } = useTranslation();
|
||||
const { choice } = planner.ski;
|
||||
return (
|
||||
@@ -121,12 +121,7 @@ function SkiFields({ planner, locked }: TourTypeFieldsProps) {
|
||||
{t('tours.ski.plannedHint')}
|
||||
</span>
|
||||
{choice.discipline !== null && (
|
||||
<SkiRouteOptions
|
||||
discipline={choice.discipline}
|
||||
options={choice.options}
|
||||
onChange={planner.ski.setOption}
|
||||
locked={locked}
|
||||
/>
|
||||
<SkiRouteOptions discipline={choice.discipline} options={choice.options} onChange={planner.ski.setOption} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -162,7 +157,7 @@ export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) {
|
||||
|
||||
{planner.isRun && <RunFields planner={planner} locked={locked} />}
|
||||
|
||||
{planner.isSki && <SkiFields planner={planner} locked={locked} />}
|
||||
{planner.isSki && <SkiFields planner={planner} />}
|
||||
|
||||
{planner.isPaddle && (
|
||||
<div data-testid="tour-planner-paddle-fields" className="flex min-w-0 flex-col gap-3">
|
||||
|
||||
@@ -47,10 +47,7 @@ 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,
|
||||
disabled,
|
||||
});
|
||||
const list = usePopoverList(offered.indexOf(value), { estimatedHeight: 50 * offered.length + 20 });
|
||||
const { open, toggle, triggerRef, listId } = list;
|
||||
const label = t('tours.planner.tourType');
|
||||
const pick = (type: T) => {
|
||||
|
||||
@@ -47,7 +47,6 @@ 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. */
|
||||
@@ -103,7 +102,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, locked }: SkiRouteOptionsProps) {
|
||||
export function SkiRouteOptions({ discipline, options, onChange }: SkiRouteOptionsProps) {
|
||||
const { t } = useTranslation();
|
||||
const read = new Set(skiOptionsReadBy(discipline));
|
||||
const current: Options = { ...DEFAULT_SKI_ROUTE_OPTIONS, ...options };
|
||||
@@ -120,7 +119,6 @@ export function SkiRouteOptions({ discipline, options, onChange, locked }: SkiRo
|
||||
<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, mockTourEditorLayout } from '../../../tests/helpers/tourPlannerStub'
|
||||
import { hikePlannerDefaults } 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,9 +151,7 @@ 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()
|
||||
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.maxDifficulty') }))
|
||||
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()
|
||||
@@ -189,4 +187,4 @@ describe('Tours English and German copy', () => {
|
||||
expect(await screen.findByText(toursText(fr, 'tours.planner.neutralTitle'))).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -284,43 +284,6 @@ 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,13 +1,10 @@
|
||||
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 type { TourListItem, TourVisitStatus } from '@trek/shared';
|
||||
import { Check, CheckCheck, Info, Redo2, SkipForward, Undo2 } from 'lucide-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';
|
||||
@@ -86,62 +83,23 @@ 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,
|
||||
place,
|
||||
placeName,
|
||||
schedule,
|
||||
onMark,
|
||||
}: {
|
||||
station: TourPlannerWaypoint;
|
||||
index: number;
|
||||
status: TourVisitStatus | undefined;
|
||||
place: Place | null;
|
||||
placeName: string | undefined;
|
||||
schedule: StationSchedule | undefined;
|
||||
onMark: ((status: TourVisitStatus | 'planned') => void) | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
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' : ''}`;
|
||||
const name = station.name ?? placeName ?? t('tours.walk.stationNumbered', { number: index + 1 });
|
||||
return (
|
||||
<li
|
||||
data-testid="walk-station"
|
||||
@@ -163,31 +121,13 @@ function StationRow({
|
||||
{station.protected && <StationShield />}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
{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>
|
||||
)}
|
||||
<span
|
||||
className={`truncate font-semibold text-content ${status === 'skipped' ? 'line-through' : ''}`}
|
||||
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')}>
|
||||
@@ -312,7 +252,7 @@ export function WalkStationsCard({
|
||||
station={station}
|
||||
index={index}
|
||||
status={station.key ? visits?.[station.key] : undefined}
|
||||
place={placeOf(station)}
|
||||
placeName={placeOf(station)?.name}
|
||||
schedule={schedule.byStation.get(station.id)}
|
||||
onMark={marking === 'ready' && station.key ? (next) => onMark(station.key ?? '', next) : null}
|
||||
/>
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
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, mockTourEditorLayout } from '../../../tests/helpers/tourPlannerStub'
|
||||
import { hikePlannerDefaults } from '../../../tests/helpers/tourPlannerStub'
|
||||
|
||||
vi.mock('../../repo/tourRepo', () => ({ tourRepo: {} }))
|
||||
vi.mock('../../store/settingsStore', () => ({
|
||||
@@ -57,7 +57,6 @@ 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]) {
|
||||
@@ -133,4 +132,4 @@ describe('CustomSelect consumer contracts', () => {
|
||||
await user.click(screen.getByRole('button', { name: /^Planned\s*1$/ }))
|
||||
expect(setFilter).toHaveBeenLastCalledWith('planned')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,9 @@
|
||||
import React, { useState, useRef, useEffect, useId } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { ChevronDown, Check } from 'lucide-react'
|
||||
import { scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
|
||||
import { useAnchoredPosition, 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
|
||||
@@ -86,6 +85,7 @@ 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,24 +97,23 @@ 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 { open, bounded, box: anchored, setOpen } = useAnchoredPopover(ref, { disabled })
|
||||
const menuOpen = open && (!bounded || !!anchored)
|
||||
const anchored = useAnchoredPosition(ref, open)
|
||||
|
||||
useEffect(() => {
|
||||
if (!menuOpen || !searchable || !searchRef.current) return
|
||||
if (!open || !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)
|
||||
}, [menuOpen, searchable])
|
||||
}, [open, searchable])
|
||||
|
||||
useEffect(() => {
|
||||
if (!menuOpen || !keyboardDirection.current) return
|
||||
if (!open || !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()
|
||||
}, [menuOpen])
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
const handleClick = (e: MouseEvent) => {
|
||||
@@ -124,7 +123,7 @@ export default function CustomSelect({
|
||||
}
|
||||
if (open) document.addEventListener('mousedown', handleClick)
|
||||
return () => document.removeEventListener('mousedown', handleClick)
|
||||
}, [open, setOpen])
|
||||
}, [open])
|
||||
|
||||
const selected = options.find(o => sameValue(value, o.value))
|
||||
const filtered = searchable && search
|
||||
@@ -153,8 +152,6 @@ 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)
|
||||
@@ -226,7 +223,7 @@ export default function CustomSelect({
|
||||
</button>
|
||||
|
||||
{/* Dropdown */}
|
||||
{menuOpen && createPortal(
|
||||
{open && createPortal(
|
||||
<div ref={dropRef} id={menuId} role="group" aria-label={ariaLabel || selected?.label || placeholder || undefined} onKeyDown={handleKeyDown} style={{
|
||||
position: 'fixed',
|
||||
...(anchored
|
||||
@@ -236,7 +233,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.
|
||||
...(!bounded && menuFit === 'content'
|
||||
...(menuFit === 'content'
|
||||
? {
|
||||
minWidth: anchored.width,
|
||||
width: 'max-content',
|
||||
@@ -254,7 +251,6 @@ 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',
|
||||
}}>
|
||||
@@ -281,7 +277,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, optionsHeight),
|
||||
maxHeight: Math.min(220, Math.max(96, (anchored?.maxHeight ?? 220) - (searchable ? 38 : 0))),
|
||||
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,15 +161,12 @@ export function PopoverListPanel({ list, label, className = '', children }: {
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
const { open, box, bounded, menuRef, listId, onListKey } = list
|
||||
const { open, box, 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 ${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,
|
||||
}}>
|
||||
className={`fixed z-[var(--z-toast)] overflow-y-auto ${className}`}
|
||||
style={{ ...POPOVER, top: box.top, bottom: box.bottom, left: box.left, maxHeight: box.maxHeight }}>
|
||||
{children}
|
||||
</div>,
|
||||
document.body,
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
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, type KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import { useAnchoredPopover } from './useAnchoredPopover';
|
||||
import { useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition';
|
||||
|
||||
const itemsOf = (list: HTMLElement | null) => Array.from(list?.querySelectorAll('button') ?? []);
|
||||
|
||||
@@ -13,47 +13,38 @@ 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,
|
||||
{
|
||||
estimatedHeight = 320,
|
||||
disabled,
|
||||
}: {
|
||||
estimatedHeight?: number;
|
||||
disabled?: boolean;
|
||||
} = {}
|
||||
) {
|
||||
export function usePopoverList(currentIndex: number, options: { estimatedHeight?: number } = {}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const startAt = useRef(0);
|
||||
const listId = useId();
|
||||
const { open, box, bounded, setOpen } = useAnchoredPopover(triggerRef, {
|
||||
const box = useAnchoredPosition(triggerRef, open, {
|
||||
matchWidth: false,
|
||||
estimatedHeight,
|
||||
disabled,
|
||||
estimatedHeight: options.estimatedHeight ?? 320,
|
||||
});
|
||||
const listShown = open && !!box;
|
||||
|
||||
const toggle = () => {
|
||||
if (!open) startAt.current = Math.max(0, currentIndex);
|
||||
setOpen((value) => !value);
|
||||
setOpen((o) => !o);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (listShown) itemsOf(menuRef.current)[startAt.current]?.focus({ preventScroll: !bounded });
|
||||
}, [listShown, bounded]);
|
||||
if (listShown) itemsOf(menuRef.current)[startAt.current]?.focus({ preventScroll: true });
|
||||
}, [listShown]);
|
||||
|
||||
// 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 || bounded) return;
|
||||
if (!listShown || !menu) 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, bounded]);
|
||||
}, [listShown, box]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -75,7 +66,7 @@ export function usePopoverList(
|
||||
document.removeEventListener('mousedown', onDown);
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
};
|
||||
}, [open, setOpen]);
|
||||
}, [open]);
|
||||
|
||||
/** Closes the list after a choice and hands the focus back to the button. */
|
||||
const close = () => {
|
||||
@@ -103,5 +94,5 @@ export function usePopoverList(
|
||||
items[next]?.focus();
|
||||
};
|
||||
|
||||
return { open, box, bounded, toggle, close, onListKey, triggerRef, menuRef, listId };
|
||||
return { open, box, toggle, close, onListKey, triggerRef, menuRef, listId };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
|
||||
export interface AnchoredBox {
|
||||
/** Distance from the viewport top, when the panel hangs below the trigger. */
|
||||
@@ -22,38 +22,8 @@ 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
|
||||
|
||||
@@ -77,35 +47,37 @@ const KEYBOARD_THRESHOLD = 120
|
||||
export function useAnchoredPosition(
|
||||
anchorRef: React.RefObject<HTMLElement | null>,
|
||||
open: boolean,
|
||||
{ estimatedHeight = 220, offset = 4, padding = 8, matchWidth = true, boundary }: AnchoredOptions = {},
|
||||
{ estimatedHeight = 220, offset = 4, padding = 8, matchWidth = true }: AnchoredOptions = {},
|
||||
): AnchoredBox | null {
|
||||
const [box, setBox] = useState<AnchoredBox | null>(null)
|
||||
const boundaryRef = boundary?.ref
|
||||
const onAnchorHidden = boundary?.onAnchorHidden
|
||||
// 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 measure = useCallback(() => {
|
||||
const el = anchorRef.current
|
||||
if (!el) return
|
||||
const { estimatedHeight: wanted, offset: gap, padding: pad, matchWidth: match } = optsRef.current
|
||||
const r = el.getBoundingClientRect()
|
||||
const limits = anchorLimits(r, boundaryRef)
|
||||
const spaceBelow = limits.bottom - r.bottom - offset - padding
|
||||
const spaceAbove = r.top - limits.top - offset - padding
|
||||
// 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
|
||||
// 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(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 flipped = spaceBelow < Math.min(wanted, 160) && spaceAbove > spaceBelow
|
||||
const maxHeight = Math.max(96, Math.floor(flipped ? spaceAbove : spaceBelow))
|
||||
|
||||
const next: AnchoredBox = flipped
|
||||
? { bottom: Math.round(window.innerHeight - r.top + offset), left, width, maxHeight, flipped }
|
||||
: { top: Math.round(r.bottom + offset), left, width, maxHeight, 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
|
||||
|
||||
setBox(prev =>
|
||||
prev
|
||||
@@ -115,7 +87,7 @@ export function useAnchoredPosition(
|
||||
? prev
|
||||
: next,
|
||||
)
|
||||
}, [anchorRef, boundaryRef, estimatedHeight, matchWidth, offset, onAnchorHidden, padding])
|
||||
}, [anchorRef])
|
||||
|
||||
// Measure before paint so the panel never shows up at a stale spot first.
|
||||
useLayoutEffect(() => {
|
||||
@@ -138,8 +110,6 @@ 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)
|
||||
@@ -147,7 +117,7 @@ export function useAnchoredPosition(
|
||||
vv?.removeEventListener('scroll', measure)
|
||||
ro?.disconnect()
|
||||
}
|
||||
}, [open, measure, anchorRef, boundaryRef])
|
||||
}, [open, measure, anchorRef])
|
||||
|
||||
return box
|
||||
}
|
||||
|
||||
@@ -146,7 +146,6 @@ 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,
|
||||
|
||||
@@ -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, placeLink: null });
|
||||
useSharedImportStore.setState({ file: null, tripId: null, link: 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,35 +217,6 @@ 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,14 +7,11 @@
|
||||
* (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, MapPin, ScanText } from 'lucide-react';
|
||||
import { ChevronRight, FileText, Link2, 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';
|
||||
@@ -34,15 +31,11 @@ interface TripRow {
|
||||
end_date?: string | null;
|
||||
}
|
||||
|
||||
type LinkChoice = 'link' | 'booking' | 'place';
|
||||
type LinkChoice = 'link' | 'booking';
|
||||
|
||||
/**
|
||||
* 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[] {
|
||||
/** 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[] {
|
||||
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;
|
||||
@@ -61,22 +54,19 @@ 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) {
|
||||
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);
|
||||
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 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, choices, showTrips: !asking && !nowhere && !presetTakes };
|
||||
return { choice, asking, nowhere, 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');
|
||||
}
|
||||
|
||||
@@ -161,7 +151,6 @@ 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;
|
||||
@@ -175,7 +164,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, choices, showTrips } = stageOf({
|
||||
const { choice, asking, nowhere, showTrips } = stageOf({
|
||||
file,
|
||||
link,
|
||||
collabOn,
|
||||
@@ -209,28 +198,17 @@ 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) => {
|
||||
if (choice === 'link') saveLink(id);
|
||||
else if (choice === 'place') addPlace(id);
|
||||
else chooseTrip(id);
|
||||
};
|
||||
const pickTrip = (id: number) => (choice === 'link' ? saveLink(id) : chooseTrip(id));
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={() => setFile(null)} variant="bottom" ariaLabel={t('native.share.title')}>
|
||||
@@ -244,7 +222,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
</div>
|
||||
{asking && file && <LinkQuestion choices={choices} onPick={(use) => setPick({ file, choice: use })} />}
|
||||
{asking && file && <LinkQuestion 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')}
|
||||
@@ -256,40 +234,22 @@ export default function NativeImportSheet(): React.ReactElement | null {
|
||||
);
|
||||
}
|
||||
|
||||
function LinkQuestion({
|
||||
choices,
|
||||
onPick,
|
||||
}: {
|
||||
choices: LinkChoice[];
|
||||
onPick: (choice: LinkChoice) => void;
|
||||
}): React.ReactElement {
|
||||
function LinkQuestion({ onPick }: { onPick: (choice: LinkChoice) => void }): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
{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')}
|
||||
/>
|
||||
)}
|
||||
<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')}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -925,23 +925,3 @@ 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; notes?: 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; 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, notes, setNotes,
|
||||
shown: held, editing, setEditing, name, setName, address, setAddress, categoryId, setCategoryId, description, setDescription,
|
||||
links, setLinks, labelIds, toggleLabel, saving, imgBusy, cover, assignedLabels, handleImagePick, handleImageRemove, cancelEdit, save,
|
||||
} = useCollectionPlaceForm({
|
||||
place, labels, onSave, onUploadImage, t, normalizeLinkUrl, holdLastPlace: true, dropPhotoOnPlaceUpdate: true,
|
||||
@@ -195,8 +195,6 @@ 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">
|
||||
@@ -230,15 +228,6 @@ 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,13 +138,6 @@ 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,
|
||||
@@ -705,8 +698,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
entry={editingEntry}
|
||||
galleryPhotos={gallery}
|
||||
quickCapture={editingEntry.id === 0}
|
||||
readOnly={!canEditEntries || readingEntry}
|
||||
onEdit={readingEntry ? () => setEditEntryId(editingEntry.id) : undefined}
|
||||
readOnly={!canEditEntries}
|
||||
showVerdict={current.show_verdict !== 0}
|
||||
showMood={current.show_mood !== 0}
|
||||
showWeather={current.show_weather !== 0}
|
||||
@@ -714,12 +706,12 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
trips={current.trips}
|
||||
photoProviders={availableProviders}
|
||||
onMoveEarlier={
|
||||
canEditEntries && !readingEntry && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveUp
|
||||
canEditEntries && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveUp
|
||||
? () => { void moveWithinDay(editingEntry, -1) }
|
||||
: undefined
|
||||
}
|
||||
onMoveLater={
|
||||
canEditEntries && !readingEntry && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveDown
|
||||
canEditEntries && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveDown
|
||||
? () => { void moveWithinDay(editingEntry, 1) }
|
||||
: undefined
|
||||
}
|
||||
@@ -728,7 +720,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
? () => { setEditingEntry(null); void dismissSuggestion(editingEntry) }
|
||||
: undefined
|
||||
}
|
||||
onClose={() => { setEditingEntry(null); setEditEntryId(null) }}
|
||||
onClose={() => setEditingEntry(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,9 +1,5 @@
|
||||
import { useRef, useState, type CSSProperties } from '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 { Briefcase, Camera, Plus, Image, Images, X, MapPin, Locate, Trash2, CheckCircle2, MinusCircle, ChevronUp, ChevronDown, EyeOff, Play, NotebookPen } from 'lucide-react'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import MToggle from '../../components/MToggle'
|
||||
@@ -52,11 +48,6 @@ 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[]
|
||||
/**
|
||||
@@ -96,16 +87,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, onEdit, onMoveEarlier, onMoveLater, onDismiss,
|
||||
showVerdict = true, showMood = true, showWeather = true, onMoveEarlier, onMoveLater, onDismiss,
|
||||
onClose, onSave, onUploadPhotos, onAddProviderPhotos, onDelete, onDone,
|
||||
}: MJourneyEntrySheetProps) {
|
||||
const { t, language } = useTranslation()
|
||||
const { t } = 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, canReorder, pendingFiles, setPendingFiles, pendingPreviews, setPendingProviderGroups,
|
||||
photos, photoOrder, pendingFiles, setPendingFiles, pendingPreviews, setPendingProviderGroups,
|
||||
showGalleryPick, setShowGalleryPick, isDirty, availableGalleryPhotos, queuedProviderPhotos, providerAssetIds,
|
||||
contextLocation, offersStatsToggle, addVerdictRow, verdictRowRef, addTag, handleSave, handleFileChange,
|
||||
pickGalleryPhoto, removePhoto, searchLocation, pickLocation, handleUseCurrentLocation,
|
||||
@@ -113,11 +104,6 @@ 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)
|
||||
@@ -135,20 +121,6 @@ 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)]'
|
||||
|
||||
@@ -158,7 +130,7 @@ export default function MJourneyEntrySheet({
|
||||
onClose={handleClose}
|
||||
variant="card"
|
||||
form
|
||||
ariaLabel={heading}
|
||||
ariaLabel={entry.id === 0 ? t('journey.detail.newEntry') : t('journey.detail.editEntry')}
|
||||
>
|
||||
{/* 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">
|
||||
@@ -166,13 +138,8 @@ 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">
|
||||
{heading}
|
||||
{entry.id === 0 ? t('journey.detail.newEntry') : t('journey.detail.editEntry')}
|
||||
</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')}>
|
||||
@@ -381,15 +348,9 @@ export default function MJourneyEntrySheet({
|
||||
)}
|
||||
|
||||
{(photos.length > 0 || pendingFiles.length > 0) && (
|
||||
<div className="mt-[10px] flex flex-wrap gap-2" data-touch-drag={sortable ? '' : undefined}>
|
||||
<div className="mt-[10px] flex flex-wrap gap-2">
|
||||
{photos.map((p, idx) => (
|
||||
<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)]' : ''}`}
|
||||
>
|
||||
<div key={p.id} className="relative h-16 w-16 overflow-hidden rounded-[13px]">
|
||||
{posterlessVideo(p) ? (
|
||||
<ClipTile />
|
||||
) : (
|
||||
@@ -553,7 +514,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. */}
|
||||
{!reading && <div className="mt-3 grid grid-cols-[minmax(0,1fr)_104px] gap-2">
|
||||
<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
|
||||
@@ -568,9 +529,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>
|
||||
|
||||
{!reading && tripSuggestion.trip && (
|
||||
{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">
|
||||
@@ -584,13 +545,7 @@ export default function MJourneyEntrySheet({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 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>
|
||||
)) : (
|
||||
{/* Location */}
|
||||
<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}`}>
|
||||
@@ -639,13 +594,11 @@ 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. */}
|
||||
{/* Settings of the entry, not its content: an editor reading it does not need them locked in view. */}
|
||||
{offersStatsToggle && !reading && (
|
||||
{offersStatsToggle && (
|
||||
<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>
|
||||
@@ -656,22 +609,19 @@ export default function MJourneyEntrySheet({
|
||||
)}
|
||||
|
||||
{/* Kept among the contributors until it is ready (#696). */}
|
||||
{!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 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>
|
||||
|
||||
{/* Mood */}
|
||||
{/* Read, only what was chosen shows, and nothing when nothing was. */}
|
||||
{showMood && !captureOnly && (!reading || MOBILE_MOODS.some(m => m.id === mood)) && <>
|
||||
{showMood && !captureOnly && <>
|
||||
<div className={`${eyebrow} mb-[6px] mt-3`}>{t('journey.editor.mood')}</div>
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{(reading ? MOBILE_MOODS.filter(m => m.id === mood) : MOBILE_MOODS).map(m => {
|
||||
{MOBILE_MOODS.map(m => {
|
||||
const active = mood === m.id
|
||||
return (
|
||||
<button
|
||||
@@ -694,10 +644,10 @@ export default function MJourneyEntrySheet({
|
||||
</>}
|
||||
|
||||
{/* Weather */}
|
||||
{showWeather && (!reading || MOBILE_WEATHERS.some(w => w.id === weather)) && <>
|
||||
{showWeather && <>
|
||||
<div className={`${eyebrow} mb-[6px] mt-3`}>{t('journey.editor.weather')}</div>
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{(reading ? MOBILE_WEATHERS.filter(w => w.id === weather) : MOBILE_WEATHERS).map(w => {
|
||||
{MOBILE_WEATHERS.map(w => {
|
||||
const active = weather === w.id
|
||||
return (
|
||||
<button
|
||||
@@ -796,7 +746,7 @@ export default function MJourneyEntrySheet({
|
||||
onClick={handleClose}
|
||||
className={`${SHEET_SECONDARY} ms-auto`}
|
||||
>
|
||||
{t(reading ? 'common.close' : 'common.cancel')}
|
||||
{t('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 { useSharedIntoTrip } from '../../../native/useSharedIntoTrip'
|
||||
import { useSharedImportStore } from '../../../native/sharedFiles'
|
||||
import MPlanTimeline from './plan/MPlanTimeline'
|
||||
import MMapArea from './map/MMapArea'
|
||||
import MPlacesBrowser from './places/MPlacesBrowser'
|
||||
@@ -316,11 +316,14 @@ export default function MTripShell({
|
||||
})
|
||||
}, [railDayId, days, dayRail])
|
||||
// The active day's pill glides to the next chip rather than jumping there.
|
||||
// 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) },
|
||||
})
|
||||
// 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])
|
||||
// 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}`)
|
||||
@@ -478,10 +481,7 @@ export default function MTripShell({
|
||||
return () => clearTimeout(timer)
|
||||
}, [boxKey, frameDayId])
|
||||
|
||||
const openSheet = (id: string, payload?: unknown) => {
|
||||
if (id === 'day' && trTab === 'plan') planner.hideOverview()
|
||||
setSheet({ id, payload })
|
||||
}
|
||||
const openSheet = (id: string, payload?: unknown) => setSheet({ id, payload })
|
||||
const closeSheet = () => setSheet(null)
|
||||
|
||||
// A hardware keyboard: ⌘1 to ⌘9 for the trip's sections in rail order, ⌥← and
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { useEffect, useMemo, useState, type MouseEvent } from 'react'
|
||||
import { useEffect, 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'
|
||||
@@ -198,9 +197,6 @@ 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')
|
||||
|
||||
@@ -277,7 +273,6 @@ 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,10 +129,8 @@ const ROW_CODE = 'flex-none whitespace-nowrap font-geist text-[0.71875rem] text-
|
||||
|
||||
// ── b3) Place row ────────────────────────────────────────────────────────────
|
||||
|
||||
export function PlaceRow({ assignment, stopNumber, fullPlace, tour, linkedReservations, chrome, reorder, drag, onOpen, onEdit, onRemove, overrun }: {
|
||||
export function PlaceRow({ assignment, 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. */
|
||||
@@ -184,7 +182,6 @@ export function PlaceRow({ assignment, stopNumber, fullPlace, tour, linkedReserv
|
||||
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 ?? {
|
||||
@@ -200,8 +197,6 @@ export function PlaceRow({ assignment, stopNumber, fullPlace, tour, linkedReserv
|
||||
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,7 +1,6 @@
|
||||
import { ChevronRight, CloudDownload, FileDown, Settings, Settings2, Sparkles } from 'lucide-react'
|
||||
import { ChevronRight, 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'
|
||||
@@ -10,8 +9,6 @@ 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> = {
|
||||
@@ -30,25 +27,9 @@ 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, language } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const { t } = useTranslation()
|
||||
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.
|
||||
@@ -80,20 +61,9 @@ export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
|
||||
shell.setTrTab(id)
|
||||
}
|
||||
|
||||
const actions: { id: string; icon: LucideIcon; label: string; sub?: string; go: () => void }[] = [
|
||||
const actions: { id: string; icon: LucideIcon; label: 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') }]
|
||||
: []),
|
||||
@@ -169,10 +139,7 @@ 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">
|
||||
<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>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.875rem] font-semibold">{action.label}</span>
|
||||
<ChevronRight size={16} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -34,7 +34,6 @@ 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'
|
||||
@@ -104,9 +103,6 @@ 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'
|
||||
|
||||
@@ -270,8 +266,6 @@ 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, type KeyboardEvent } from 'react'
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import DawarichIcon from '../../../../components/shared/DawarichIcon'
|
||||
import {
|
||||
ArrowLeftRight, Bookmark, ChevronRight, ExternalLink, Map as MapIcon, MapPinOff, Navigation, Paperclip,
|
||||
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, timedSlot } from '../../../../utils/dayMerge'
|
||||
import { getPlaceBookings } 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,9 +61,6 @@ 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)
|
||||
@@ -73,7 +70,6 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
planner.setSelectedPlaceId(null)
|
||||
setFilesExpanded(false)
|
||||
setDayPickerOpen(false)
|
||||
setMovingIds(null)
|
||||
setParticipantPickerOpen(false)
|
||||
setColorPickerOpen(false)
|
||||
}
|
||||
@@ -95,20 +91,7 @@ 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)] || []) : []
|
||||
@@ -237,28 +220,8 @@ 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${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>
|
||||
<div className="mt-[2px] font-geist text-[0.6875rem] leading-[1.4] text-m-muted"><bdi>{place.address}</bdi></div>
|
||||
)}
|
||||
{/* A typed address that never got coordinates: no marker, and the sheet says why (#2837). */}
|
||||
{addressWithoutCoordinates(place) && (
|
||||
@@ -365,20 +328,7 @@ 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]'}`}
|
||||
>
|
||||
{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)}
|
||||
{day.title || t('planner.dayN', { n: (day.day_number ?? planner.days.indexOf(day) + 1) || '?' })}
|
||||
{canEditDays && !isTourPlace && place.lat != null && place.lng != null && (
|
||||
// In or out of that day's route (#2532); the icon says which it is.
|
||||
<button
|
||||
@@ -406,7 +356,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
{canEditDays && unassignedDays.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setMovingIds(null); setDayPickerOpen(v => !v) }}
|
||||
onClick={() => 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"
|
||||
@@ -415,22 +365,18 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{(dayPickerOpen || moving) && (
|
||||
{dayPickerOpen && (
|
||||
<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={() => {
|
||||
if (moving) moveToDay(moving, d.id)
|
||||
else planner.handleAssignToDay(place.id, d.id)
|
||||
setDayPickerOpen(false)
|
||||
setMovingIds(null)
|
||||
}}
|
||||
onClick={() => { planner.handleAssignToDay(place.id, d.id); setDayPickerOpen(false) }}
|
||||
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">{dayLabel(d)}</span>
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{d.title || t('planner.dayN', { n: (d.day_number ?? planner.days.indexOf(d) + 1) || '?' })}
|
||||
</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,5 +1,4 @@
|
||||
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'
|
||||
@@ -49,10 +48,6 @@ 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 {
|
||||
@@ -78,7 +73,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, initialQuery, onInitialQueryRun }: PlPlaceSearchProps) {
|
||||
export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggestionName, onResolvingChange }: PlPlaceSearchProps) {
|
||||
const { t, toast } = planner
|
||||
const {
|
||||
query, setQuery, results, suggestions, setSuggestions, acSource, searchSource, searching, googleAnswers,
|
||||
@@ -99,21 +94,8 @@ 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,5 +1,4 @@
|
||||
import { MapPin, Navigation } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { MapPin } from 'lucide-react'
|
||||
import MDancingTrek from '../../../components/MDancingTrek'
|
||||
import { RES_ICONS } from '../../../../components/Planner/DayPlanSidebar.constants'
|
||||
import { formatTime, formatPriceText } from '../../../../utils/formatters'
|
||||
@@ -10,12 +9,10 @@ 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 { listSections, useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
|
||||
import { 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
|
||||
@@ -33,7 +30,10 @@ export default function MBookingsTab({ planner, shell }: MTabScreenProps) {
|
||||
} = useReservationListFilter(allBookings, days, planner.tripMembers.length)
|
||||
const canEdit = planner.can('reservation_edit', planner.trip)
|
||||
|
||||
const sections = listSections(groups, t)
|
||||
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)
|
||||
|
||||
return (
|
||||
<TabScroller wide="full">
|
||||
@@ -176,16 +176,17 @@ 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>
|
||||
)}
|
||||
@@ -195,40 +196,3 @@ 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,20 +45,13 @@ 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] pb-[env(safe-area-inset-bottom,0px)]"
|
||||
className="m-root fixed inset-0 z-[65] flex flex-col bg-black/[.92]"
|
||||
onClick={onClose}
|
||||
onTouchStart={onTouchStart}
|
||||
onTouchEnd={onTouchEnd}
|
||||
>
|
||||
{/* Header */}
|
||||
{/* 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()}
|
||||
>
|
||||
<div role="presentation" className="flex flex-none items-center justify-between px-4 py-[10px]" 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>
|
||||
@@ -80,13 +73,8 @@ 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="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 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>
|
||||
</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 { listSections, useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
|
||||
import { 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,7 +30,11 @@ export default function MTransportsTab({ planner, shell }: MTabScreenProps) {
|
||||
} = useReservationListFilter(allTransports, days, planner.tripMembers.length)
|
||||
const canEdit = planner.can('day_edit', planner.trip)
|
||||
|
||||
const sections = listSections(groups, t)
|
||||
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)
|
||||
|
||||
return (
|
||||
<TabScroller wide="full">
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
// 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();
|
||||
});
|
||||
});
|
||||
@@ -1,115 +0,0 @@
|
||||
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);
|
||||
});
|
||||
}
|
||||
@@ -81,50 +81,3 @@ html[data-touch-input]
|
||||
--tw-ring-offset-shadow: 0 0 #0000;
|
||||
--tw-ring-shadow: 0 0 #0000;
|
||||
}
|
||||
|
||||
/* The handover from the app's address screen to this server's UI
|
||||
(native/appBoot.ts): the waiting states stand on that screen's colour, with
|
||||
its spinner, which fades in only once the wait is long enough to notice. */
|
||||
html[data-app-boot] .app-boot {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: #fffaf5;
|
||||
}
|
||||
html[data-app-boot] .app-boot span {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
border: 2.5px solid #6b5f57;
|
||||
border-top-color: transparent;
|
||||
animation:
|
||||
trek-boot-spin 0.8s linear infinite,
|
||||
trek-image-in 0.3s ease-out 0.6s both;
|
||||
}
|
||||
@keyframes trek-boot-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
/* Signed in from the app's sign-in screen: the app rises in on the page
|
||||
colour instead of cutting in (native/appBoot.ts endAppBoot). */
|
||||
html[data-app-enter] #root {
|
||||
animation: trek-app-enter 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) both;
|
||||
}
|
||||
@keyframes trek-app-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.97);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
html[data-app-enter] #root {
|
||||
animation-duration: 0.01s;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,25 +22,13 @@ export interface SharedLink {
|
||||
presetTripId: number | null;
|
||||
}
|
||||
|
||||
/** A shared map link on its way to a trip's new place (#2582). */
|
||||
interface SharedPlaceLink {
|
||||
tripId: number;
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface SharedImportState {
|
||||
file: File | null;
|
||||
/** The trip whose booking import takes the file; the planner of that trip takes it from here. */
|
||||
tripId: number | null;
|
||||
link: SharedLink | null;
|
||||
/** A map link picked to become a place: the trip's new place sheet looks it up. */
|
||||
placeLink: SharedPlaceLink | null;
|
||||
setFile: (file: File | null, link?: SharedLink | null) => void;
|
||||
chooseTrip: (tripId: number) => void;
|
||||
/** The shared link goes to this trip as a place; the sheet's queue is done with it. */
|
||||
choosePlaceTrip: (tripId: number) => void;
|
||||
/** The trip's place sheet took the link up. */
|
||||
clearPlaceLink: () => void;
|
||||
/** The booking import took the file: the queue is empty again. */
|
||||
take: () => File | null;
|
||||
}
|
||||
@@ -49,14 +37,8 @@ export const useSharedImportStore = create<SharedImportState>((set, get) => ({
|
||||
file: null,
|
||||
tripId: null,
|
||||
link: null,
|
||||
placeLink: null,
|
||||
setFile: (file, link = null) => set({ file, tripId: null, link: file ? link : null }),
|
||||
chooseTrip: (tripId) => set({ tripId }),
|
||||
choosePlaceTrip: (tripId) => {
|
||||
const { link } = get();
|
||||
set({ file: null, tripId: null, link: null, placeLink: link ? { tripId, url: link.url } : null });
|
||||
},
|
||||
clearPlaceLink: () => set({ placeLink: null }),
|
||||
take: () => {
|
||||
const { file } = get();
|
||||
set({ file: null, tripId: null, link: null });
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import { useEffect, useEffectEvent } from 'react';
|
||||
|
||||
import { useSharedImportStore } from './sharedFiles';
|
||||
|
||||
/**
|
||||
* What was shared to TREK and sent to this trip (native/sharedFiles.ts), opened
|
||||
* where it belongs once the trip is on screen: a booking document in the booking
|
||||
* import, a map link in the new place sheet, whose search looks it up (#2582).
|
||||
*/
|
||||
export function useSharedIntoTrip(tripId: number, open: { bookingImport: () => void; newPlace: () => void }): void {
|
||||
const bookingTripId = useSharedImportStore((s) => s.tripId);
|
||||
const placeTripId = useSharedImportStore((s) => s.placeLink?.tripId ?? null);
|
||||
const openBookingImport = useEffectEvent(() => open.bookingImport());
|
||||
const openNewPlace = useEffectEvent(() => open.newPlace());
|
||||
useEffect(() => {
|
||||
if (bookingTripId != null && bookingTripId === tripId) openBookingImport();
|
||||
}, [bookingTripId, tripId]);
|
||||
useEffect(() => {
|
||||
if (placeTripId != null && placeTripId === tripId) openNewPlace();
|
||||
}, [placeTripId, tripId]);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
// FE-PAGE-LOGIN-NATIVE-001: LoginPage inside the iOS/Android app
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, waitFor } from '../../tests/helpers/render';
|
||||
import { resetAllStores } from '../../tests/helpers/store';
|
||||
import LoginPage from './LoginPage';
|
||||
|
||||
vi.mock('../native/platform', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../native/platform')>()),
|
||||
isNativeApp: () => true,
|
||||
nativeServerHost: () => 'trek.example.com',
|
||||
}));
|
||||
vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }));
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
});
|
||||
|
||||
describe('LoginPage in the app', () => {
|
||||
it('FE-PAGE-LOGIN-NATIVE-001: shows the app sign-in screen, without the language menu or the web layout', async () => {
|
||||
const { container } = render(<LoginPage />);
|
||||
await waitFor(() => expect(screen.getByLabelText('Email')).toBeInTheDocument());
|
||||
expect(container.querySelector('.app-login')).toBeInTheDocument();
|
||||
expect(screen.getByText('trek.example.com')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Change language' })).not.toBeInTheDocument();
|
||||
expect(container.querySelector('.lg-panel')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -16,8 +16,7 @@ import ToggleSwitch from '../components/Settings/ToggleSwitch';
|
||||
import { SUPPORTED_LANGUAGES, useTranslation } from '../i18n';
|
||||
import { IDP_LOGIN_URL, useLogin } from './login/useLogin';
|
||||
import LoginWorld from './login/LoginWorld';
|
||||
import AppLogin from './login/AppLogin';
|
||||
import { heading as headingOf, submitLabel } from './login/loginModel';
|
||||
import NativeServerLink from './login/NativeServerLink';
|
||||
import MfaCodeStep from './login/MfaCodeStep';
|
||||
import { LANGUAGE_CORNER_CLASS } from './login/languageCorner';
|
||||
import PasswordChecklist from '../components/shared/PasswordChecklist';
|
||||
@@ -45,10 +44,8 @@ const STARFIELD = [
|
||||
export default function LoginPage(): React.ReactElement {
|
||||
const { t, language } = useTranslation();
|
||||
// Page = wiring container: the whole auth surface lives in the useLogin hook.
|
||||
const login = useLogin();
|
||||
const {
|
||||
navigate,
|
||||
nativeApp,
|
||||
mode,
|
||||
setMode,
|
||||
username,
|
||||
@@ -90,10 +87,8 @@ export default function LoginPage(): React.ReactElement {
|
||||
idpSlow,
|
||||
idpName,
|
||||
handleDemoLogin, handleSubmit, handlePasskeyLogin, handleSsoClick,
|
||||
} = login;
|
||||
} = useLogin();
|
||||
|
||||
const step = { mode, mfaStep, passwordChangeStep, hasUsers: !!appConfig?.has_users };
|
||||
const heading = headingOf(step, t);
|
||||
const oidcButtonShown = !!(appConfig?.oidc_configured && appConfig?.oidc_login && !oidcOnly);
|
||||
const passkeyAvailable = !!(
|
||||
appConfig?.passkey_login &&
|
||||
@@ -120,7 +115,7 @@ export default function LoginPage(): React.ReactElement {
|
||||
transition: 'border-color 0.15s',
|
||||
};
|
||||
|
||||
if (showTakeoff && !nativeApp) {
|
||||
if (showTakeoff) {
|
||||
return (
|
||||
<div
|
||||
className="takeoff-overlay"
|
||||
@@ -232,9 +227,6 @@ export default function LoginPage(): React.ReactElement {
|
||||
);
|
||||
}
|
||||
|
||||
// In the app: the screen continuing its address screen (login/AppLogin.tsx).
|
||||
if (nativeApp) return <AppLogin login={login} />;
|
||||
|
||||
return (
|
||||
<div style={{ minHeight: '100vh', display: 'flex', fontFamily: 'var(--font-system)', position: 'relative' }}>
|
||||
<div className={LANGUAGE_CORNER_CLASS}>
|
||||
@@ -584,10 +576,26 @@ export default function LoginPage(): React.ReactElement {
|
||||
color: '#111827',
|
||||
}}
|
||||
>
|
||||
{heading.title}
|
||||
{passwordChangeStep
|
||||
? t('login.setNewPassword')
|
||||
: mode === 'login' && mfaStep
|
||||
? t('login.mfaTitle')
|
||||
: mode === 'register'
|
||||
? !appConfig?.has_users
|
||||
? t('login.createAdmin')
|
||||
: t('login.createAccount')
|
||||
: t('login.title')}
|
||||
</h2>
|
||||
<p style={{ margin: '0 0 28px', fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', color: '#9ca3af' }}>
|
||||
{heading.subtitle}
|
||||
{passwordChangeStep
|
||||
? t('login.setNewPasswordHint')
|
||||
: mode === 'login' && mfaStep
|
||||
? t('login.mfaSubtitle')
|
||||
: mode === 'register'
|
||||
? !appConfig?.has_users
|
||||
? t('login.createAdminHint')
|
||||
: t('login.createAccountHint')
|
||||
: t('login.subtitle')}
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
@@ -1006,12 +1014,24 @@ export default function LoginPage(): React.ReactElement {
|
||||
animation: 'spin 0.7s linear infinite',
|
||||
}}
|
||||
/>
|
||||
{submitLabel(step, true, t)}
|
||||
{passwordChangeStep
|
||||
? t('settings.updatePassword')
|
||||
: mode === 'register'
|
||||
? t('login.creating')
|
||||
: mode === 'login' && mfaStep
|
||||
? t('login.mfaVerify')
|
||||
: t('login.signingIn')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plane size={16} />
|
||||
{submitLabel(step, false, t)}
|
||||
{passwordChangeStep
|
||||
? t('settings.updatePassword')
|
||||
: mode === 'register'
|
||||
? t('login.createAccount')
|
||||
: mode === 'login' && mfaStep
|
||||
? t('login.mfaVerify')
|
||||
: t('login.signIn')}
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
@@ -1202,6 +1222,7 @@ export default function LoginPage(): React.ReactElement {
|
||||
{t('login.demoHint')}
|
||||
</button>
|
||||
)}
|
||||
<NativeServerLink />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
pushUndo, undo, canUndo, lastActionLabel, handleUndo,
|
||||
enabledAddons, collabFeatures, journalId, tripAccommodations, setTripAccommodations,
|
||||
roadtripMode, toggleRoadtripMode, roadtripActive, roadtripRoutes, roadtripLineColors, roadtripMapLines, roadtripMapPlaces, collapsedRoadtripDays, toggleRoadtripDay, roadtripCorridor,
|
||||
overviewActive, tripOverview, overviewShown,
|
||||
overviewActive, tripOverview, toggleOverview, overviewShown,
|
||||
dawarichEnabled, dawarichTrailShown, toggleDawarichTrail, dawarichTrail, dawarichHiddenDates,
|
||||
followTrack, roadtripViaCounts,
|
||||
allowedFileTypes, tripMembers, setTripMembers, refreshMembers, loadAccommodations,
|
||||
@@ -77,8 +77,8 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
leftWidth, rightWidth,
|
||||
leftHidden, rightHidden, toggleLeft, toggleRight,
|
||||
startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing, resizeMin, resizeMaxLeft, resizeMaxRight,
|
||||
selectedPlaceId, selectedAssignmentId, setSelectedPlaceId,
|
||||
showDayDetail, dayDetailCollapsed, setDayDetailCollapsed,
|
||||
selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment,
|
||||
showDayDetail, setShowDayDetail, dayDetailCollapsed, setDayDetailCollapsed,
|
||||
stayPickerDayId, setStayPickerDayId,
|
||||
showPlaceForm, setShowPlaceForm, editingPlace, setEditingPlace, setPlaceFormDayId,
|
||||
prefillCoords, editingAssignmentId, setEditingAssignmentId, setRoadtripStopKind,
|
||||
@@ -139,10 +139,6 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
locationSearch,
|
||||
dayPlanTours,
|
||||
placeForm,
|
||||
planMap: {
|
||||
leftPanelPx, rightPanelPx, mapInsetLeft, mapInsetRight, overviewRightGap,
|
||||
dayCardRef, overviewCardRef, handleToggleOverview, handleDayDetail, closeDayDetail, openSelectedDayDetail,
|
||||
},
|
||||
} = pageState
|
||||
// Tablets run this very layout but cannot start an HTML5 drag with a finger,
|
||||
// so a long press stands in for one (#1616). Only where the pointer is
|
||||
@@ -199,6 +195,14 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
}
|
||||
if (!trip) return null
|
||||
|
||||
// What each panel actually occupies right now, and where that leaves the
|
||||
// strip of map between them. The panels float 10px inside the map, so the
|
||||
// corridor starts past that margin.
|
||||
const leftPanelPx = leftHidden ? 0 : leftWidth
|
||||
const rightPanelPx = rightHidden ? 0 : rightWidth
|
||||
const mapInsetLeft = leftPanelPx ? leftPanelPx + 10 : 0
|
||||
const mapInsetRight = rightPanelPx ? rightPanelPx + 10 : 0
|
||||
|
||||
// The place inspector and the tour dialog open on the selected place, beside
|
||||
// the panels or in the phone-width sheet. What every one of them gets; each
|
||||
// call site adds what differs.
|
||||
@@ -272,7 +276,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
roadtripRoutes={roadtripRoutes} roadtripConnections={roadtripConnections} roadtripVias={roadtripVias}
|
||||
dayBoundaryControls={dayBoundaryControls} dropPoiOnRoute={dropPoiOnRoute} addRoadtripVia={addRoadtripVia} moveRoadtripVia={moveRoadtripVia} removeRoadtripVia={removeRoadtripVia}
|
||||
routeAlternatives={routeAlternatives} alternativeOverlays={alternativeOverlays} highlightedAlternative={highlightedAlternative} chooseRouteAlternative={chooseRouteAlternative} setHighlightedAlternative={setHighlightedAlternative}
|
||||
overviewActive={overviewActive} tripOverview={tripOverview} overviewShown={overviewShown} toggleOverview={handleToggleOverview} overviewCardRef={overviewCardRef}
|
||||
overviewActive={overviewActive} tripOverview={tripOverview} overviewShown={overviewShown} toggleOverview={toggleOverview}
|
||||
dawarichEnabled={dawarichEnabled} dawarichTrail={dawarichTrail} dawarichHiddenDates={dawarichHiddenDates} dawarichTrailShown={dawarichTrailShown} toggleDawarichTrail={toggleDawarichTrail}
|
||||
mobileSidebarOpen={mobileSidebarOpen} showPlaceForm={showPlaceForm} showMembersModal={showMembersModal} showReservationModal={showReservationModal}
|
||||
poi={poi} tourMap={tourMap} leftPanelPx={leftPanelPx} rightPanelPx={rightPanelPx} mapInsetLeft={mapInsetLeft} mapInsetRight={mapInsetRight}
|
||||
@@ -339,7 +343,6 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
categories={categories}
|
||||
assignments={storedAssignments}
|
||||
selectedDayId={selectedDayId}
|
||||
openSelectedDayDetail={openSelectedDayDetail}
|
||||
selectedPlaceId={selectedPlaceId}
|
||||
selectedAssignmentId={selectedAssignmentId}
|
||||
onSelectDay={handleSelectDay}
|
||||
@@ -371,8 +374,8 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true) } : undefined}
|
||||
// The narrow layout keeps what a booking row opened before.
|
||||
onOpenBooking={isMobile ? undefined : openBookingFromDayList}
|
||||
onDayDetail={handleDayDetail}
|
||||
onAddAccommodation={can('day_edit', trip) ? (day) => { handleSelectDay(day.id); handleDayDetail(day); setStayPickerDayId(day.id) } : undefined}
|
||||
onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }}
|
||||
onAddAccommodation={can('day_edit', trip) ? (day) => { handleSelectDay(day.id); setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null); setStayPickerDayId(day.id) } : undefined}
|
||||
onRemoveAssignment={handleRemoveAssignment}
|
||||
onEditPlace={(place, assignmentId) => {
|
||||
// The day is cleared on the way in: the form assigns to whatever
|
||||
@@ -520,12 +523,10 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
lat={weatherLat}
|
||||
lng={weatherLng}
|
||||
weatherPlaceName={weatherPlaceName}
|
||||
panelRef={dayCardRef}
|
||||
onClose={() => { closeDayDetail(); handleSelectDay(null) }}
|
||||
onClose={() => { setShowDayDetail(null); handleSelectDay(null) }}
|
||||
onAccommodationChange={loadAccommodations}
|
||||
leftWidth={isMobile ? 0 : leftPanelPx}
|
||||
rightWidth={isMobile ? 0 : rightPanelPx}
|
||||
rightGap={isMobile || roadtripActive ? undefined : overviewRightGap}
|
||||
collapsed={dayDetailCollapsed}
|
||||
onToggleCollapse={() => setDayDetailCollapsed(c => !c)}
|
||||
mobile={isMobile}
|
||||
@@ -606,7 +607,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
</div>
|
||||
<div style={{ flex: 1, overflow: 'auto', paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}>
|
||||
{mobileSidebarOpen === 'left'
|
||||
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} {...dayPlanTours} categories={categories} assignments={storedAssignments} selectedDayId={selectedDayId} openSelectedDayDetail={openSelectedDayDetail} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onReorderDays={handleReorderDays} onAddDay={handleAddDay} dayAdd={dayAdd} onDeleteDay={handleDeleteDay} deleteDayQuestion={deleteDayQuestion} onClearDay={can('day_edit', trip) ? handleClearDay : undefined} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onMoveToDay={handleMoveToDay} onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } else { setRoute(null); setRouteInfo(null) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} allConnectionsShown={allConnectionsShown} onToggleAllConnections={toggleAllConnections} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(false); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onOpenTransit={(r) => { setTransitJourney(r); setMobileSidebarOpen(null) }} onPlanTransit={can('day_edit', trip) && tripHasDates ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onPlanTransitLeg={can('day_edit', trip) && tripHasDates ? ({ dayId, ...leg }) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(leg); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onCreatePlaceForDay={can('place_edit', trip) ? (dayId) => { setEditingPlace(null); setPlaceFormDayId(dayId); setShowPlaceForm(true); setMobileSidebarOpen(null) } : undefined} onDayDetail={handleDayDetail} onRemoveAssignment={handleRemoveAssignment} onEditPlace={(place, assignmentId) => { setEditingPlace(place); setEditingAssignmentId(assignmentId || null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} roadtripViasByDay={roadtripVias.byDay} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} showRouteToolsWhenExpanded isMobile />
|
||||
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} {...dayPlanTours} categories={categories} assignments={storedAssignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onReorderDays={handleReorderDays} onAddDay={handleAddDay} dayAdd={dayAdd} onDeleteDay={handleDeleteDay} deleteDayQuestion={deleteDayQuestion} onClearDay={can('day_edit', trip) ? handleClearDay : undefined} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onMoveToDay={handleMoveToDay} onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } else { setRoute(null); setRouteInfo(null) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} allConnectionsShown={allConnectionsShown} onToggleAllConnections={toggleAllConnections} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(false); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onOpenTransit={(r) => { setTransitJourney(r); setMobileSidebarOpen(null) }} onPlanTransit={can('day_edit', trip) && tripHasDates ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onPlanTransitLeg={can('day_edit', trip) && tripHasDates ? ({ dayId, ...leg }) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(leg); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onCreatePlaceForDay={can('place_edit', trip) ? (dayId) => { setEditingPlace(null); setPlaceFormDayId(dayId); setShowPlaceForm(true); setMobileSidebarOpen(null) } : undefined} onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }} onRemoveAssignment={handleRemoveAssignment} onEditPlace={(place, assignmentId) => { setEditingPlace(place); setEditingAssignmentId(assignmentId || null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} roadtripViasByDay={roadtripVias.byDay} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} showRouteToolsWhenExpanded isMobile />
|
||||
: <PlacesSidebar tripId={tripId} places={places} toursEnabled={toursEnabled} excludePlaceIds={toursEnabled ? tourPlaceIds : undefined} onToursChanged={placeIds => invalidateTourPlaceIds(placeIds ? { placeIds } : undefined)} categories={categories} assignments={assignments} accommodations={tripAccommodations} selectedDayId={selectedDayId} onClearSelectedDay={() => handleSelectDay(null)} selectedPlaceId={selectedPlaceId} onPlaceClick={(placeId) => { handlePlaceClick(placeId); setMobileSidebarOpen(null) }} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onAssignToDay={handleAssignToDay} onEditPlace={(place) => { openPlaceEditor(place); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} onBulkDeletePlaces={(ids) => setDeletePlaceIds(ids)} onBulkDeleteConfirm={(ids) => confirmDeletePlaces(ids)} onBulkChangeCategory={(ids, catId) => confirmChangeCategory(ids, catId)} days={days} isMobile pushUndo={pushUndo} initialScrollTop={mobilePlacesScrollTopRef.current} onScrollTopChange={(top) => { mobilePlacesScrollTopRef.current = top }} />
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -50,7 +50,7 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
|
||||
const navigate = useNavigate()
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
const { current, loading, notFound, loadJourney, refreshJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto } = useJourneyStore()
|
||||
const { current, loading, notFound, loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto } = useJourneyStore()
|
||||
const mapRef = useRef<JourneyMapHandle>(null)
|
||||
const fullMapRef = useRef<JourneyMapHandle>(null)
|
||||
/** The gallery hands its file picker up here, so the hero button can open it. */
|
||||
@@ -341,7 +341,7 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
|
||||
|
||||
// Provider photos from the gallery picker and from the entry editor, the same
|
||||
// way on desktop and phone (#1587).
|
||||
const providerPhotos = useProviderPhotoAdds(() => { void refreshJourney(Number(id)) })
|
||||
const providerPhotos = useProviderPhotoAdds(() => { void loadJourney(Number(id)) })
|
||||
|
||||
const restoreSuggestions = useCallback(async () => {
|
||||
if (!current) return
|
||||
@@ -539,7 +539,7 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
|
||||
recordingPrep, recordings, canTakeOverRecording, recordingNeedsConnection, mapTracks, mapLayers, entryTitleOf,
|
||||
dayImport, dayImportDates,
|
||||
} = useJourneyDetailLayers({
|
||||
journey: current, loaded: journeyLoaded, canEditEntries, loadJourney: refreshJourney, dawarich, dawarichByDate, dawarichTrail,
|
||||
journey: current, loaded: journeyLoaded, canEditEntries, loadJourney, dawarich, dawarichByDate, dawarichTrail,
|
||||
tripDates, sidebarMapItems, photoCount: mapPhotos.length, showTripTracks,
|
||||
})
|
||||
|
||||
@@ -592,8 +592,7 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
|
||||
recordings, canTakeOverRecording, recordingNeedsConnection, dayImport, dayImportDates, recordingPrep,
|
||||
mapPhotos, openMapPhotos,
|
||||
feedEdge, scrollFeedTo,
|
||||
// The views reload after their own changes; such a read never rejects.
|
||||
loadJourney: refreshJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto,
|
||||
loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto,
|
||||
addPickedProviderPhotos: providerPhotos.addPickedPhotos,
|
||||
addEntryProviderPhotos: providerPhotos.addEntryPhotos,
|
||||
// A planned place picked on the map that nothing was written about yet: write it up.
|
||||
|
||||
@@ -63,7 +63,7 @@ export function useJourneyStudio() {
|
||||
const location = useLocation()
|
||||
const { t, locale } = useTranslation()
|
||||
const isMobile = useIsMobile()
|
||||
const { current, loading, refreshJourney } = useJourneyStore()
|
||||
const { current, loading, loadJourney } = useJourneyStore()
|
||||
|
||||
const doc = useStudioStore(s => s.doc)
|
||||
const loadDoc = useStudioStore(s => s.load)
|
||||
@@ -211,8 +211,8 @@ export function useJourneyStudio() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!Number.isFinite(journeyId)) return
|
||||
if (!current || current.id !== journeyId) void refreshJourney(journeyId)
|
||||
}, [journeyId, current, refreshJourney])
|
||||
if (!current || current.id !== journeyId) void loadJourney(journeyId)
|
||||
}, [journeyId, current, loadJourney])
|
||||
|
||||
// Lay the book out once, from the journey. After that it is an ordinary
|
||||
// document and this must not run again, or it would throw away the user's
|
||||
@@ -672,7 +672,7 @@ export function useJourneyStudio() {
|
||||
* the new ones the way it shows an upload.
|
||||
*/
|
||||
const photoProviders = useConnectedPhotoProviders(canEdit)
|
||||
const providerAdds = useProviderPhotoAdds(() => { void refreshJourney(journeyId) })
|
||||
const providerAdds = useProviderPhotoAdds(() => { void loadJourney(journeyId) })
|
||||
const [providerPick, setProviderPick] = useState<{ provider: string; entryId: number | null } | null>(null)
|
||||
const pickAnswer = useRef<((photoIds: number[]) => void) | null>(null)
|
||||
const answerPick = (photoIds: number[]) => {
|
||||
|
||||
@@ -1,231 +0,0 @@
|
||||
// FE-LOGIN-APP-001 to FE-LOGIN-APP-011: the sign-in screen inside the iOS/Android app
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { buildAppConfig } from '../../../tests/helpers/factories';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import { nativeServerHost } from '../../native/platform';
|
||||
import { TrekShell } from '../../native/trekShell';
|
||||
import AppLogin from './AppLogin';
|
||||
import type { useLogin } from './useLogin';
|
||||
|
||||
type Login = ReturnType<typeof useLogin>;
|
||||
type LoginConfig = NonNullable<Login['appConfig']>;
|
||||
|
||||
/** The sign-in page's own config shape, on top of the shared factory's. */
|
||||
function appConfigOf(overrides: Partial<LoginConfig> = {}): LoginConfig {
|
||||
return { ...buildAppConfig({ has_users: true }), setup_complete: true, ...overrides } as LoginConfig;
|
||||
}
|
||||
|
||||
vi.mock('../../native/platform', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../native/platform')>()),
|
||||
nativeServerHost: vi.fn(),
|
||||
}));
|
||||
vi.mock('../../native/trekShell', () => ({ TrekShell: { resetServer: vi.fn() } }));
|
||||
// The landscape is a WebGL loop, which jsdom cannot draw.
|
||||
vi.mock('../../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }));
|
||||
|
||||
function buildLogin(overrides: Partial<Login> = {}): Login {
|
||||
const login = {
|
||||
navigate: vi.fn(),
|
||||
nativeApp: true,
|
||||
mode: 'login',
|
||||
setMode: vi.fn(),
|
||||
username: '',
|
||||
setUsername: vi.fn(),
|
||||
email: '',
|
||||
setEmail: vi.fn(),
|
||||
password: '',
|
||||
setPassword: vi.fn(),
|
||||
rememberMe: true,
|
||||
setRememberMe: vi.fn(),
|
||||
showPassword: false,
|
||||
setShowPassword: vi.fn(),
|
||||
isLoading: false,
|
||||
error: '',
|
||||
setError: vi.fn(),
|
||||
insecureCookie: false,
|
||||
appConfig: appConfigOf(),
|
||||
inviteToken: '',
|
||||
langDropdownOpen: false,
|
||||
setLangDropdownOpen: vi.fn(),
|
||||
setLanguageLocal: vi.fn(),
|
||||
showTakeoff: false,
|
||||
mfaStep: false,
|
||||
setMfaStep: vi.fn(),
|
||||
mfaToken: '',
|
||||
setMfaToken: vi.fn(),
|
||||
mfaCode: '',
|
||||
setMfaCode: vi.fn(),
|
||||
passwordChangeStep: false,
|
||||
newPassword: '',
|
||||
setNewPassword: vi.fn(),
|
||||
confirmPassword: '',
|
||||
setConfirmPassword: vi.fn(),
|
||||
noRedirect: false,
|
||||
showRegisterOption: false,
|
||||
oidcOnly: false,
|
||||
redirectScreen: false,
|
||||
configWait: false,
|
||||
idpSlow: false,
|
||||
idpName: 'SSO',
|
||||
handleDemoLogin: vi.fn(),
|
||||
handleSubmit: vi.fn((e: React.FormEvent) => e.preventDefault()),
|
||||
handlePasskeyLogin: vi.fn(),
|
||||
handleSsoClick: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
return login as unknown as Login;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.mocked(nativeServerHost).mockReturnValue('trek.example.com');
|
||||
vi.mocked(TrekShell.resetServer).mockReset().mockResolvedValue();
|
||||
});
|
||||
|
||||
describe('AppLogin', () => {
|
||||
it('FE-LOGIN-APP-001: shows the server it signs in to, no language menu, and leads back to the address screen', () => {
|
||||
render(<AppLogin login={buildLogin()} />);
|
||||
expect(screen.getByText('trek.example.com')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Change language' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change server' }));
|
||||
expect(TrekShell.resetServer).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-LOGIN-APP-002: signs in with email and password, with the fields password managers fill', () => {
|
||||
// Filled, as the hook would hold them: the form refuses to submit with its required fields empty.
|
||||
const login = buildLogin({ email: 'old@example.com', password: 'old' });
|
||||
render(<AppLogin login={login} />);
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Sign In' })).toBeInTheDocument();
|
||||
expect(screen.queryByText('Welcome back')).not.toBeInTheDocument();
|
||||
const email = screen.getByLabelText('Email');
|
||||
const password = screen.getByLabelText('Password');
|
||||
expect(email).toHaveAttribute('autocomplete', 'username');
|
||||
expect(password).toHaveAttribute('autocomplete', 'current-password');
|
||||
|
||||
fireEvent.change(email, { target: { value: 'me@example.com' } });
|
||||
fireEvent.change(password, { target: { value: 'secret' } });
|
||||
expect(login.setEmail).toHaveBeenCalledWith('me@example.com');
|
||||
expect(login.setPassword).toHaveBeenCalledWith('secret');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Sign In' }));
|
||||
expect(login.handleSubmit).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-LOGIN-APP-003: shows the password, remembers the login and keeps the way to a new password last', () => {
|
||||
const login = buildLogin();
|
||||
render(<AppLogin login={login} />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Show password' }));
|
||||
expect(login.setShowPassword).toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Remember me' }));
|
||||
expect(login.setRememberMe).toHaveBeenCalledWith(false);
|
||||
|
||||
const forgot = screen.getByRole('button', { name: 'Forgot password?' });
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons[buttons.length - 1]).toBe(forgot);
|
||||
fireEvent.click(forgot);
|
||||
expect(login.navigate).toHaveBeenCalledWith('/forgot-password');
|
||||
});
|
||||
|
||||
it('FE-LOGIN-APP-004: offers SSO beside the password, carrying the remember-me choice', () => {
|
||||
const login = buildLogin({
|
||||
rememberMe: false,
|
||||
appConfig: appConfigOf({
|
||||
has_users: true,
|
||||
oidc_configured: true,
|
||||
oidc_login: true,
|
||||
oidc_display_name: 'Pocket ID',
|
||||
}),
|
||||
});
|
||||
render(<AppLogin login={login} />);
|
||||
|
||||
const sso = screen.getByRole('link', { name: 'Sign in with Pocket ID' });
|
||||
expect(sso).toHaveAttribute('href', '/api/auth/oidc/login?remember=0');
|
||||
fireEvent.click(sso);
|
||||
expect(login.handleSsoClick).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-LOGIN-APP-005: offers only SSO on an OIDC-only install', () => {
|
||||
render(
|
||||
<AppLogin
|
||||
login={buildLogin({
|
||||
oidcOnly: true,
|
||||
inviteToken: 'abc',
|
||||
appConfig: appConfigOf({ has_users: true, oidc_display_name: 'Authentik' }),
|
||||
})}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByRole('link', { name: 'Sign in with Authentik' })).toHaveAttribute(
|
||||
'href',
|
||||
'/api/auth/oidc/login?invite=abc&remember=1'
|
||||
);
|
||||
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-LOGIN-APP-006: offers a passkey where the server allows one', () => {
|
||||
const login = buildLogin({
|
||||
appConfig: appConfigOf({ has_users: true, passkey_login: true, passkey_configured: true }),
|
||||
});
|
||||
render(<AppLogin login={login} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Sign in with a passkey' }));
|
||||
expect(login.handlePasskeyLogin).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-LOGIN-APP-007: asks for the one-time code in the second step, with the way back', () => {
|
||||
const login = buildLogin({ mfaStep: true, email: 'me@example.com' });
|
||||
render(<AppLogin login={login} />);
|
||||
|
||||
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument();
|
||||
const code = document.getElementById('totp') as HTMLInputElement;
|
||||
expect(code).toHaveAttribute('autocomplete', 'one-time-code');
|
||||
fireEvent.change(code, { target: { value: 'ab12cd' } });
|
||||
expect(login.setMfaCode).toHaveBeenCalledWith('AB12CD');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '← Back to sign in' }));
|
||||
expect(login.setMfaStep).toHaveBeenCalledWith(false);
|
||||
expect(login.setMfaCode).toHaveBeenCalledWith('');
|
||||
});
|
||||
|
||||
it('FE-LOGIN-APP-008: sets a new password when the account must change it', () => {
|
||||
const login = buildLogin({ passwordChangeStep: true });
|
||||
render(<AppLogin login={login} />);
|
||||
fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'Abcdefgh1!' } });
|
||||
fireEvent.change(screen.getByLabelText('Confirm new password'), { target: { value: 'Abcdefgh1!' } });
|
||||
expect(login.setNewPassword).toHaveBeenCalledWith('Abcdefgh1!');
|
||||
expect(login.setConfirmPassword).toHaveBeenCalledWith('Abcdefgh1!');
|
||||
expect(screen.queryByRole('button', { name: 'Forgot password?' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-LOGIN-APP-009: switches to registering where the server allows it', () => {
|
||||
const login = buildLogin({ showRegisterOption: true });
|
||||
const { rerender } = render(<AppLogin login={login} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Register' }));
|
||||
expect(login.setMode).toHaveBeenCalled();
|
||||
|
||||
rerender(<AppLogin login={buildLogin({ showRegisterOption: true, mode: 'register' })} />);
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Password')).toHaveAttribute('autocomplete', 'new-password');
|
||||
});
|
||||
|
||||
it('FE-LOGIN-APP-010: shows errors and waits in the address screen style', () => {
|
||||
const { rerender } = render(<AppLogin login={buildLogin({ error: 'Invalid credentials' })} />);
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Invalid credentials');
|
||||
|
||||
rerender(<AppLogin login={buildLogin({ redirectScreen: true, idpSlow: true, idpName: 'Authentik' })} />);
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Authentik');
|
||||
expect(screen.queryByLabelText('Email')).not.toBeInTheDocument();
|
||||
|
||||
rerender(<AppLogin login={buildLogin({ configWait: true })} />);
|
||||
expect(screen.getByRole('status', { name: 'Loading...' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-LOGIN-APP-011: steps back once signed in instead of playing the takeoff', () => {
|
||||
const { container } = render(<AppLogin login={buildLogin({ showTakeoff: true })} />);
|
||||
expect(container.querySelector('.app-login')).toHaveClass('al-leaving');
|
||||
expect(container.querySelector('.takeoff-overlay')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,423 +0,0 @@
|
||||
import { AlertCircle, Eye, EyeOff, Fingerprint, Globe, Lock, Shield } from 'lucide-react';
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import ToggleSwitch from '../../components/Settings/ToggleSwitch';
|
||||
import { useNativeServer } from '../../components/Settings/useNativeServer';
|
||||
import PasswordChecklist from '../../components/shared/PasswordChecklist';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { lightStatusBarIcons } from '../../native/appBoot';
|
||||
import { reportNativeFailure } from '../../native/reportFailure';
|
||||
import './appLogin.css';
|
||||
import { heading as headingOf, oidcLoginHref, oidcOnlyHref, submitLabel, type LoginStep } from './loginModel';
|
||||
import { mfaCodeInputProps } from './mfaCodeInput';
|
||||
import { IDP_LOGIN_URL, type useLogin } from './useLogin';
|
||||
|
||||
type Login = ReturnType<typeof useLogin>;
|
||||
|
||||
/**
|
||||
* The sign-in screen inside the iOS and Android app. It follows the app's own
|
||||
* address screen (native-shell/), so it continues it instead of looking like a
|
||||
* web page: the same landscape on top, the card with the server just connected
|
||||
* to, the same fields and buttons. Everything it does comes from useLogin, as
|
||||
* on the browser's LoginPage; only the look and the missing language menu
|
||||
* (the device decides, see useLogin) differ.
|
||||
*/
|
||||
export default function AppLogin({ login }: { login: Login }) {
|
||||
useEffect(() => lightStatusBarIcons(), []);
|
||||
return (
|
||||
<div className={login.showTakeoff ? 'app-login al-leaving' : 'app-login'}>
|
||||
<AppLoginHero />
|
||||
<main className="al-body">
|
||||
<AppLoginContent login={login} />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AppLoginContent({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
if (login.redirectScreen) {
|
||||
return (
|
||||
<div className="al-wait" role="status" aria-live="polite">
|
||||
<span className="al-spin" aria-hidden="true" />
|
||||
<p>{t('login.oidcRedirecting', { name: login.idpName })}</p>
|
||||
{login.idpSlow && (
|
||||
<a href={IDP_LOGIN_URL} onClick={login.handleSsoClick}>
|
||||
{t('login.oidcRedirectSlow', { name: login.idpName })}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (login.configWait) {
|
||||
return (
|
||||
<div className="al-wait" role="status" aria-label={t('common.loading')}>
|
||||
<span className="al-spin" aria-hidden="true" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (login.oidcOnly) return <OidcOnly login={login} />;
|
||||
return <Credentials login={login} />;
|
||||
}
|
||||
|
||||
/** The landscape of the address screen, with the server this screen signs in to. */
|
||||
function AppLoginHero() {
|
||||
const { t } = useTranslation();
|
||||
const { host, changeServer } = useNativeServer();
|
||||
const hero = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const box = hero.current;
|
||||
if (!box) return;
|
||||
let cancelled = false;
|
||||
// The same camera the address screen ends on, so the picture holds still
|
||||
// across the change of screens. The scene stops drawing once its canvas
|
||||
// has left the page.
|
||||
void import('../../../native-shell/scenery')
|
||||
.then(({ startScenery, cameraForPlan }) => {
|
||||
if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false });
|
||||
})
|
||||
// Without the landscape the box keeps its plain sea colour.
|
||||
.catch(reportNativeFailure);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
box.querySelector('canvas.scenery')?.remove();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="al-hero" ref={hero}>
|
||||
<img className="al-logo" src="/logo-light.svg" alt="TREK" />
|
||||
{host && (
|
||||
<div className="al-card">
|
||||
<div className="al-card-text">
|
||||
<small>
|
||||
<Lock size={12} strokeWidth={2.6} aria-hidden="true" />
|
||||
{t('native.connect.yourTrek')}
|
||||
</small>
|
||||
<div className="al-host" dir="ltr">
|
||||
<Globe size={17} aria-hidden="true" />
|
||||
<span>{host}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="al-change" onClick={changeServer} aria-label={t('native.changeServer')}>
|
||||
{t('common.change')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Notice({ tone, children }: { tone?: 'warn'; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className={tone ? `al-notice ${tone}` : 'al-notice'} role={tone ? undefined : 'alert'}>
|
||||
<AlertCircle size={18} aria-hidden="true" />
|
||||
<div>{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A field on a white card, the label above the input, as on the address screen.
|
||||
* A control beside the input (the password's eye) sits outside the label, so
|
||||
* the label names the input alone.
|
||||
*/
|
||||
function Field({
|
||||
label,
|
||||
after,
|
||||
...input
|
||||
}: { label: string; after?: React.ReactNode } & React.InputHTMLAttributes<HTMLInputElement>) {
|
||||
return (
|
||||
<div className={after ? 'al-fld-wrap with-after' : 'al-fld-wrap'}>
|
||||
<label className="al-fld">
|
||||
<span className="al-lab">{label}</span>
|
||||
<input {...input} />
|
||||
</label>
|
||||
{after && <span className="al-after">{after}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OidcOnly({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="al-form">
|
||||
<h1 className="al-title">{t('login.title')}</h1>
|
||||
<p className="al-sub">{login.noRedirect ? t('login.oidcLoggedOut') : t('login.oidcOnly')}</p>
|
||||
{login.error && <Notice>{login.error}</Notice>}
|
||||
<a className="al-cta" href={oidcOnlyHref(login.inviteToken)} onClick={login.handleSsoClick}>
|
||||
<Shield size={18} aria-hidden="true" />
|
||||
{t('login.oidcSignIn', { name: login.appConfig?.oidc_display_name || 'SSO' })}
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function stepOf(login: Login): LoginStep {
|
||||
return {
|
||||
mode: login.mode,
|
||||
mfaStep: login.mfaStep,
|
||||
passwordChangeStep: login.passwordChangeStep,
|
||||
hasUsers: !!login.appConfig?.has_users,
|
||||
};
|
||||
}
|
||||
|
||||
function Credentials({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
const step = stepOf(login);
|
||||
const heading = headingOf(step, t);
|
||||
const onMfa = login.mode === 'login' && login.mfaStep && !login.passwordChangeStep;
|
||||
const onAccount = !(login.mode === 'login' && login.mfaStep) && !login.passwordChangeStep;
|
||||
return (
|
||||
<>
|
||||
<form className="al-form" onSubmit={(e) => void login.handleSubmit(e)}>
|
||||
<h1 className="al-title">{heading.title}</h1>
|
||||
{/* The plain sign-in needs no line under its heading; the other steps say what they ask for. */}
|
||||
{!heading.plain && <p className="al-sub">{heading.subtitle}</p>}
|
||||
<Notices login={login} />
|
||||
{login.passwordChangeStep && <NewPassword login={login} />}
|
||||
{onMfa && <MfaCode login={login} />}
|
||||
{onAccount && <Account login={login} />}
|
||||
<button type="submit" className="al-cta" disabled={login.isLoading}>
|
||||
{login.isLoading && <span className="al-spin" aria-hidden="true" />}
|
||||
{submitLabel(step, login.isLoading, t)}
|
||||
</button>
|
||||
</form>
|
||||
<OtherWays login={login} />
|
||||
<ModeSwitch login={login} />
|
||||
{login.mode === 'login' && onAccount && (
|
||||
<button type="button" className="al-forgot" onClick={() => void login.navigate('/forgot-password')}>
|
||||
{t('login.forgotPassword')}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Notices({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
{login.error && <Notice>{login.error}</Notice>}
|
||||
{login.insecureCookie && !login.appConfig?.managed && (
|
||||
<Notice tone="warn">
|
||||
<b>{t('login.insecureCookie.title')}</b>
|
||||
{t('login.insecureCookie.body')}
|
||||
<br />
|
||||
<a href="https://github.com/liketrek/TREK/wiki/Troubleshooting" target="_blank" rel="noopener noreferrer">
|
||||
{t('login.insecureCookie.link')}
|
||||
</a>
|
||||
</Notice>
|
||||
)}
|
||||
{login.passwordChangeStep && <Notice tone="warn">{t('settings.mustChangePassword')}</Notice>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function NewPassword({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<Field
|
||||
label={t('settings.newPassword')}
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={login.newPassword}
|
||||
onChange={(e) => login.setNewPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<PasswordChecklist password={login.newPassword} className="al-check" tone="light" />
|
||||
<Field
|
||||
label={t('settings.confirmPassword')}
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={login.confirmPassword}
|
||||
onChange={(e) => login.setConfirmPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function MfaCode({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
const back = () => {
|
||||
login.setMfaStep(false);
|
||||
login.setMfaToken('');
|
||||
login.setMfaCode('');
|
||||
login.setError('');
|
||||
};
|
||||
return (
|
||||
<>
|
||||
{/* The account the code belongs to, for password managers (see MfaCodeStep). */}
|
||||
<input
|
||||
type="text"
|
||||
name="username"
|
||||
autoComplete="username"
|
||||
value={login.email}
|
||||
readOnly
|
||||
tabIndex={-1}
|
||||
aria-hidden="true"
|
||||
className="sr-only"
|
||||
/>
|
||||
<Field
|
||||
label={t('login.mfaCodeLabel')}
|
||||
{...mfaCodeInputProps(login.mfaCode, login.setMfaCode, t('login.mfaPlaceholder'))}
|
||||
/>
|
||||
<p className="al-hint">{t('login.mfaHint')}</p>
|
||||
<button type="button" className="al-back" onClick={back}>
|
||||
{t('login.mfaBack')}
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Account({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
const registering = login.mode === 'register';
|
||||
return (
|
||||
<>
|
||||
{registering && (
|
||||
<Field
|
||||
label={t('login.username')}
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
autoCapitalize="none"
|
||||
value={login.username}
|
||||
onChange={(e) => login.setUsername(e.target.value)}
|
||||
required
|
||||
placeholder="admin"
|
||||
/>
|
||||
)}
|
||||
<Field
|
||||
label={t('common.email')}
|
||||
type="email"
|
||||
autoComplete={registering ? 'email' : 'username'}
|
||||
inputMode="email"
|
||||
autoCapitalize="none"
|
||||
value={login.email}
|
||||
onChange={(e) => login.setEmail(e.target.value)}
|
||||
required
|
||||
placeholder={t('login.emailPlaceholder')}
|
||||
/>
|
||||
<Field
|
||||
label={t('common.password')}
|
||||
type={login.showPassword ? 'text' : 'password'}
|
||||
autoComplete={registering ? 'new-password' : 'current-password'}
|
||||
value={login.password}
|
||||
onChange={(e) => login.setPassword(e.target.value)}
|
||||
required
|
||||
placeholder="••••••••"
|
||||
after={
|
||||
<button
|
||||
type="button"
|
||||
className="al-eye"
|
||||
onClick={() => login.setShowPassword((v) => !v)}
|
||||
aria-label={t('native.claim.showPassword')}
|
||||
aria-pressed={login.showPassword}
|
||||
>
|
||||
{login.showPassword ? <EyeOff size={19} /> : <Eye size={19} />}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
{registering && <PasswordChecklist password={login.password} className="al-check" tone="light" />}
|
||||
{!registering && <LoginOptions login={login} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginOptions({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
const toggle = () => login.setRememberMe(!login.rememberMe);
|
||||
return (
|
||||
<div className="al-options">
|
||||
<div className="al-remember">
|
||||
<ToggleSwitch on={login.rememberMe} onToggle={toggle} label={t('login.rememberMe')} />
|
||||
{/* The caption repeats the switch's own name; a tap on it is a shortcut for the switch. */}
|
||||
<span aria-hidden="true" onClick={toggle}>
|
||||
{t('login.rememberMe')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Which of the ways in besides the password this server offers on this step. */
|
||||
function otherWaysOf(login: Login): { sso: boolean; passkey: boolean; demo: boolean } {
|
||||
const config = login.appConfig;
|
||||
const onFirstStep = login.mode === 'login' && !login.mfaStep && !login.passwordChangeStep;
|
||||
return {
|
||||
sso: !!(config?.oidc_configured && config.oidc_login && !login.oidcOnly),
|
||||
passkey: !!(config?.passkey_login && config.passkey_configured && onFirstStep),
|
||||
demo: !!config?.demo_mode,
|
||||
};
|
||||
}
|
||||
|
||||
/** SSO, a passkey and the demo: the ways in besides the password. */
|
||||
function OtherWays({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
const ways = otherWaysOf(login);
|
||||
if (!ways.sso && !ways.passkey && !ways.demo) return null;
|
||||
return (
|
||||
<div className="al-alt">
|
||||
{(ways.sso || ways.passkey) && <div className="al-or">{t('common.or')}</div>}
|
||||
{ways.sso && <SsoButton login={login} />}
|
||||
{ways.passkey && (
|
||||
<button
|
||||
type="button"
|
||||
className="al-cta2"
|
||||
onClick={() => void login.handlePasskeyLogin()}
|
||||
disabled={login.isLoading}
|
||||
>
|
||||
<Fingerprint size={18} aria-hidden="true" />
|
||||
{t('login.passkey.signIn')}
|
||||
</button>
|
||||
)}
|
||||
{ways.demo && (
|
||||
<button
|
||||
type="button"
|
||||
className="al-cta al-demo"
|
||||
onClick={() => void login.handleDemoLogin()}
|
||||
disabled={login.isLoading}
|
||||
>
|
||||
{t('login.demoHint')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SsoButton({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<a
|
||||
className="al-cta2"
|
||||
href={oidcLoginHref(login.inviteToken, login.mode, login.rememberMe)}
|
||||
onClick={login.handleSsoClick}
|
||||
>
|
||||
<Shield size={18} aria-hidden="true" />
|
||||
{t('login.oidcSignIn', { name: login.appConfig?.oidc_display_name || 'SSO' })}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function ModeSwitch({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
const config = login.appConfig;
|
||||
if (!login.showRegisterOption || !config?.has_users || config?.demo_mode || login.passwordChangeStep) return null;
|
||||
const toggle = () => {
|
||||
login.setMode((m) => (m === 'login' ? 'register' : 'login'));
|
||||
login.setError('');
|
||||
login.setMfaStep(false);
|
||||
login.setMfaToken('');
|
||||
login.setMfaCode('');
|
||||
};
|
||||
return (
|
||||
<p className="al-switch">
|
||||
{t(login.mode === 'login' ? 'login.noAccount' : 'login.hasAccount')}{' '}
|
||||
<button type="button" onClick={toggle}>
|
||||
{t(login.mode === 'login' ? 'login.register' : 'login.signIn')}
|
||||
</button>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { KeyRound } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { mfaCodeInputProps } from './mfaCodeInput';
|
||||
|
||||
interface MfaCodeStepProps {
|
||||
/** The account being signed in, kept in the form for password managers. */
|
||||
@@ -54,7 +53,23 @@ export default function MfaCodeStep({ email, code, onCode, inputStyle, onBack }:
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
{...mfaCodeInputProps(code, onCode, t('login.mfaPlaceholder'))}
|
||||
type="text"
|
||||
id="totp"
|
||||
name="totp"
|
||||
// Text, not numeric: backup codes carry letters. The hints are set here
|
||||
// rather than left to native/keyboardFields.ts, because autoFocus gives
|
||||
// the field focus before any touch could prepare it.
|
||||
inputMode="text"
|
||||
autoComplete="one-time-code"
|
||||
autoCapitalize="characters"
|
||||
autoCorrect="off"
|
||||
spellCheck={false}
|
||||
enterKeyHint="go"
|
||||
value={code}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => onCode(e.target.value.toUpperCase().slice(0, 24))}
|
||||
placeholder={t('login.mfaPlaceholder')}
|
||||
required
|
||||
autoFocus
|
||||
style={inputStyle}
|
||||
onFocus={(e: React.FocusEvent<HTMLInputElement>) => (e.target.style.borderColor = '#111827')}
|
||||
onBlur={(e: React.FocusEvent<HTMLInputElement>) => (e.target.style.borderColor = '#e5e7eb')}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useNativeServer } from '../../components/Settings/useNativeServer';
|
||||
import { useTranslation } from '../../i18n';
|
||||
|
||||
/** Inside the iOS/Android app only: the way from the sign-in screen back to the address screen. */
|
||||
export default function NativeServerLink() {
|
||||
const { t } = useTranslation();
|
||||
const { host, changeServer } = useNativeServer();
|
||||
if (!host) return null;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={changeServer}
|
||||
className="mt-4 w-full cursor-pointer border-none bg-transparent p-2 text-caption text-content-muted"
|
||||
>
|
||||
{t('native.changeServer')}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,652 +0,0 @@
|
||||
/*
|
||||
* The sign-in screen inside the iOS and Android app (AppLogin.tsx). It is the
|
||||
* next screen after the app's own address screen (native-shell/), so it wears
|
||||
* that screen's look: the same landscape on top, the same glass card with the
|
||||
* server on it, the same type, fields and buttons on the same warm page. The
|
||||
* values mirror native-shell/shell.css; keep the two in step.
|
||||
*
|
||||
* Light on purpose, like the screens before it: the user's appearance is not
|
||||
* known before signing in. The tokens the shared controls read (ToggleSwitch,
|
||||
* PasswordChecklist) are pinned to the light values inside the screen, so a
|
||||
* dark scheme left on the device does not reach into it.
|
||||
*
|
||||
* Every side is a logical one, so Arabic mirrors the layout on its own.
|
||||
*/
|
||||
|
||||
/*
|
||||
* The text face of the address screen, from the same files it bundles. Loaded
|
||||
* only once a letter of the range is on this screen; Cyrillic and the scripts
|
||||
* it does not cover fall back to the app's own face.
|
||||
*/
|
||||
@font-face {
|
||||
font-family: 'Plus Jakarta Sans';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-500.woff2') format('woff2');
|
||||
unicode-range:
|
||||
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC,
|
||||
U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Plus Jakarta Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-600.woff2') format('woff2');
|
||||
unicode-range:
|
||||
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC,
|
||||
U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Plus Jakarta Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-700.woff2') format('woff2');
|
||||
unicode-range:
|
||||
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC,
|
||||
U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Plus Jakarta Sans';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-ext-500.woff2') format('woff2');
|
||||
unicode-range:
|
||||
U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,
|
||||
U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Plus Jakarta Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-ext-600.woff2') format('woff2');
|
||||
unicode-range:
|
||||
U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,
|
||||
U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Plus Jakarta Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-ext-700.woff2') format('woff2');
|
||||
unicode-range:
|
||||
U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,
|
||||
U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
|
||||
.app-login {
|
||||
--al-page: #fffaf5;
|
||||
--al-ink: #1f1a17;
|
||||
--al-text: #6b5f57;
|
||||
--al-muted: #8a7b6f;
|
||||
--al-faint: #b9ab9e;
|
||||
--al-line: #efe4d8;
|
||||
--al-line-soft: #f3ebe1;
|
||||
--al-sand: #f6efe6;
|
||||
--al-dark: #111827;
|
||||
--al-good: #1d7a46;
|
||||
--al-bad: #b42318;
|
||||
--al-bad-soft: #fbeeec;
|
||||
--al-bad-ink: #8f2a1d;
|
||||
--al-warn-soft: #fdf3e2;
|
||||
--al-warn-ink: #8a5a12;
|
||||
--al-sea: #cfe3ef;
|
||||
--al-text-face: 'Plus Jakarta Sans', var(--font-system);
|
||||
--al-display: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
--al-safe-top: max(env(safe-area-inset-top, 0px), var(--safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
|
||||
--al-safe-bottom: max(
|
||||
env(safe-area-inset-bottom, 0px),
|
||||
var(--safe-area-inset-bottom, 0px),
|
||||
var(--trek-native-safe-bottom, 0px)
|
||||
);
|
||||
--al-safe-start: max(
|
||||
env(safe-area-inset-left, 0px),
|
||||
var(--safe-area-inset-left, 0px),
|
||||
var(--trek-native-safe-left, 0px)
|
||||
);
|
||||
--al-safe-end: max(
|
||||
env(safe-area-inset-right, 0px),
|
||||
var(--safe-area-inset-right, 0px),
|
||||
var(--trek-native-safe-right, 0px)
|
||||
);
|
||||
|
||||
/* What the shared controls inside read. */
|
||||
--accent: var(--al-dark);
|
||||
--accent-text: #fff;
|
||||
--text-primary: var(--al-ink);
|
||||
--border-primary: #e6dccf;
|
||||
--bg-card: #fff;
|
||||
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: none;
|
||||
scrollbar-width: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--al-page);
|
||||
color: var(--al-ink);
|
||||
color-scheme: light;
|
||||
font-family: var(--al-text-face);
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
animation: al-in 0.42s cubic-bezier(0.2, 0.8, 0.2, 1) both;
|
||||
}
|
||||
.app-login::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.app-login *,
|
||||
.app-login *::before,
|
||||
.app-login *::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
@keyframes al-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── The landscape and the server card on it ── */
|
||||
.al-hero {
|
||||
position: relative;
|
||||
flex: none;
|
||||
overflow: hidden;
|
||||
height: min(272px, 33svh);
|
||||
min-height: 200px;
|
||||
margin-bottom: -1px;
|
||||
background: var(--al-sea);
|
||||
}
|
||||
.al-hero .scenery {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
animation: al-in 0.6s ease-out both;
|
||||
}
|
||||
/* The status bar's clock and icons stay readable on the sea. */
|
||||
.al-hero::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
inset-inline: 0;
|
||||
top: 0;
|
||||
height: calc(var(--al-safe-top) + 36px);
|
||||
background: linear-gradient(180deg, rgba(8, 24, 40, 0.28), rgba(8, 24, 40, 0));
|
||||
pointer-events: none;
|
||||
}
|
||||
.al-hero::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset-inline: 0;
|
||||
bottom: -2px;
|
||||
height: 110px;
|
||||
background: linear-gradient(180deg, rgba(255, 250, 245, 0) 0%, rgba(255, 250, 245, 0.8) 55%, #fffaf5 82%);
|
||||
pointer-events: none;
|
||||
}
|
||||
.al-logo {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
top: calc(var(--al-safe-top) + 10px);
|
||||
inset-inline-start: calc(24px + var(--al-safe-start));
|
||||
height: 40px;
|
||||
filter: drop-shadow(0 1px 6px rgba(7, 40, 70, 0.45));
|
||||
}
|
||||
.al-card {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
inset-inline: calc(20px + var(--al-safe-start)) calc(20px + var(--al-safe-end));
|
||||
bottom: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding-block: 12px 13px;
|
||||
padding-inline: 16px 12px;
|
||||
border-radius: 18px;
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
-webkit-backdrop-filter: blur(16px) saturate(1.5);
|
||||
backdrop-filter: blur(16px) saturate(1.5);
|
||||
box-shadow:
|
||||
0 18px 36px -18px rgba(17, 24, 39, 0.55),
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
.al-card-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.al-card small {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
color: var(--al-good);
|
||||
}
|
||||
.al-host {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 5px;
|
||||
min-width: 0;
|
||||
font-family: var(--al-display);
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.02em;
|
||||
color: var(--al-dark);
|
||||
}
|
||||
.al-host svg {
|
||||
flex: none;
|
||||
}
|
||||
.al-host span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.al-change {
|
||||
flex: none;
|
||||
min-height: 36px;
|
||||
padding: 0 13px;
|
||||
border: 0;
|
||||
border-radius: 11px;
|
||||
background: #fff;
|
||||
color: var(--al-dark);
|
||||
font: 700 13.5px var(--al-text-face);
|
||||
cursor: pointer;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
/* ── The content ── */
|
||||
.al-body {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-block: 6px calc(28px + var(--al-safe-bottom));
|
||||
padding-inline: calc(24px + var(--al-safe-start)) calc(24px + var(--al-safe-end));
|
||||
}
|
||||
.al-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
.al-title {
|
||||
margin: 0;
|
||||
font-family: var(--al-display);
|
||||
font-size: calc(28px * var(--fs-scale-title, 1));
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.02em;
|
||||
line-height: 1.12;
|
||||
text-wrap: balance;
|
||||
}
|
||||
.al-sub {
|
||||
margin: 4px 0 6px;
|
||||
font-size: calc(15px * var(--fs-scale-body, 1));
|
||||
line-height: 1.5;
|
||||
color: var(--al-text);
|
||||
}
|
||||
|
||||
/* A field on a white card: the label above, the input below it. */
|
||||
.al-fld {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 10px 16px 11px;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 0 1px var(--al-line);
|
||||
cursor: text;
|
||||
transition: box-shadow 0.2s;
|
||||
}
|
||||
.al-fld:focus-within {
|
||||
box-shadow: 0 0 0 2px var(--al-dark);
|
||||
}
|
||||
.al-lab {
|
||||
font-size: calc(12px * var(--fs-scale-body, 1));
|
||||
font-weight: 700;
|
||||
color: var(--al-muted);
|
||||
}
|
||||
.al-fld-wrap {
|
||||
position: relative;
|
||||
}
|
||||
.al-fld-wrap.with-after .al-fld input {
|
||||
padding-inline-end: 40px;
|
||||
}
|
||||
.al-after {
|
||||
position: absolute;
|
||||
inset-inline-end: 8px;
|
||||
bottom: 4px;
|
||||
}
|
||||
.al-fld input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
border: 0;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
/* 16 px or more, or iOS zooms into the field on focus. */
|
||||
font: 600 16px var(--al-text-face);
|
||||
color: var(--al-ink);
|
||||
}
|
||||
.al-fld input::placeholder {
|
||||
color: var(--al-faint);
|
||||
font-weight: 500;
|
||||
}
|
||||
.al-eye {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border: 0;
|
||||
border-radius: 10px;
|
||||
background: transparent;
|
||||
color: var(--al-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.al-check {
|
||||
margin-top: -4px;
|
||||
}
|
||||
|
||||
.al-options {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-height: 44px;
|
||||
}
|
||||
.al-remember {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
font-size: calc(14px * var(--fs-scale-body, 1));
|
||||
font-weight: 600;
|
||||
color: var(--al-text);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
.al-forgot {
|
||||
align-self: center;
|
||||
min-height: 44px;
|
||||
margin-top: 6px;
|
||||
padding: 0 8px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--al-text);
|
||||
font: 600 calc(14px * var(--fs-scale-body, 1)) var(--al-text-face);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* ── Buttons ── */
|
||||
.al-cta,
|
||||
.al-cta2 {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
border-radius: 16px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
transition:
|
||||
transform 0.15s,
|
||||
opacity 0.15s;
|
||||
}
|
||||
.al-cta {
|
||||
min-height: 56px;
|
||||
margin-top: 4px;
|
||||
background: var(--al-dark);
|
||||
color: #fff;
|
||||
font: 700 calc(17px * var(--fs-scale-body, 1)) var(--al-text-face);
|
||||
box-shadow: 0 14px 28px -14px rgba(17, 24, 39, 0.55);
|
||||
}
|
||||
.al-cta2 {
|
||||
min-height: 52px;
|
||||
background: #fff;
|
||||
color: var(--al-dark);
|
||||
font: 700 calc(16px * var(--fs-scale-body, 1)) var(--al-text-face);
|
||||
box-shadow: 0 0 0 1.5px var(--al-line);
|
||||
}
|
||||
.al-cta:active,
|
||||
.al-cta2:active {
|
||||
transform: scale(0.985);
|
||||
}
|
||||
.al-cta:disabled,
|
||||
.al-cta2:disabled {
|
||||
opacity: 0.7;
|
||||
cursor: default;
|
||||
}
|
||||
.al-demo {
|
||||
background: linear-gradient(135deg, #f59e0b, #d97706);
|
||||
color: #451a03;
|
||||
box-shadow: 0 10px 24px -14px rgba(217, 119, 6, 0.7);
|
||||
}
|
||||
.al-spin {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid currentColor;
|
||||
border-top-color: transparent;
|
||||
animation: al-spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes al-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.al-or {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin: 10px 0 2px;
|
||||
font-size: calc(13px * var(--fs-scale-body, 1));
|
||||
font-weight: 600;
|
||||
color: var(--al-faint);
|
||||
}
|
||||
.al-or::before,
|
||||
.al-or::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: var(--al-line);
|
||||
}
|
||||
.al-alt {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.al-switch {
|
||||
margin: 16px 0 0;
|
||||
text-align: center;
|
||||
font-size: calc(14px * var(--fs-scale-body, 1));
|
||||
color: var(--al-muted);
|
||||
}
|
||||
.al-switch button {
|
||||
min-height: 44px;
|
||||
padding: 0 4px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--al-ink);
|
||||
font: 700 calc(14px * var(--fs-scale-body, 1)) var(--al-text-face);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* ── Messages ── */
|
||||
.al-notice {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: flex-start;
|
||||
margin: 0;
|
||||
padding: 12px 14px;
|
||||
border-radius: 14px;
|
||||
background: var(--al-bad-soft);
|
||||
color: var(--al-bad-ink);
|
||||
font-size: calc(13.5px * var(--fs-scale-body, 1));
|
||||
font-weight: 600;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.al-notice svg {
|
||||
flex: none;
|
||||
margin-top: 1px;
|
||||
}
|
||||
.al-notice.warn {
|
||||
background: var(--al-warn-soft);
|
||||
color: var(--al-warn-ink);
|
||||
}
|
||||
.al-notice b {
|
||||
display: block;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
.al-notice a {
|
||||
display: inline-block;
|
||||
margin-top: 4px;
|
||||
color: inherit;
|
||||
font-weight: 700;
|
||||
}
|
||||
.al-hint {
|
||||
margin: 0;
|
||||
font-size: calc(12.5px * var(--fs-scale-body, 1));
|
||||
line-height: 1.5;
|
||||
color: var(--al-muted);
|
||||
}
|
||||
.al-back {
|
||||
align-self: flex-start;
|
||||
min-height: 40px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--al-text);
|
||||
font: 600 calc(14px * var(--fs-scale-body, 1)) var(--al-text-face);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Waiting: on the way to the sign-in provider, or for the server's settings. */
|
||||
.al-wait {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 14px;
|
||||
min-height: 180px;
|
||||
padding-bottom: 40px;
|
||||
text-align: center;
|
||||
color: var(--al-text);
|
||||
}
|
||||
.al-wait .al-spin {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-width: 2.5px;
|
||||
}
|
||||
.al-wait p {
|
||||
margin: 0;
|
||||
font-size: calc(16px * var(--fs-scale-body, 1));
|
||||
font-weight: 600;
|
||||
color: var(--al-ink);
|
||||
}
|
||||
.al-wait a {
|
||||
font-size: calc(14px * var(--fs-scale-body, 1));
|
||||
color: var(--al-text);
|
||||
}
|
||||
|
||||
.app-login :focus-visible {
|
||||
outline: 2px solid var(--al-dark);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/*
|
||||
* An iPad, an unfolded phone, a phone on its side: the landscape fills one side
|
||||
* and the form stands in a column of its own beside it, as on the address screen.
|
||||
*/
|
||||
@media (min-width: 900px), (orientation: landscape) and (max-height: 500px) {
|
||||
.app-login {
|
||||
flex-direction: row;
|
||||
overflow: hidden;
|
||||
}
|
||||
.al-hero {
|
||||
flex: 1 1 auto;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
margin: 0;
|
||||
}
|
||||
.al-hero::after {
|
||||
display: none;
|
||||
}
|
||||
.al-card {
|
||||
inset-inline: calc(32px + var(--al-safe-start)) auto;
|
||||
width: min(420px, calc(100% - 64px));
|
||||
bottom: 40px;
|
||||
}
|
||||
.al-logo {
|
||||
top: calc(var(--al-safe-top) + 24px);
|
||||
inset-inline-start: calc(32px + var(--al-safe-start));
|
||||
height: 46px;
|
||||
}
|
||||
.al-body {
|
||||
flex: none;
|
||||
width: 460px;
|
||||
height: 100%;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
scrollbar-width: none;
|
||||
justify-content: center;
|
||||
padding-block: calc(var(--al-safe-top) + 32px) calc(32px + var(--al-safe-bottom));
|
||||
padding-inline: 32px calc(32px + var(--al-safe-end));
|
||||
background: var(--al-page);
|
||||
box-shadow: -1px 0 0 rgba(31, 26, 23, 0.06);
|
||||
}
|
||||
}
|
||||
@media (orientation: landscape) and (max-height: 500px) {
|
||||
.al-body {
|
||||
width: min(420px, 52vw);
|
||||
justify-content: flex-start;
|
||||
padding-top: calc(var(--al-safe-top) + 20px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.app-login,
|
||||
.app-login * {
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
}
|
||||
.al-spin {
|
||||
animation: al-spin 1.6s linear infinite !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Signed in: the screen steps back into the page colour, and the app rises in
|
||||
from it (native/appBoot.ts handOverToApp). */
|
||||
.app-login.al-leaving .al-body {
|
||||
animation: al-leave-body 0.34s cubic-bezier(0.4, 0, 1, 1) both;
|
||||
}
|
||||
.app-login.al-leaving .al-hero {
|
||||
animation: al-leave-hero 0.42s ease-in both;
|
||||
}
|
||||
@keyframes al-leave-body {
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateY(14px);
|
||||
}
|
||||
}
|
||||
@keyframes al-leave-hero {
|
||||
to {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// FE-LOGIN-MODEL-001 to FE-LOGIN-MODEL-004
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { heading, oidcLoginHref, oidcOnlyHref, submitLabel, type LoginStep } from './loginModel';
|
||||
|
||||
/** Returns the key itself, so the assertions read the keys. */
|
||||
const t = (key: string) => key;
|
||||
|
||||
const step = (overrides: Partial<LoginStep> = {}): LoginStep => ({
|
||||
mode: 'login',
|
||||
mfaStep: false,
|
||||
passwordChangeStep: false,
|
||||
hasUsers: true,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('loginModel', () => {
|
||||
it('FE-LOGIN-MODEL-001: names each step of the sign-in', () => {
|
||||
expect(heading(step(), t)).toEqual({ title: 'login.title', subtitle: 'login.subtitle', plain: true });
|
||||
expect(heading(step({ mfaStep: true }), t).title).toBe('login.mfaTitle');
|
||||
expect(heading(step({ passwordChangeStep: true, mfaStep: true }), t).title).toBe('login.setNewPassword');
|
||||
expect(heading(step({ mode: 'register' }), t).title).toBe('login.createAccount');
|
||||
expect(heading(step({ mode: 'register', hasUsers: false }), t).title).toBe('login.createAdmin');
|
||||
});
|
||||
|
||||
it('FE-LOGIN-MODEL-002: labels the submit button for the step and while it runs', () => {
|
||||
expect(submitLabel(step(), false, t)).toBe('login.signIn');
|
||||
expect(submitLabel(step(), true, t)).toBe('login.signingIn');
|
||||
expect(submitLabel(step({ mfaStep: true }), true, t)).toBe('login.mfaVerify');
|
||||
expect(submitLabel(step({ mode: 'register' }), false, t)).toBe('login.createAccount');
|
||||
expect(submitLabel(step({ mode: 'register' }), true, t)).toBe('login.creating');
|
||||
expect(submitLabel(step({ passwordChangeStep: true }), true, t)).toBe('settings.updatePassword');
|
||||
});
|
||||
|
||||
it('FE-LOGIN-MODEL-003: carries the invite and the remember-me choice to SSO, only when signing in', () => {
|
||||
expect(oidcLoginHref('', 'login', true)).toBe('/api/auth/oidc/login?remember=1');
|
||||
expect(oidcLoginHref('', 'login', false)).toBe('/api/auth/oidc/login?remember=0');
|
||||
expect(oidcLoginHref('a b', 'login', true)).toBe('/api/auth/oidc/login?invite=a%20b&remember=1');
|
||||
expect(oidcLoginHref('', 'register', true)).toBe('/api/auth/oidc/login');
|
||||
expect(oidcLoginHref('tok', 'register', false)).toBe('/api/auth/oidc/login?invite=tok');
|
||||
});
|
||||
|
||||
it('FE-LOGIN-MODEL-004: always asks for the remembered session on an OIDC-only install', () => {
|
||||
expect(oidcOnlyHref('')).toBe('/api/auth/oidc/login?remember=1');
|
||||
expect(oidcOnlyHref('tok')).toBe('/api/auth/oidc/login?invite=tok&remember=1');
|
||||
});
|
||||
});
|
||||
@@ -1,61 +0,0 @@
|
||||
// What the sign-in screens say and where their buttons lead, shared by the
|
||||
// browser's LoginPage and the app's AppLogin, so the two cannot drift apart.
|
||||
|
||||
export type LoginMode = 'login' | 'register';
|
||||
|
||||
export interface LoginStep {
|
||||
mode: LoginMode;
|
||||
mfaStep: boolean;
|
||||
passwordChangeStep: boolean;
|
||||
/** False on a fresh install, where the first account becomes the admin. */
|
||||
hasUsers: boolean;
|
||||
}
|
||||
|
||||
type Translate = (key: string) => string;
|
||||
|
||||
/**
|
||||
* The heading and the line under it. `plain` is the plain sign-in, whose line
|
||||
* the app's screen leaves out. Translated here, with the keys written out, so
|
||||
* the i18n key check sees every one of them.
|
||||
*/
|
||||
export function heading(step: LoginStep, t: Translate): { title: string; subtitle: string; plain: boolean } {
|
||||
if (step.passwordChangeStep) {
|
||||
return { title: t('login.setNewPassword'), subtitle: t('login.setNewPasswordHint'), plain: false };
|
||||
}
|
||||
if (step.mode === 'login' && step.mfaStep) {
|
||||
return { title: t('login.mfaTitle'), subtitle: t('login.mfaSubtitle'), plain: false };
|
||||
}
|
||||
if (step.mode === 'register') {
|
||||
return step.hasUsers
|
||||
? { title: t('login.createAccount'), subtitle: t('login.createAccountHint'), plain: false }
|
||||
: { title: t('login.createAdmin'), subtitle: t('login.createAdminHint'), plain: false };
|
||||
}
|
||||
return { title: t('login.title'), subtitle: t('login.subtitle'), plain: true };
|
||||
}
|
||||
|
||||
/** The submit button's label; another while the request runs. */
|
||||
export function submitLabel(step: LoginStep, loading: boolean, t: Translate): string {
|
||||
if (step.passwordChangeStep) return t('settings.updatePassword');
|
||||
if (step.mode === 'register') return loading ? t('login.creating') : t('login.createAccount');
|
||||
if (step.mfaStep) return t('login.mfaVerify');
|
||||
return loading ? t('login.signingIn') : t('login.signIn');
|
||||
}
|
||||
|
||||
/**
|
||||
* The SSO button beside the password form. The remember-me switch only shows in
|
||||
* login mode; in register mode the parameter stays off so the server default applies.
|
||||
*/
|
||||
export function oidcLoginHref(inviteToken: string, mode: LoginMode, rememberMe: boolean): string {
|
||||
const params: string[] = [];
|
||||
if (inviteToken) params.push('invite=' + encodeURIComponent(inviteToken));
|
||||
if (mode === 'login') params.push('remember=' + (rememberMe ? '1' : '0'));
|
||||
return '/api/auth/oidc/login' + (params.length ? '?' + params.join('&') : '');
|
||||
}
|
||||
|
||||
/**
|
||||
* The only button in OIDC-only mode. No remember-me switch there: the IdP owns
|
||||
* the session policy, so it always asks for the remembered lifetime (#1927).
|
||||
*/
|
||||
export function oidcOnlyHref(inviteToken: string): string {
|
||||
return `/api/auth/oidc/login${inviteToken ? '?invite=' + encodeURIComponent(inviteToken) + '&' : '?'}remember=1`;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import type React from 'react';
|
||||
|
||||
/**
|
||||
* The one-time code field, for this step and the app's sign-in screen alike.
|
||||
* Text, not numeric: backup codes carry letters. The hints are set here rather
|
||||
* than left to native/keyboardFields.ts, because autoFocus gives the field
|
||||
* focus before any touch could prepare it.
|
||||
*/
|
||||
export function mfaCodeInputProps(
|
||||
code: string,
|
||||
onCode: (code: string) => void,
|
||||
placeholder: string
|
||||
): React.InputHTMLAttributes<HTMLInputElement> {
|
||||
return {
|
||||
type: 'text',
|
||||
id: 'totp',
|
||||
name: 'totp',
|
||||
inputMode: 'text',
|
||||
autoComplete: 'one-time-code',
|
||||
autoCapitalize: 'characters',
|
||||
autoCorrect: 'off',
|
||||
spellCheck: false,
|
||||
enterKeyHint: 'go',
|
||||
value: code,
|
||||
onChange: (e: React.ChangeEvent<HTMLInputElement>) => onCode(e.target.value.toUpperCase().slice(0, 24)),
|
||||
placeholder,
|
||||
required: true,
|
||||
autoFocus: true,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-012: useLogin inside the iOS/Android app
|
||||
// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-008: useLogin inside the iOS/Android app
|
||||
import { startAuthentication } from '@simplewebauthn/browser';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import React from 'react';
|
||||
@@ -11,9 +11,7 @@ import { act, renderHook, waitFor } from '../../../tests/helpers/render';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import { TranslationProvider } from '../../i18n/TranslationContext';
|
||||
import { BrowserSignInCancelled, resumeBrowserSignIn, signInThroughBrowser } from '../../native/browserSignIn';
|
||||
import { toastHaptic } from '../../native/haptics';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { markSignedOut, wasSignedOut } from '../../utils/signedOut';
|
||||
import { useLogin } from './useLogin';
|
||||
|
||||
@@ -25,18 +23,12 @@ vi.mock('react-router', async () => {
|
||||
});
|
||||
vi.mock('@simplewebauthn/browser', () => ({ startAuthentication: vi.fn() }));
|
||||
vi.mock('../../native/platform', () => ({ isNativeApp: () => true }));
|
||||
vi.mock('../../native/haptics', () => ({ toastHaptic: vi.fn() }));
|
||||
vi.mock('../../native/browserSignIn', async () => {
|
||||
const actual = await vi.importActual<typeof import('../../native/browserSignIn')>('../../native/browserSignIn');
|
||||
return { ...actual, signInThroughBrowser: vi.fn(), resumeBrowserSignIn: vi.fn() };
|
||||
});
|
||||
|
||||
const realLocation = window.location;
|
||||
const realLanguages = Object.getOwnPropertyDescriptor(window.navigator, 'languages');
|
||||
|
||||
function deviceLanguages(languages: string[]) {
|
||||
Object.defineProperty(window.navigator, 'languages', { configurable: true, get: () => languages });
|
||||
}
|
||||
const loadUser = vi.fn(async () => {});
|
||||
|
||||
function renderLogin() {
|
||||
@@ -58,7 +50,6 @@ beforeEach(() => {
|
||||
vi.mocked(signInThroughBrowser).mockReset();
|
||||
vi.mocked(resumeBrowserSignIn).mockReset().mockResolvedValue(false);
|
||||
vi.mocked(startAuthentication).mockReset();
|
||||
vi.mocked(toastHaptic).mockClear();
|
||||
loadUser.mockClear();
|
||||
useAuthStore.setState({ loadUser });
|
||||
Object.defineProperty(window, 'location', {
|
||||
@@ -70,10 +61,6 @@ beforeEach(() => {
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
if (realLanguages) Object.defineProperty(window.navigator, 'languages', realLanguages);
|
||||
else delete (window.navigator as { languages?: readonly string[] }).languages;
|
||||
localStorage.removeItem('app_language');
|
||||
document.documentElement.removeAttribute('data-app-handover');
|
||||
Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation });
|
||||
});
|
||||
|
||||
@@ -165,37 +152,4 @@ describe('useLogin in the native app', () => {
|
||||
await waitFor(() => expect(result.current.error).toBe('Signing in did not work. Please try again.'));
|
||||
expect(result.current.showTakeoff).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-LOGIN-NATIVE-009: speaks the device language when no language was chosen', async () => {
|
||||
deviceLanguages(['de-DE', 'en-US']);
|
||||
renderLogin();
|
||||
await waitFor(() => expect(useSettingsStore.getState().settings.language).toBe('de'));
|
||||
});
|
||||
|
||||
it('FE-LOGIN-NATIVE-010: falls back to English on a device language TREK has no translation for', async () => {
|
||||
deviceLanguages(['pt-PT']);
|
||||
useSettingsStore.setState((state) => ({ settings: { ...state.settings, language: 'fr' } }));
|
||||
renderLogin();
|
||||
await waitFor(() => expect(useSettingsStore.getState().settings.language).toBe('en'));
|
||||
});
|
||||
|
||||
it('FE-LOGIN-NATIVE-011: opens the app after signing in without the takeoff, with the success tap', async () => {
|
||||
vi.mocked(resumeBrowserSignIn).mockResolvedValue(true);
|
||||
mockNavigate.mockClear();
|
||||
const { result } = renderLogin();
|
||||
|
||||
await waitFor(() => expect(result.current.showTakeoff).toBe(true));
|
||||
expect(toastHaptic).toHaveBeenCalledWith('success');
|
||||
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith('/'), { timeout: 2500 });
|
||||
expect(document.documentElement.hasAttribute('data-app-handover')).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-LOGIN-NATIVE-012: keeps a language once picked on this page over the device language', async () => {
|
||||
localStorage.setItem('app_language', 'fr');
|
||||
useSettingsStore.setState((state) => ({ settings: { ...state.settings, language: 'fr' } }));
|
||||
deviceLanguages(['de-DE', 'en-US']);
|
||||
const { result } = renderLogin();
|
||||
await waitFor(() => expect(result.current.appConfig).not.toBeNull());
|
||||
expect(useSettingsStore.getState().settings.language).toBe('fr');
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user