mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 05:21:15 +00:00
Compare commits
66 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3bfef73a46 | |||
| 7e790c3fb7 | |||
| 228db8541c | |||
| a729a6935f | |||
| 6c0e39e287 | |||
| 22574a2270 | |||
| 1d880cb881 | |||
| 3d076704f9 | |||
| 1b0f043506 | |||
| c383b11648 | |||
| fed564e7c0 | |||
| 9e216f5ae4 | |||
| 0f0232491b | |||
| 35fb59e64e | |||
| ee3fff1dab | |||
| 3bc75d2b1c | |||
| 094426debb | |||
| 313198ba63 | |||
| e677d58f91 | |||
| bc60aea839 | |||
| b5cd951bd2 | |||
| fd818050bd | |||
| 0313597b10 | |||
| 2c867673bf | |||
| 39ebf0976c | |||
| 1ecc449f3e | |||
| b8990782cc | |||
| 8ba7add541 | |||
| a3664e7117 | |||
| 64ed2175a5 | |||
| 447ae54b93 | |||
| 0067b0ff19 | |||
| d589da59f2 | |||
| 69ff295184 | |||
| d07c17ded6 | |||
| 44509723fd | |||
| b80fdf27f2 | |||
| a0b7b4d196 | |||
| aa24a9eff7 | |||
| de5417f9f0 | |||
| a48dd7645f | |||
| 217a576e16 | |||
| f6976d5cec | |||
| c1c2bbf146 | |||
| c05349f7c4 | |||
| a5342df648 | |||
| f44b143371 | |||
| d911122a37 | |||
| a69eee191c | |||
| 90f31d3f07 | |||
| d4da05bbc9 | |||
| bd1de9e1d5 | |||
| c33eb5b593 | |||
| dcfbf89234 | |||
| 6b6d971f07 | |||
| 9fc98b5d49 | |||
| daaa6c425d | |||
| b33ef6bec2 | |||
| eb9f6a3438 | |||
| 7823ab1550 | |||
| 47fdd3588c | |||
| a9ebd2d1ac | |||
| 9c32b42256 | |||
| 26611b46e4 | |||
| e3eec8d6d1 | |||
| 2d398568da |
@@ -1161,7 +1161,7 @@ jobs:
|
|||||||
docker run -d --name trek-ci -p 127.0.0.1:3000:3000 \
|
docker run -d --name trek-ci -p 127.0.0.1:3000:3000 \
|
||||||
--read-only --tmpfs /tmp:noexec,nosuid,size=128m \
|
--read-only --tmpfs /tmp:noexec,nosuid,size=128m \
|
||||||
--security-opt no-new-privileges:true \
|
--security-opt no-new-privileges:true \
|
||||||
--cap-drop ALL --cap-add CHOWN --cap-add SETUID --cap-add SETGID \
|
--cap-drop ALL --cap-add CHOWN --cap-add SETUID --cap-add SETGID --cap-add KILL \
|
||||||
-v "$RUNNER_TEMP/trek/data:/app/data" \
|
-v "$RUNNER_TEMP/trek/data:/app/data" \
|
||||||
-v "$RUNNER_TEMP/trek/uploads:/app/uploads" \
|
-v "$RUNNER_TEMP/trek/uploads:/app/uploads" \
|
||||||
-e ENCRYPTION_KEY="$(openssl rand -hex 32)" \
|
-e ENCRYPTION_KEY="$(openssl rand -hex 32)" \
|
||||||
@@ -1194,6 +1194,17 @@ jobs:
|
|||||||
curl -sf http://127.0.0.1:3000/ | grep -q '<div id="root">' \
|
curl -sf http://127.0.0.1:3000/ | grep -q '<div id="root">' \
|
||||||
|| { echo "::error::/ does not serve the client"; exit 1; }
|
|| { echo "::error::/ does not serve the client"; exit 1; }
|
||||||
|
|
||||||
|
# Same capabilities as the shipped compose file: dumb-init has to be able
|
||||||
|
# to pass the stop signal on to node, or docker stop ends in SIGKILL (137).
|
||||||
|
- name: Stop gracefully
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
docker stop -t 30 trek-ci >/dev/null
|
||||||
|
code="$(docker inspect -f '{{.State.ExitCode}}' trek-ci)"
|
||||||
|
[ "$code" = "0" ] || { echo "::error::docker stop ended with exit code $code, not a graceful shutdown"; exit 1; }
|
||||||
|
docker logs trek-ci 2>&1 | grep -q 'SIGTERM received' \
|
||||||
|
|| { echo "::error::the server never saw SIGTERM"; exit 1; }
|
||||||
|
|
||||||
- name: Container log
|
- name: Container log
|
||||||
if: always()
|
if: always()
|
||||||
run: docker logs trek-ci 2>&1 || true
|
run: docker logs trek-ci 2>&1 || true
|
||||||
|
|||||||
@@ -234,12 +234,15 @@ the details.
|
|||||||
## Get started in 30 seconds
|
## Get started in 30 seconds
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
ENCRYPTION_KEY=$(openssl rand -hex 32) docker run -d -p 3000:3000 \
|
ENCRYPTION_KEY=$(openssl rand -hex 32) docker run -d --name trek -p 3000:3000 \
|
||||||
-e ENCRYPTION_KEY=$ENCRYPTION_KEY \
|
-e ENCRYPTION_KEY=$ENCRYPTION_KEY \
|
||||||
|
-e COOKIE_SECURE=false \
|
||||||
-v ./data:/app/data -v ./uploads:/app/uploads mauriceboe/trek
|
-v ./data:/app/data -v ./uploads:/app/uploads mauriceboe/trek
|
||||||
```
|
```
|
||||||
|
|
||||||
Open `http://localhost:3000`. On first boot TREK seeds an admin account — if you set `ADMIN_EMAIL`/`ADMIN_PASSWORD` those are used, otherwise the credentials are printed to the container log (`docker logs trek`).
|
Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine. On first boot TREK seeds an admin account — if you set `ADMIN_EMAIL`/`ADMIN_PASSWORD` those are used, otherwise the credentials are printed to the container log (`docker logs trek`).
|
||||||
|
|
||||||
|
`COOKIE_SECURE=false` is only for trying TREK over plain HTTP: without it the browser drops the session cookie and the login does not stick. Once TREK sits behind HTTPS (see [Reverse Proxy](#reverse-proxy)), remove it.
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
apiVersion: v2
|
apiVersion: v2
|
||||||
name: trek
|
name: trek
|
||||||
version: 4.3.4
|
version: 5.0.0
|
||||||
description: Minimal Helm chart for TREK app
|
description: Minimal Helm chart for TREK app
|
||||||
appVersion: "4.3.4"
|
appVersion: "5.0.0"
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@trek/client",
|
"name": "@trek/client",
|
||||||
"version": "4.3.4",
|
"version": "5.0.0",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
|
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"src": {
|
"src": {
|
||||||
"@typescript-eslint/no-non-null-assertion": 384,
|
"@typescript-eslint/no-non-null-assertion": 382,
|
||||||
"@typescript-eslint/no-misused-promises": 849,
|
"@typescript-eslint/no-misused-promises": 848,
|
||||||
"no-console": 88,
|
"no-console": 88,
|
||||||
"complexity": 221,
|
"complexity": 220,
|
||||||
"@typescript-eslint/no-explicit-any": 146,
|
"@typescript-eslint/no-explicit-any": 146,
|
||||||
"trek/no-swallowed-catch": 130,
|
"trek/no-swallowed-catch": 130,
|
||||||
"max-params": 32,
|
"max-params": 32,
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
"no-useless-assignment": 7,
|
"no-useless-assignment": 7,
|
||||||
"no-empty": 19,
|
"no-empty": 19,
|
||||||
"trek/no-window-globals": 41,
|
"trek/no-window-globals": 41,
|
||||||
"react-refresh/only-export-components": 45,
|
"react-refresh/only-export-components": 44,
|
||||||
"unused-disable-directive": 6,
|
"unused-disable-directive": 6,
|
||||||
"max-depth": 21,
|
"max-depth": 21,
|
||||||
"react-hooks/void-use-memo": 1,
|
"react-hooks/void-use-memo": 1,
|
||||||
@@ -30,7 +30,7 @@
|
|||||||
"no-useless-escape": 1
|
"no-useless-escape": 1
|
||||||
},
|
},
|
||||||
"suppressed": {
|
"suppressed": {
|
||||||
"@typescript-eslint/no-explicit-any": 40,
|
"@typescript-eslint/no-explicit-any": 38,
|
||||||
"react-hooks/exhaustive-deps": 46
|
"react-hooks/exhaustive-deps": 46
|
||||||
},
|
},
|
||||||
"tests": {
|
"tests": {
|
||||||
|
|||||||
@@ -65,7 +65,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"feature": "AI assistant chat",
|
"feature": "AI assistant chat",
|
||||||
"hooks": ["src/components/Assistant/useAssistantThread.ts"],
|
"hooks": ["src/components/Assistant/useAssistantThread.ts", "src/components/Assistant/useAssistantStatus.ts"],
|
||||||
"desktop": ["src/components/Assistant/AssistantWindow.tsx"],
|
"desktop": ["src/components/Assistant/AssistantWindow.tsx"],
|
||||||
"mobile": ["src/mobile/screens/trip/assistant/MAssistantScreen.tsx"]
|
"mobile": ["src/mobile/screens/trip/assistant/MAssistantScreen.tsx"]
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"admin.ts": 126,
|
"admin.ts": 112,
|
||||||
"atlas.ts": 9,
|
"atlas.ts": 9,
|
||||||
"backup.ts": 10,
|
"backup.ts": 10,
|
||||||
"budget.ts": 36,
|
"budget.ts": 36,
|
||||||
|
|||||||
@@ -150,7 +150,6 @@
|
|||||||
"src/pages/resetPassword/useResetPassword.ts",
|
"src/pages/resetPassword/useResetPassword.ts",
|
||||||
"src/pages/settings/useSettings.ts",
|
"src/pages/settings/useSettings.ts",
|
||||||
"src/pages/sharedTrip/useSharedTrip.ts",
|
"src/pages/sharedTrip/useSharedTrip.ts",
|
||||||
"src/pages/tripPlanner/useBookingEdits.ts",
|
|
||||||
"src/pages/tripPlanner/usePlaceFormOpeners.ts",
|
"src/pages/tripPlanner/usePlaceFormOpeners.ts",
|
||||||
"src/pages/tripPlanner/usePlannerDialogs.ts",
|
"src/pages/tripPlanner/usePlannerDialogs.ts",
|
||||||
"src/pages/tripPlanner/useTripPlanner.ts",
|
"src/pages/tripPlanner/useTripPlanner.ts",
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"components/Admin/AdminPluginsPanel.tsx": 2,
|
"components/Admin/plugins/pluginMenu.ts": 2,
|
||||||
"components/Budget/BudgetPanelMemberChips.tsx": 6,
|
"components/Budget/BudgetPanelMemberChips.tsx": 6,
|
||||||
"components/Budget/CostsPanel.tsx": 3,
|
"components/Budget/CostsPanel.tsx": 3,
|
||||||
"components/Budget/ReceiptPreviewModal.tsx": 2,
|
"components/Budget/ReceiptPreviewModal.tsx": 2,
|
||||||
@@ -59,8 +59,6 @@
|
|||||||
"components/Studio/StudioSavedLayouts.tsx": 1,
|
"components/Studio/StudioSavedLayouts.tsx": 1,
|
||||||
"components/Studio/TravelElements.tsx": 4,
|
"components/Studio/TravelElements.tsx": 4,
|
||||||
"components/Studio/TravelPreview.tsx": 1,
|
"components/Studio/TravelPreview.tsx": 1,
|
||||||
"components/SystemNotices/ReleaseNoticeVisuals.tsx": 3,
|
|
||||||
"components/SystemNotices/releaseNotice.css": 2,
|
|
||||||
"components/Vacay/VacayCalendar.tsx": 3,
|
"components/Vacay/VacayCalendar.tsx": 3,
|
||||||
"components/Vacay/VacayMonthCard.tsx": 7,
|
"components/Vacay/VacayMonthCard.tsx": 7,
|
||||||
"components/Vacay/VacaySettings.tsx": 1,
|
"components/Vacay/VacaySettings.tsx": 1,
|
||||||
|
|||||||
@@ -2,13 +2,13 @@
|
|||||||
"e2e/help/fixtures.ts": 2291,
|
"e2e/help/fixtures.ts": 2291,
|
||||||
"src/api/client.ts": 1873,
|
"src/api/client.ts": 1873,
|
||||||
"src/components/Admin/AdminPluginsPanel.test.tsx": 2704,
|
"src/components/Admin/AdminPluginsPanel.test.tsx": 2704,
|
||||||
"src/components/Admin/AdminPluginsPanel.tsx": 1667,
|
"src/components/Admin/AdminPluginsPanel.tsx": 1277,
|
||||||
"src/components/Budget/CostsPanel.test.tsx": 2736,
|
"src/components/Budget/CostsPanel.test.tsx": 2736,
|
||||||
"src/components/Budget/CostsPanel.tsx": 1798,
|
"src/components/Budget/CostsPanel.tsx": 1798,
|
||||||
"src/components/Map/MapView.tsx": 1385,
|
"src/components/Map/MapView.tsx": 1385,
|
||||||
"src/components/Map/MapViewGL.test.tsx": 2919,
|
"src/components/Map/MapViewGL.test.tsx": 2919,
|
||||||
"src/components/Map/MapViewGL.tsx": 2290,
|
"src/components/Map/MapViewGL.tsx": 2218,
|
||||||
"src/components/Map/RouteCalculator.ts": 1076,
|
"src/components/Map/RouteCalculator.ts": 1063,
|
||||||
"src/components/PDF/TripPDF.tsx": 1082,
|
"src/components/PDF/TripPDF.tsx": 1082,
|
||||||
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
|
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
|
||||||
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
|
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"App.tsx": 11,
|
"App.tsx": 11,
|
||||||
"components/Admin/AdminPluginsPanel.tsx": 2,
|
|
||||||
"components/Admin/DefaultUserSettingsTab.tsx": 1,
|
"components/Admin/DefaultUserSettingsTab.tsx": 1,
|
||||||
|
"components/Admin/plugins/pluginMenu.ts": 2,
|
||||||
"components/Atlas/AtlasCountryPlaces.tsx": 6,
|
"components/Atlas/AtlasCountryPlaces.tsx": 6,
|
||||||
"components/BackgroundTasks/BackgroundTasksWidget.tsx": 4,
|
"components/BackgroundTasks/BackgroundTasksWidget.tsx": 4,
|
||||||
"components/Budget/BudgetPanel.helpers.ts": 2,
|
"components/Budget/BudgetPanel.helpers.ts": 2,
|
||||||
@@ -105,7 +105,6 @@
|
|||||||
"components/Studio/TravelElements.tsx": 5,
|
"components/Studio/TravelElements.tsx": 5,
|
||||||
"components/Studio/printSheets.ts": 5,
|
"components/Studio/printSheets.ts": 5,
|
||||||
"components/Studio/sidebar/contentDrops.ts": 2,
|
"components/Studio/sidebar/contentDrops.ts": 2,
|
||||||
"components/SystemNotices/ReleaseNoticeVisuals.tsx": 4,
|
|
||||||
"components/SystemNotices/SystemNoticeBanner.tsx": 28,
|
"components/SystemNotices/SystemNoticeBanner.tsx": 28,
|
||||||
"components/SystemNotices/SystemNoticeModal.tsx": 107,
|
"components/SystemNotices/SystemNoticeModal.tsx": 107,
|
||||||
"components/Todo/TodoListPanel.tsx": 6,
|
"components/Todo/TodoListPanel.tsx": 6,
|
||||||
|
|||||||
@@ -229,6 +229,8 @@ export const aiAdminApi = {
|
|||||||
connection: (): Promise<AiAdminConnectionResponse> => apiClient.get('/admin/ai/connection').then((r) => r.data),
|
connection: (): Promise<AiAdminConnectionResponse> => apiClient.get('/admin/ai/connection').then((r) => r.data),
|
||||||
saveConnection: (body: AiInstanceConnectionRequest): Promise<AiAdminConnectionResponse> =>
|
saveConnection: (body: AiInstanceConnectionRequest): Promise<AiAdminConnectionResponse> =>
|
||||||
apiClient.put('/admin/ai/connection', body, viaProvider).then((r) => r.data),
|
apiClient.put('/admin/ai/connection', body, viaProvider).then((r) => r.data),
|
||||||
|
setModel: (model: string): Promise<AiAdminConnectionResponse> =>
|
||||||
|
apiClient.patch('/admin/ai/connection/model', { model }).then((r) => r.data),
|
||||||
removeConnection: (): Promise<SuccessResponse> => apiClient.delete('/admin/ai/connection').then((r) => r.data),
|
removeConnection: (): Promise<SuccessResponse> => apiClient.delete('/admin/ai/connection').then((r) => r.data),
|
||||||
models: (): Promise<AiModelListResponse> => apiClient.get('/admin/ai/models', viaProvider).then((r) => r.data),
|
models: (): Promise<AiModelListResponse> => apiClient.get('/admin/ai/models', viaProvider).then((r) => r.data),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -692,6 +692,7 @@ describe('client > request payloads', () => {
|
|||||||
it('FE-APISURF-030: adminApi.pluginActivate only sends consent when granted', async () => {
|
it('FE-APISURF-030: adminApi.pluginActivate only sends consent when granted', async () => {
|
||||||
expect((await traceOne(() => adminApi.pluginActivate('koffi'))).body).toEqual({})
|
expect((await traceOne(() => adminApi.pluginActivate('koffi'))).body).toEqual({})
|
||||||
expect((await traceOne(() => adminApi.pluginActivate('koffi', true))).body).toEqual({ consent: true })
|
expect((await traceOne(() => adminApi.pluginActivate('koffi', true))).body).toEqual({ consent: true })
|
||||||
|
expect((await traceOne(() => adminApi.pluginActivate('koffi', false, true))).body).toEqual({ acceptTrekRange: true })
|
||||||
})
|
})
|
||||||
|
|
||||||
it('FE-APISURF-031: adminApi.pluginInstall spreads its options next to the id', async () => {
|
it('FE-APISURF-031: adminApi.pluginInstall spreads its options next to the id', async () => {
|
||||||
|
|||||||
@@ -574,9 +574,9 @@ export const adminApi = {
|
|||||||
plugins: () => apiClient.get('/admin/plugins').then(r => r.data),
|
plugins: () => apiClient.get('/admin/plugins').then(r => r.data),
|
||||||
pluginBrowse: (refresh?: boolean) => apiClient.get('/admin/plugins/registry', { params: refresh ? { refresh: 1 } : undefined }).then(r => r.data),
|
pluginBrowse: (refresh?: boolean) => apiClient.get('/admin/plugins/registry', { params: refresh ? { refresh: 1 } : undefined }).then(r => r.data),
|
||||||
pluginDetail: (id: string) => apiClient.get(`/admin/plugins/registry/${encodeURIComponent(id)}`).then(r => r.data),
|
pluginDetail: (id: string) => apiClient.get(`/admin/plugins/registry/${encodeURIComponent(id)}`).then(r => r.data),
|
||||||
pluginInstall: (id: string, opts?: Pick<PluginInstallRequest, 'version' | 'constraint' | 'withDependencies'>) =>
|
pluginInstall: (id: string, opts?: Omit<PluginInstallRequest, 'id'>) =>
|
||||||
apiClient.post('/admin/plugins/install', { id, ...opts } satisfies PluginInstallRequest).then(r => r.data),
|
apiClient.post('/admin/plugins/install', { id, ...opts } satisfies PluginInstallRequest).then(r => r.data),
|
||||||
pluginActivate: (id: string, consent?: boolean) => apiClient.post(`/admin/plugins/${id}/activate`, consent ? { consent: true } : {}).then(r => r.data),
|
pluginActivate: (id: string, consent?: boolean, accept?: boolean) => apiClient.post(`/admin/plugins/${id}/activate`, { consent: consent || undefined, acceptTrekRange: accept || undefined }).then(r => r.data),
|
||||||
pluginDeactivate: (id: string) => apiClient.post(`/admin/plugins/${id}/deactivate`).then(r => r.data),
|
pluginDeactivate: (id: string) => apiClient.post(`/admin/plugins/${id}/deactivate`).then(r => r.data),
|
||||||
// `version` pins the exact version to install (the rollback path); omitted, the server
|
// `version` pins the exact version to install (the rollback path); omitted, the server
|
||||||
// resolves the newest TREK-compatible version itself.
|
// resolves the newest TREK-compatible version itself.
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, I
|
|||||||
import EmptyState from '../shared/EmptyState'
|
import EmptyState from '../shared/EmptyState'
|
||||||
import DawarichIcon from '../shared/DawarichIcon'
|
import DawarichIcon from '../shared/DawarichIcon'
|
||||||
import AirTrailIcon from '../shared/AirTrailIcon'
|
import AirTrailIcon from '../shared/AirTrailIcon'
|
||||||
import { DOCUMENT_PROVIDER_ICONS } from '../shared/DocumentProviderIcons'
|
import { DOCUMENT_PROVIDER_ICONS } from '../shared/documentProviderIconMap'
|
||||||
import AddonTile from './AddonTile'
|
import AddonTile from './AddonTile'
|
||||||
import AddonSubRow from './AddonSubRow'
|
import AddonSubRow from './AddonSubRow'
|
||||||
import { Tooltip } from '../shared/Tooltip'
|
import { Tooltip } from '../shared/Tooltip'
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ export default function AddonSubRow({
|
|||||||
icon,
|
icon,
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
|
badge,
|
||||||
enabled,
|
enabled,
|
||||||
onToggle,
|
onToggle,
|
||||||
}: {
|
}: {
|
||||||
@@ -26,6 +27,8 @@ export default function AddonSubRow({
|
|||||||
icon?: ReactNode
|
icon?: ReactNode
|
||||||
title: string
|
title: string
|
||||||
description?: string
|
description?: string
|
||||||
|
/** A small pill after the title, e.g. the beta mark on the assistant. */
|
||||||
|
badge?: ReactNode
|
||||||
enabled: boolean
|
enabled: boolean
|
||||||
onToggle: () => void
|
onToggle: () => void
|
||||||
}) {
|
}) {
|
||||||
@@ -34,8 +37,11 @@ export default function AddonSubRow({
|
|||||||
{icon
|
{icon
|
||||||
? <span className={`grid h-6 w-6 flex-none place-items-center ${enabled ? 'text-content-muted' : 'text-content-faint'}`}>{icon}</span>
|
? <span className={`grid h-6 w-6 flex-none place-items-center ${enabled ? 'text-content-muted' : 'text-content-faint'}`}>{icon}</span>
|
||||||
: <span className="w-6 flex-none" aria-hidden />}
|
: <span className="w-6 flex-none" aria-hidden />}
|
||||||
<span className={`min-w-0 flex-1 truncate font-medium ${enabled ? 'text-content' : 'text-content-muted'}`} style={fs(12.5, 'body')} title={description}>
|
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||||
{title}
|
<span className={`min-w-0 truncate font-medium ${enabled ? 'text-content' : 'text-content-muted'}`} style={fs(12.5, 'body')} title={description}>
|
||||||
|
{title}
|
||||||
|
</span>
|
||||||
|
{badge}
|
||||||
</span>
|
</span>
|
||||||
<ToggleSwitch on={enabled} onToggle={onToggle} label={title} />
|
<ToggleSwitch on={enabled} onToggle={onToggle} label={title} />
|
||||||
</li>
|
</li>
|
||||||
|
|||||||
@@ -489,10 +489,10 @@ describe('AdminPluginsPanel — TREK-version compatibility', () => {
|
|||||||
fireEvent.click(await screen.findByText('Discover'))
|
fireEvent.click(await screen.findByText('Discover'))
|
||||||
}
|
}
|
||||||
|
|
||||||
it('blocks Install when no published version runs on this TREK, and says why', async () => {
|
it('marks a plugin no published version runs on, and still lets the admin install it', async () => {
|
||||||
await openDiscover({ trek: '>=4.0.0', hostVersion: '3.3.0', compatible: false, latestCompatible: null })
|
await openDiscover({ trek: '>=4.0.0', hostVersion: '3.3.0', compatible: false, latestCompatible: null })
|
||||||
const btn = await screen.findByRole('button', { name: /^incompatible$/i })
|
expect(await screen.findByText('Not confirmed for TREK 3.3.0 yet')).toBeInTheDocument()
|
||||||
expect(btn).toBeDisabled()
|
expect(screen.getByRole('button', { name: /^install$/i })).toBeEnabled()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('offers the newest version that DOES run here rather than a dead button', async () => {
|
it('offers the newest version that DOES run here rather than a dead button', async () => {
|
||||||
@@ -549,9 +549,11 @@ function panelRoot(container: HTMLElement): HTMLElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Opens one of the toolbar dropdowns (identified by its current title) and picks an option. */
|
/** Opens one of the toolbar dropdowns (identified by its current title) and picks an option. */
|
||||||
async function pickFilter(trigger: RegExp, option: RegExp) {
|
/** The toolbar's one Filter button; a pick in its menu leaves the menu open. */
|
||||||
fireEvent.click(await screen.findByTitle(trigger))
|
const filterButton = (): HTMLElement => screen.getByRole('button', { name: /^Filter/ })
|
||||||
fireEvent.click(await screen.findByRole('button', { name: option }))
|
async function pickFilter(option: RegExp) {
|
||||||
|
if ((await screen.findByRole('button', { name: /^Filter/ })).getAttribute('aria-expanded') !== 'true') fireEvent.click(filterButton())
|
||||||
|
fireEvent.click(await screen.findByRole('menuitemradio', { name: option }))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The enable toggle of a named installed row. */
|
/** The enable toggle of a named installed row. */
|
||||||
@@ -610,9 +612,9 @@ describe('AdminPluginsPanel — load states and toolbar', () => {
|
|||||||
render(<AdminPluginsPanel />)
|
render(<AdminPluginsPanel />)
|
||||||
await screen.findByText('Gotify')
|
await screen.findByText('Gotify')
|
||||||
|
|
||||||
await pickFilter(/^Type: All types$/, /^Widget$/)
|
await pickFilter(/^Widget$/)
|
||||||
|
|
||||||
expect(await screen.findByTitle('Type: Widget')).toBeInTheDocument()
|
expect(await screen.findByRole('menuitemradio', { name: 'Widget' })).toHaveAttribute('aria-checked', 'true')
|
||||||
expect(screen.getByText('Countdown')).toBeInTheDocument()
|
expect(screen.getByText('Countdown')).toBeInTheDocument()
|
||||||
expect(screen.queryByText('Gotify')).not.toBeInTheDocument()
|
expect(screen.queryByText('Gotify')).not.toBeInTheDocument()
|
||||||
})
|
})
|
||||||
@@ -626,15 +628,15 @@ describe('AdminPluginsPanel — load states and toolbar', () => {
|
|||||||
render(<AdminPluginsPanel />)
|
render(<AdminPluginsPanel />)
|
||||||
await screen.findByText('OnOne')
|
await screen.findByText('OnOne')
|
||||||
|
|
||||||
await pickFilter(/^Status: All$/, /^Off$/)
|
await pickFilter(/^Off$/)
|
||||||
expect(await screen.findByText('OffOne')).toBeInTheDocument()
|
expect(await screen.findByText('OffOne')).toBeInTheDocument()
|
||||||
expect(screen.queryByText('OnOne')).not.toBeInTheDocument()
|
expect(screen.queryByText('OnOne')).not.toBeInTheDocument()
|
||||||
|
|
||||||
await pickFilter(/^Status: Off$/, /^Error$/)
|
await pickFilter(/^Error$/)
|
||||||
expect(await screen.findByText('BadOne')).toBeInTheDocument()
|
expect(await screen.findByText('BadOne')).toBeInTheDocument()
|
||||||
expect(screen.getByText('boom')).toBeInTheDocument()
|
expect(screen.getByText('boom')).toBeInTheDocument()
|
||||||
|
|
||||||
await pickFilter(/^Status: Error$/, /^Update available$/)
|
await pickFilter(/^Update available$/)
|
||||||
expect(await screen.findByText('OnOne')).toBeInTheDocument()
|
expect(await screen.findByText('OnOne')).toBeInTheDocument()
|
||||||
expect(screen.queryByText('BadOne')).not.toBeInTheDocument()
|
expect(screen.queryByText('BadOne')).not.toBeInTheDocument()
|
||||||
})
|
})
|
||||||
@@ -644,11 +646,10 @@ describe('AdminPluginsPanel — load states and toolbar', () => {
|
|||||||
render(<AdminPluginsPanel />)
|
render(<AdminPluginsPanel />)
|
||||||
await screen.findByText('Gotify')
|
await screen.findByText('Gotify')
|
||||||
|
|
||||||
await pickFilter(/^Sort: Name$/, /^Updates first$/)
|
await pickFilter(/^Updates first$/)
|
||||||
expect(await screen.findByTitle('Sort: Updates first')).toBeInTheDocument()
|
expect(filterButton()).toHaveTextContent('Updates first')
|
||||||
|
|
||||||
await clickDiscover()
|
await clickDiscover()
|
||||||
await waitFor(() => expect(screen.getByTitle('Sort: Name')).toBeInTheDocument())
|
await waitFor(() => expect(filterButton()).toHaveTextContent(/Name$/))
|
||||||
})
|
})
|
||||||
|
|
||||||
it('FE-COMP-PLUGINS-PANEL-008: rescan re-pulls the registry past its cache and confirms with a toast', async () => {
|
it('FE-COMP-PLUGINS-PANEL-008: rescan re-pulls the registry past its cache and confirms with a toast', async () => {
|
||||||
@@ -1663,15 +1664,16 @@ describe('AdminPluginsPanel — Discover cards and the detail modal', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('AdminPluginsPanel — security footer', () => {
|
describe('AdminPluginsPanel — security dialog', () => {
|
||||||
it('FE-COMP-PLUGINS-PANEL-048: the containment note expands into its sections', async () => {
|
it('FE-COMP-PLUGINS-PANEL-048: the shield in the header opens how plugins are contained', async () => {
|
||||||
panelWith([])
|
panelWith([])
|
||||||
render(<AdminPluginsPanel />)
|
render(<AdminPluginsPanel />)
|
||||||
await screen.findByText('No plugins installed yet.')
|
await screen.findByText('No plugins installed yet.')
|
||||||
|
|
||||||
expect(screen.queryByText('Every plugin runs boxed in')).not.toBeInTheDocument()
|
expect(screen.queryByText('Every plugin runs boxed in')).not.toBeInTheDocument()
|
||||||
fireEvent.click(screen.getByText('How plugins are contained — and the limits'))
|
fireEvent.click(screen.getByRole('button', { name: 'How plugins are secured' }))
|
||||||
|
|
||||||
|
expect(screen.getByRole('dialog', { name: 'How plugins are secured' })).toBeInTheDocument()
|
||||||
expect(screen.getByText('Every plugin runs boxed in')).toBeInTheDocument()
|
expect(screen.getByText('Every plugin runs boxed in')).toBeInTheDocument()
|
||||||
expect(screen.getByText('What "Reviewed" means')).toBeInTheDocument()
|
expect(screen.getByText('What "Reviewed" means')).toBeInTheDocument()
|
||||||
expect(screen.getByText('What "Signed" means')).toBeInTheDocument()
|
expect(screen.getByText('What "Signed" means')).toBeInTheDocument()
|
||||||
@@ -1700,9 +1702,9 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
|
|||||||
row({ id: 'c-page', name: 'Gamma Page', description: 'a page', type: 'page', enabled: 1, status: 'error', last_error: 'boom' }),
|
row({ id: 'c-page', name: 'Gamma Page', description: 'a page', type: 'page', enabled: 1, status: 'error', last_error: 'boom' }),
|
||||||
]
|
]
|
||||||
|
|
||||||
const pickFilter = async (user: ReturnType<typeof userEvent.setup>, filter: RegExp, option: RegExp) => {
|
const pickFilter = async (user: ReturnType<typeof userEvent.setup>, option: RegExp) => {
|
||||||
await user.click(screen.getByTitle(filter))
|
if (filterButton().getAttribute('aria-expanded') !== 'true') await user.click(filterButton())
|
||||||
await user.click(screen.getByRole('button', { name: option }))
|
await user.click(screen.getByRole('menuitemradio', { name: option }))
|
||||||
}
|
}
|
||||||
|
|
||||||
it('FE-W5PLG-001: the search box narrows the installed list by name and description', async () => {
|
it('FE-W5PLG-001: the search box narrows the installed list by name and description', async () => {
|
||||||
@@ -1734,7 +1736,7 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
|
|||||||
render(<AdminPluginsPanel />)
|
render(<AdminPluginsPanel />)
|
||||||
await screen.findByText('Alpha Widget')
|
await screen.findByText('Alpha Widget')
|
||||||
|
|
||||||
await pickFilter(user, /^Type:/, /^Widget$/)
|
await pickFilter(user, /^Widget$/)
|
||||||
|
|
||||||
await waitFor(() => expect(screen.queryByText('Beta Bridge')).not.toBeInTheDocument())
|
await waitFor(() => expect(screen.queryByText('Beta Bridge')).not.toBeInTheDocument())
|
||||||
expect(screen.getByText('Alpha Widget')).toBeInTheDocument()
|
expect(screen.getByText('Alpha Widget')).toBeInTheDocument()
|
||||||
@@ -1746,15 +1748,15 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
|
|||||||
render(<AdminPluginsPanel />)
|
render(<AdminPluginsPanel />)
|
||||||
await screen.findByText('Alpha Widget')
|
await screen.findByText('Alpha Widget')
|
||||||
|
|
||||||
await pickFilter(user, /^Status:/, /^Active$/)
|
await pickFilter(user, /^Active$/)
|
||||||
await waitFor(() => expect(screen.queryByText('Beta Bridge')).not.toBeInTheDocument())
|
await waitFor(() => expect(screen.queryByText('Beta Bridge')).not.toBeInTheDocument())
|
||||||
expect(screen.queryByText('Gamma Page')).not.toBeInTheDocument()
|
expect(screen.queryByText('Gamma Page')).not.toBeInTheDocument()
|
||||||
|
|
||||||
await pickFilter(user, /^Status:/, /^Off$/)
|
await pickFilter(user, /^Off$/)
|
||||||
await waitFor(() => expect(screen.getByText('Beta Bridge')).toBeInTheDocument())
|
await waitFor(() => expect(screen.getByText('Beta Bridge')).toBeInTheDocument())
|
||||||
expect(screen.queryByText('Alpha Widget')).not.toBeInTheDocument()
|
expect(screen.queryByText('Alpha Widget')).not.toBeInTheDocument()
|
||||||
|
|
||||||
await pickFilter(user, /^Status:/, /^Error$/)
|
await pickFilter(user, /^Error$/)
|
||||||
await waitFor(() => expect(screen.getByText('Gamma Page')).toBeInTheDocument())
|
await waitFor(() => expect(screen.getByText('Gamma Page')).toBeInTheDocument())
|
||||||
expect(screen.queryByText('Alpha Widget')).not.toBeInTheDocument()
|
expect(screen.queryByText('Alpha Widget')).not.toBeInTheDocument()
|
||||||
})
|
})
|
||||||
@@ -1766,13 +1768,13 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
|
|||||||
await screen.findByText('Alpha Widget')
|
await screen.findByText('Alpha Widget')
|
||||||
await waitFor(() => expect(screen.getByText(/updates? available/i)).toBeInTheDocument())
|
await waitFor(() => expect(screen.getByText(/updates? available/i)).toBeInTheDocument())
|
||||||
|
|
||||||
await pickFilter(user, /^Sort:/, /^Updates first$/)
|
await pickFilter(user, /^Updates first$/)
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
const names = screen.getAllByText(/Alpha Widget|Beta Bridge|Gamma Page/).map(e => e.textContent)
|
const names = screen.getAllByText(/Alpha Widget|Beta Bridge|Gamma Page/).map(e => e.textContent)
|
||||||
expect(names[0]).toBe('Gamma Page')
|
expect(names[0]).toBe('Gamma Page')
|
||||||
})
|
})
|
||||||
|
|
||||||
await pickFilter(user, /^Status:/, /^Update available$/)
|
await pickFilter(user, /^Update available$/)
|
||||||
await waitFor(() => expect(screen.queryByText('Alpha Widget')).not.toBeInTheDocument())
|
await waitFor(() => expect(screen.queryByText('Alpha Widget')).not.toBeInTheDocument())
|
||||||
expect(screen.getByText('Gamma Page')).toBeInTheDocument()
|
expect(screen.getByText('Gamma Page')).toBeInTheDocument()
|
||||||
})
|
})
|
||||||
@@ -1783,11 +1785,10 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
|
|||||||
render(<AdminPluginsPanel />)
|
render(<AdminPluginsPanel />)
|
||||||
await screen.findByText('Alpha Widget')
|
await screen.findByText('Alpha Widget')
|
||||||
|
|
||||||
await pickFilter(user, /^Sort:/, /^Updates first$/)
|
await pickFilter(user, /^Updates first$/)
|
||||||
expect(screen.getByTitle(/^Sort: Updates first$/)).toBeInTheDocument()
|
expect(filterButton()).toHaveTextContent('Updates first')
|
||||||
|
|
||||||
await user.click(screen.getByRole('tab', { name: /Discover/ }))
|
await user.click(screen.getByRole('tab', { name: /Discover/ }))
|
||||||
await waitFor(() => expect(screen.getByTitle(/^Sort: Name$/)).toBeInTheDocument())
|
await waitFor(() => expect(filterButton()).toHaveTextContent(/Name$/))
|
||||||
})
|
})
|
||||||
|
|
||||||
it('FE-W5PLG-007: the registry sorts by downloads and by review date', async () => {
|
it('FE-W5PLG-007: the registry sorts by downloads and by review date', async () => {
|
||||||
@@ -1802,19 +1803,19 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
|
|||||||
await user.click(screen.getByRole('tab', { name: /Discover/ }))
|
await user.click(screen.getByRole('tab', { name: /Discover/ }))
|
||||||
await screen.findByText('Old Tool')
|
await screen.findByText('Old Tool')
|
||||||
|
|
||||||
await pickFilter(user, /^Sort:/, /^Most downloads$/)
|
await pickFilter(user, /^Most downloads$/)
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
const names = screen.getAllByText(/^(Old|New) Tool$/).map(e => e.textContent)
|
const names = screen.getAllByText(/^(Old|New) Tool$/).map(e => e.textContent)
|
||||||
expect(names[0]).toBe('New Tool')
|
expect(names[0]).toBe('New Tool')
|
||||||
})
|
})
|
||||||
|
|
||||||
await pickFilter(user, /^Sort:/, /^Recently updated$/)
|
await pickFilter(user, /^Recently updated$/)
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
const names = screen.getAllByText(/^(Old|New) Tool$/).map(e => e.textContent)
|
const names = screen.getAllByText(/^(Old|New) Tool$/).map(e => e.textContent)
|
||||||
expect(names[0]).toBe('New Tool')
|
expect(names[0]).toBe('New Tool')
|
||||||
})
|
})
|
||||||
|
|
||||||
await pickFilter(user, /^Sort:/, /^Name$/)
|
await pickFilter(user, /^Name$/)
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
const names = screen.getAllByText(/^(Old|New) Tool$/).map(e => e.textContent)
|
const names = screen.getAllByText(/^(Old|New) Tool$/).map(e => e.textContent)
|
||||||
expect(names[0]).toBe('New Tool')
|
expect(names[0]).toBe('New Tool')
|
||||||
@@ -1833,7 +1834,7 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
|
|||||||
await user.click(screen.getByRole('tab', { name: /Discover/ }))
|
await user.click(screen.getByRole('tab', { name: /Discover/ }))
|
||||||
await screen.findByText('Mapper')
|
await screen.findByText('Mapper')
|
||||||
|
|
||||||
await pickFilter(user, /^Type:/, /^Page$/)
|
await pickFilter(user, /^Page$/)
|
||||||
await waitFor(() => expect(screen.queryByText('Mapper')).not.toBeInTheDocument())
|
await waitFor(() => expect(screen.queryByText('Mapper')).not.toBeInTheDocument())
|
||||||
expect(screen.getByText('Poster')).toBeInTheDocument()
|
expect(screen.getByText('Poster')).toBeInTheDocument()
|
||||||
|
|
||||||
@@ -1962,12 +1963,12 @@ describe('AdminPluginsPanel toolbar and dialogs', () => {
|
|||||||
const { container } = render(<AdminPluginsPanel />)
|
const { container } = render(<AdminPluginsPanel />)
|
||||||
await screen.findByText('Alpha Widget')
|
await screen.findByText('Alpha Widget')
|
||||||
|
|
||||||
await user.click(screen.getByTitle(/^Type:/))
|
await user.click(filterButton())
|
||||||
expect(screen.getByRole('button', { name: /^Widget$/ })).toBeInTheDocument()
|
expect(screen.getByRole('menuitemradio', { name: /^Widget$/ })).toBeInTheDocument()
|
||||||
|
|
||||||
const layer = container.querySelector('.fixed.inset-0.z-20') as HTMLElement
|
const layer = container.querySelector('.fixed.inset-0.z-20') as HTMLElement
|
||||||
fireEvent.click(layer)
|
fireEvent.click(layer)
|
||||||
await waitFor(() => expect(screen.queryByRole('button', { name: /^Widget$/ })).not.toBeInTheDocument())
|
await waitFor(() => expect(screen.queryByRole('menuitemradio', { name: /^Widget$/ })).not.toBeInTheDocument())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -2004,12 +2005,11 @@ describe('AdminPluginsPanel registry cards and dependency chips', () => {
|
|||||||
await screen.findByText('Alpha Widget')
|
await screen.findByText('Alpha Widget')
|
||||||
|
|
||||||
await openDiscover(user)
|
await openDiscover(user)
|
||||||
await user.click(screen.getByTitle(/^Sort:/))
|
await user.click(filterButton())
|
||||||
await user.click(screen.getByRole('button', { name: /^Most downloads$/ }))
|
await user.click(screen.getByRole('menuitemradio', { name: /^Most downloads$/ }))
|
||||||
expect(screen.getByTitle(/^Sort: Most downloads$/)).toBeInTheDocument()
|
expect(filterButton()).toHaveTextContent('Most downloads')
|
||||||
|
|
||||||
await user.click(screen.getByRole('tab', { name: /Installed/ }))
|
await user.click(screen.getByRole('tab', { name: /Installed/ }))
|
||||||
await waitFor(() => expect(screen.getByTitle(/^Sort: Name$/)).toBeInTheDocument())
|
await waitFor(() => expect(filterButton()).toHaveTextContent(/Name$/))
|
||||||
})
|
})
|
||||||
|
|
||||||
it('FE-W5PLG-017: an outrun release offers the newest compatible version instead of a dead button', async () => {
|
it('FE-W5PLG-017: an outrun release offers the newest compatible version instead of a dead button', async () => {
|
||||||
@@ -2026,9 +2026,8 @@ describe('AdminPluginsPanel registry cards and dependency chips', () => {
|
|||||||
expect(offer).not.toBeDisabled()
|
expect(offer).not.toBeDisabled()
|
||||||
expect(offer).toHaveAttribute('title', expect.stringContaining('3.5.0'))
|
expect(offer).toHaveAttribute('title', expect.stringContaining('3.5.0'))
|
||||||
|
|
||||||
const dead = screen.getByRole('button', { name: /^Incompatible$/ })
|
// Nothing fits: no dead button any more, but a card that says so before anything installs.
|
||||||
expect(dead).toBeDisabled()
|
expect(screen.getByText(/^Not confirmed for TREK .+ yet$/)).toBeInTheDocument()
|
||||||
expect(dead.getAttribute('title')).toBeTruthy()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('FE-W5PLG-018: an already installed registry entry cannot be installed again', async () => {
|
it('FE-W5PLG-018: an already installed registry entry cannot be installed again', async () => {
|
||||||
@@ -2556,7 +2555,7 @@ describe('AdminPluginsPanel — TREK-range bypass (TREK_PLUGINS_IGNORE_TREK_RANG
|
|||||||
expect(await screen.findByText('Version checks off')).toBeInTheDocument()
|
expect(await screen.findByText('Version checks off')).toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('FE-PLG-BYPASS-002: offers "Install anyway" for an incompatible entry and asks before installing', async () => {
|
it('FE-PLG-BYPASS-002: offers Install for an incompatible entry and asks before installing', async () => {
|
||||||
let posted: unknown = null
|
let posted: unknown = null
|
||||||
bypassPanel([plugin({ id: 'something-else' })], incompatibleEntry())
|
bypassPanel([plugin({ id: 'something-else' })], incompatibleEntry())
|
||||||
server.use(http.post('*/api/admin/plugins/install', async ({ request }) => {
|
server.use(http.post('*/api/admin/plugins/install', async ({ request }) => {
|
||||||
@@ -2566,7 +2565,7 @@ describe('AdminPluginsPanel — TREK-range bypass (TREK_PLUGINS_IGNORE_TREK_RANG
|
|||||||
withToast()
|
withToast()
|
||||||
fireEvent.click(await screen.findByText('Discover'))
|
fireEvent.click(await screen.findByText('Discover'))
|
||||||
|
|
||||||
const btn = await screen.findByRole('button', { name: /^install anyway$/i })
|
const btn = await screen.findByRole('button', { name: /^install$/i })
|
||||||
expect(btn).toBeEnabled()
|
expect(btn).toBeEnabled()
|
||||||
fireEvent.click(btn)
|
fireEvent.click(btn)
|
||||||
|
|
||||||
@@ -2585,7 +2584,7 @@ describe('AdminPluginsPanel — TREK-range bypass (TREK_PLUGINS_IGNORE_TREK_RANG
|
|||||||
server.use(http.post('*/api/admin/plugins/install', () => { posted = true; return HttpResponse.json({ id: 'trek-gotify', version: '2.0.0', trekRangeBypassed: null }) }))
|
server.use(http.post('*/api/admin/plugins/install', () => { posted = true; return HttpResponse.json({ id: 'trek-gotify', version: '2.0.0', trekRangeBypassed: null }) }))
|
||||||
withToast()
|
withToast()
|
||||||
fireEvent.click(await screen.findByText('Discover'))
|
fireEvent.click(await screen.findByText('Discover'))
|
||||||
fireEvent.click(await screen.findByRole('button', { name: /^install anyway$/i }))
|
fireEvent.click(await screen.findByRole('button', { name: /^install$/i }))
|
||||||
|
|
||||||
const dialog = await screen.findByRole('dialog', { name: /outside its supported trek versions/i })
|
const dialog = await screen.findByRole('dialog', { name: /outside its supported trek versions/i })
|
||||||
fireEvent.click(within(dialog).getByRole('button', { name: /cancel/i }))
|
fireEvent.click(within(dialog).getByRole('button', { name: /cancel/i }))
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react'
|
import { useState, type ReactNode } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
|
||||||
import {
|
import {
|
||||||
Blocks, AlertTriangle, RefreshCw, Trash2, Download, Bug, ShieldCheck, UploadCloud,
|
Blocks, AlertTriangle, RefreshCw, Trash2, Download, Bug, ShieldCheck, UploadCloud,
|
||||||
ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search, Link2, KeyRound, ShieldAlert,
|
ArrowUpCircle, Github, ExternalLink, Check, Search, Link2, KeyRound, ShieldAlert,
|
||||||
SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, Database,
|
SlidersHorizontal, CircleDot, Database,
|
||||||
Globe, Info, History, PauseCircle, Puzzle, Bot, Loader2,
|
Globe, History, Puzzle, Bot, Loader2,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import PluginIcon from '../shared/PluginIcon'
|
import PluginIcon from '../shared/PluginIcon'
|
||||||
import { useInstanceSettings } from './useInstanceSettings'
|
import { useInstanceSettings } from './useInstanceSettings'
|
||||||
@@ -23,15 +22,17 @@ import {
|
|||||||
SettingsCard, SettingRows, SettingRow, SettingsHint, StatusPill,
|
SettingsCard, SettingRows, SettingRow, SettingsHint, StatusPill,
|
||||||
SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON,
|
SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON,
|
||||||
} from '../Settings/settingsKit'
|
} from '../Settings/settingsKit'
|
||||||
import { POPOVER } from '../Packing/packingPopoverStyles'
|
|
||||||
import {
|
import {
|
||||||
KNOWN_TYPES, PERM_KEYS, blockIsCurrent, dependencyRows, deriveDeps, fingerprint, formatCompactCount,
|
KNOWN_TYPES, PERM_KEYS, blockIsCurrent, dependencyRows, fingerprint, formatCompactCount,
|
||||||
installOffer, isRegistrySourced, parseJson, signatureBlockView, sortLabel, statusLabel,
|
installOffer, signatureBlockView,
|
||||||
type PluginDep, type PluginRow, type RegistryItem, type SigSubject, type SortKey,
|
type PluginDep, type PluginRow, type RegistryItem, type SigSubject,
|
||||||
type StatusFilter, type T, type TypeFilter, type VersionInfo, type VersionMismatch,
|
type T, type VersionInfo, type VersionMismatch,
|
||||||
} from './plugins/pluginModel'
|
} from './plugins/pluginModel'
|
||||||
import { usePluginDetail } from './plugins/usePluginDetail'
|
import { usePluginDetail } from './plugins/usePluginDetail'
|
||||||
import { usePluginsAdmin } from './plugins/usePluginsAdmin'
|
import { usePluginsAdmin } from './plugins/usePluginsAdmin'
|
||||||
|
import PluginFilterMenu from './plugins/PluginFilterMenu'
|
||||||
|
import PluginInstalledRow from './plugins/PluginInstalledRow'
|
||||||
|
import PluginSecurityDialog from './plugins/PluginSecurityDialog'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Admin → Plugins (#plugins). A full plugin-management surface: a segmented
|
* Admin → Plugins (#plugins). A full plugin-management surface: a segmented
|
||||||
@@ -42,31 +43,13 @@ import { usePluginsAdmin } from './plugins/usePluginsAdmin'
|
|||||||
* tile; the security section at the bottom explains the model honestly.
|
* tile; the security section at the bottom explains the model honestly.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Runtime health → dot colour on the icon tile.
|
|
||||||
const HEALTH: Record<string, string> = {
|
|
||||||
active: 'bg-success',
|
|
||||||
starting: 'bg-info animate-pulse',
|
|
||||||
error: 'bg-danger',
|
|
||||||
inactive: 'bg-content-faint/60',
|
|
||||||
disabled: 'bg-warning',
|
|
||||||
incompatible: 'bg-warning',
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The head band of a dialog that warns before something happens: a faint wash of the warning tone. */
|
/** The head band of a dialog that warns before something happens: a faint wash of the warning tone. */
|
||||||
const WARN_TINT = 'color-mix(in srgb, var(--warning) 10%, transparent)'
|
const WARN_TINT = 'color-mix(in srgb, var(--warning) 10%, transparent)'
|
||||||
/** The eyebrow over a block, the size the dialogs' sections use. */
|
/** The eyebrow over a block, the size the dialogs' sections use. */
|
||||||
const EYEBROW = 'm-0 font-geist font-bold uppercase tracking-[.08em] text-content-faint'
|
const EYEBROW = 'm-0 font-geist font-bold uppercase tracking-[.08em] text-content-faint'
|
||||||
/** A capability or dependency chip on an installed row. */
|
|
||||||
const CHIP = 'inline-flex max-w-full items-center gap-1.5 rounded-full border px-2 py-[2px] font-medium'
|
|
||||||
const CHIP_NEUTRAL = 'border-edge-faint bg-surface-secondary text-content-secondary'
|
|
||||||
const CHIP_NET = 'border-transparent bg-info-soft text-info'
|
|
||||||
const CHIP_WARN = 'border-transparent bg-warning-soft text-warning'
|
|
||||||
/** A small action inside a row or a card: the kit's button, a size down. */
|
/** A small action inside a row or a card: the kit's button, a size down. */
|
||||||
const SMALL_BUTTON = 'inline-flex flex-none items-center justify-center gap-1.5 rounded-[10px] bg-surface-card px-2.5 py-1.5 font-semibold text-content shadow-sm ring-1 ring-edge-faint hover:bg-surface-secondary disabled:cursor-default disabled:opacity-50'
|
const SMALL_BUTTON = 'inline-flex flex-none items-center justify-center gap-1.5 rounded-[10px] bg-surface-card px-2.5 py-1.5 font-semibold text-content shadow-sm ring-1 ring-edge-faint hover:bg-surface-secondary disabled:cursor-default disabled:opacity-50'
|
||||||
const SMALL_PRIMARY = 'inline-flex flex-none items-center justify-center gap-1.5 rounded-[10px] bg-accent px-3 py-1.5 font-semibold text-accent-text hover:opacity-90 disabled:cursor-default disabled:bg-surface-tertiary disabled:text-content-faint'
|
const SMALL_PRIMARY = 'inline-flex flex-none items-center justify-center gap-1.5 rounded-[10px] bg-accent px-3 py-1.5 font-semibold text-accent-text hover:opacity-90 disabled:cursor-default disabled:bg-surface-tertiary disabled:text-content-faint'
|
||||||
/** A line of state under a row's name: a refused update, a paused one, an error. */
|
|
||||||
const ROW_NOTE = 'mt-1.5 flex min-w-0 items-center gap-1.5'
|
|
||||||
|
|
||||||
/** A pill that explains itself on hover. */
|
/** A pill that explains itself on hover. */
|
||||||
function HintPill({ hint, children }: { hint: string; children: ReactNode }) {
|
function HintPill({ hint, children }: { hint: string; children: ReactNode }) {
|
||||||
return (
|
return (
|
||||||
@@ -76,19 +59,6 @@ function HintPill({ hint, children }: { hint: string; children: ReactNode }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function ReviewedBadge({ t }: { t: T }) {
|
|
||||||
return <ShieldCheck size={13} className="text-success shrink-0" aria-label={t('admin.plugins.reviewed')} />
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Marks a manually-uploaded (sideloaded) plugin: no registry, unsigned, not reviewed. */
|
|
||||||
function SideloadedBadge({ t }: { t: T }) {
|
|
||||||
return (
|
|
||||||
<HintPill hint={t('admin.plugins.sideloadedHint')}>
|
|
||||||
<StatusPill tone="warning" icon={<UploadCloud size={11} />}>{t('admin.plugins.sideloaded')}</StatusPill>
|
|
||||||
</HintPill>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Signed / Unsigned, for registry plugins only (see isRegistrySourced).
|
* Signed / Unsigned, for registry plugins only (see isRegistrySourced).
|
||||||
*
|
*
|
||||||
@@ -113,15 +83,6 @@ function TrustBadge({ signed, t }: { signed: boolean; t: T }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Marks a dev-linked plugin: loaded from a local build dir + hot-reloaded (dev only). */
|
|
||||||
function DevLinkBadge({ t }: { t: T }) {
|
|
||||||
return (
|
|
||||||
<HintPill hint={t('admin.plugins.devLinkHint')}>
|
|
||||||
<StatusPill icon={<Link2 size={11} />}>{t('admin.plugins.devLinkBadge')}</StatusPill>
|
|
||||||
</HintPill>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function TypeBadge({ type, t }: { type: string; t: T }) {
|
function TypeBadge({ type, t }: { type: string; t: T }) {
|
||||||
return (
|
return (
|
||||||
<span className="inline-flex flex-none items-center rounded-full bg-surface-tertiary px-2 py-[3px] font-geist font-bold uppercase tracking-[.06em] text-content-muted" style={fs(9.5)}>
|
<span className="inline-flex flex-none items-center rounded-full bg-surface-tertiary px-2 py-[3px] font-geist font-bold uppercase tracking-[.06em] text-content-muted" style={fs(9.5)}>
|
||||||
@@ -145,6 +106,7 @@ export default function AdminPluginsPanel() {
|
|||||||
sort, statusFilter, toggle, typeFilter, uninstallConfirmed, updatable, updateAll, updateAvailable, uploadInputRef,
|
sort, statusFilter, toggle, typeFilter, uninstallConfirmed, updatable, updateAll, updateAvailable, uploadInputRef,
|
||||||
uploadPlugin, versionPicker, view,
|
uploadPlugin, versionPicker, view,
|
||||||
} = usePluginsAdmin()
|
} = usePluginsAdmin()
|
||||||
|
const [securityOpen, setSecurityOpen] = useState(false)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative mb-24 sm:mb-0"
|
<div className="relative mb-24 sm:mb-0"
|
||||||
@@ -181,6 +143,9 @@ export default function AdminPluginsPanel() {
|
|||||||
) : undefined}
|
) : undefined}
|
||||||
action={ready ? (
|
action={ready ? (
|
||||||
<>
|
<>
|
||||||
|
<BandButton label={t('admin.plugins.security.short')} onClick={() => setSecurityOpen(true)}>
|
||||||
|
<ShieldCheck size={15} strokeWidth={2} />
|
||||||
|
</BandButton>
|
||||||
<BandButton label={t('admin.plugins.upload')} onClick={pickUpload} disabled={busy === '__upload'}>
|
<BandButton label={t('admin.plugins.upload')} onClick={pickUpload} disabled={busy === '__upload'}>
|
||||||
<UploadCloud size={15} strokeWidth={2} />
|
<UploadCloud size={15} strokeWidth={2} />
|
||||||
</BandButton>
|
</BandButton>
|
||||||
@@ -242,31 +207,9 @@ export default function AdminPluginsPanel() {
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<FilterMenu id="type" label={t('admin.plugins.filterType')} value={typeFilter} menu={menu} setMenu={setMenu} icon={<SlidersHorizontal size={14} />}
|
<PluginFilterMenu t={t} view={view} typeFilter={typeFilter} setTypeFilter={setTypeFilter}
|
||||||
options={[
|
statusFilter={statusFilter} setStatusFilter={setStatusFilter} sort={sort} setSort={setSort}
|
||||||
['all', t('admin.plugins.allTypes')], ['widget', t('admin.plugins.type.widget')],
|
menu={menu} setMenu={setMenu} />
|
||||||
['integration', t('admin.plugins.type.integration')], ['page', t('admin.plugins.type.page')],
|
|
||||||
['trip-page', t('admin.plugins.type.trip-page')],
|
|
||||||
]}
|
|
||||||
valueLabel={typeFilter === 'all' ? t('admin.plugins.allTypes') : t(`admin.plugins.type.${typeFilter}` as never)}
|
|
||||||
onPick={v => setTypeFilter(v as TypeFilter)} />
|
|
||||||
|
|
||||||
{view === 'installed' && (
|
|
||||||
<FilterMenu id="status" label={t('admin.plugins.filterStatus')} value={statusFilter} menu={menu} setMenu={setMenu} icon={<CircleDot size={14} />}
|
|
||||||
options={[
|
|
||||||
['all', t('admin.plugins.allStatuses')], ['on', t('admin.plugins.status.active')], ['off', t('admin.plugins.stateOff')],
|
|
||||||
['update', t('admin.plugins.filterUpdate')], ['err', t('admin.plugins.status.error')],
|
|
||||||
]}
|
|
||||||
valueLabel={statusLabel(statusFilter, t)}
|
|
||||||
onPick={v => setStatusFilter(v as StatusFilter)} />
|
|
||||||
)}
|
|
||||||
|
|
||||||
<FilterMenu id="sort" label={t('admin.plugins.sortBy')} value={sort} menu={menu} setMenu={setMenu} icon={<ArrowUpDown size={14} />}
|
|
||||||
options={view === 'discover'
|
|
||||||
? [['name', t('admin.plugins.sortName')], ['recent', t('admin.plugins.sortRecent')], ['downloads', t('admin.plugins.sortDownloads')]]
|
|
||||||
: [['name', t('admin.plugins.sortName')], ['recent', t('admin.plugins.sortRecent')], ['updates', t('admin.plugins.sortUpdates')]]}
|
|
||||||
valueLabel={sortLabel(sort, t)}
|
|
||||||
onPick={v => setSort(v as SortKey)} />
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{view === 'discover' ? (
|
{view === 'discover' ? (
|
||||||
@@ -299,7 +242,7 @@ export default function AdminPluginsPanel() {
|
|||||||
) : (
|
) : (
|
||||||
<SettingRows>
|
<SettingRows>
|
||||||
{shownInstalled.map(p => (
|
{shownInstalled.map(p => (
|
||||||
<InstalledRow key={p.id} p={p} t={t} busy={busy} menu={menu} setMenu={setMenu}
|
<PluginInstalledRow key={p.id} p={p} t={t} busy={busy} menu={menu} setMenu={setMenu}
|
||||||
hasUpdate={updateAvailable(p)} latestVer={latest[p.id]}
|
hasUpdate={updateAvailable(p)} latestVer={latest[p.id]}
|
||||||
newerIncompatible={newerIncompatible(p)}
|
newerIncompatible={newerIncompatible(p)}
|
||||||
blocked={blockIsCurrent(p, latest[p.id])}
|
blocked={blockIsCurrent(p, latest[p.id])}
|
||||||
@@ -320,7 +263,7 @@ export default function AdminPluginsPanel() {
|
|||||||
)}
|
)}
|
||||||
</SettingsCard>
|
</SettingsCard>
|
||||||
|
|
||||||
<SecurityInfo t={t} />
|
{securityOpen && <PluginSecurityDialog t={t} onClose={() => setSecurityOpen(false)} />}
|
||||||
|
|
||||||
{/* Registry detail dialog */}
|
{/* Registry detail dialog */}
|
||||||
{detailFor && (
|
{detailFor && (
|
||||||
@@ -438,268 +381,6 @@ function SegBtn({ active, onClick, label, count }: { active: boolean; onClick: (
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Re-renders while the page moves under an open, portaled menu, so it stays pinned to its trigger. */
|
|
||||||
function useFollowTrigger(open: boolean) {
|
|
||||||
const [, reanchor] = useState(0)
|
|
||||||
useEffect(() => {
|
|
||||||
if (!open) return
|
|
||||||
const onMove = () => reanchor(n => n + 1)
|
|
||||||
window.addEventListener('scroll', onMove, true)
|
|
||||||
window.addEventListener('resize', onMove)
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('scroll', onMove, true)
|
|
||||||
window.removeEventListener('resize', onMove)
|
|
||||||
}
|
|
||||||
}, [open])
|
|
||||||
}
|
|
||||||
|
|
||||||
function FilterMenu({ id, label, valueLabel, options, onPick, value, menu, setMenu, icon }: {
|
|
||||||
id: string; label: string; valueLabel: string
|
|
||||||
options: Array<[string, string]>; onPick: (v: string) => void; value: string
|
|
||||||
menu: string | null; setMenu: (v: string | null) => void; icon?: ReactNode
|
|
||||||
}) {
|
|
||||||
const open = menu === id
|
|
||||||
const active = value !== options[0]?.[0]
|
|
||||||
const btnRef = useRef<HTMLButtonElement>(null)
|
|
||||||
// Portaled like the row menu: the card around the toolbar clips what overflows it.
|
|
||||||
useFollowTrigger(open)
|
|
||||||
return (
|
|
||||||
<div className="relative flex-none">
|
|
||||||
<button type="button" ref={btnRef} onClick={() => setMenu(open ? null : id)} title={`${label}: ${valueLabel}`} aria-expanded={open}
|
|
||||||
className={`inline-flex h-9 items-center gap-1.5 whitespace-nowrap rounded-[10px] border bg-surface-card px-3 text-content-secondary transition-colors hover:text-content ${
|
|
||||||
active ? 'border-[color:var(--text-primary)]' : 'border-edge'}`}
|
|
||||||
style={fs(12.5, 'body')}>
|
|
||||||
<span className="flex-none text-content-faint">{icon}</span>
|
|
||||||
<span>{label}: </span>
|
|
||||||
<span className="font-semibold text-content">{valueLabel}</span>
|
|
||||||
<ChevronDown size={13} className={`flex-none text-content-faint transition-transform ${open ? 'rotate-180' : ''}`} />
|
|
||||||
</button>
|
|
||||||
{open && createPortal(
|
|
||||||
<div className="min-w-[200px] max-w-[calc(100vw-2rem)]" style={{ ...POPOVER, ...anchorMenu(btnRef.current) }}>
|
|
||||||
{options.map(([v, lbl]) => (
|
|
||||||
<button type="button" key={v} onClick={() => { onPick(v); setMenu(null) }}
|
|
||||||
className={`${MENU_ITEM} ${value === v ? 'font-semibold text-content' : 'text-content-secondary'}`} style={fs(12.5, 'body')}>
|
|
||||||
<span className="min-w-0 flex-1 truncate text-start">{lbl}</span>
|
|
||||||
<Check size={14} className={`flex-none text-content-muted ${value === v ? 'opacity-100' : 'opacity-0'}`} />
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>,
|
|
||||||
document.body,
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, newerIncompatible, blocked, onToggle, onUpdate, onRestart, onChangeVersion, onResume, onReviewBlock, onErrors, onEgress, onSettings, onUninstall }: {
|
|
||||||
p: PluginRow; t: T; busy: string | null; menu: string | null; setMenu: (v: string | null) => void
|
|
||||||
hasUpdate: boolean; latestVer?: string; newerIncompatible: { version: string; range: string } | null; blocked: boolean
|
|
||||||
onToggle: () => void; onUpdate: () => void; onRestart: () => void; onChangeVersion: () => void; onResume: () => void; onReviewBlock: () => void
|
|
||||||
onErrors: () => void; onEgress: () => void; onSettings: () => void; onUninstall: () => void
|
|
||||||
}) {
|
|
||||||
const caps = deriveCaps(parseJson<string[]>(p.permissions, []), parseJson<{ widget?: { slot?: string } }>(p.capabilities, {}), t)
|
|
||||||
const deps = deriveDeps(p, t)
|
|
||||||
const menuOpen = menu === `row:${p.id}`
|
|
||||||
const menuBtnRef = useRef<HTMLButtonElement>(null)
|
|
||||||
const working = busy === p.id
|
|
||||||
const on = p.enabled === 1 && p.status !== 'error'
|
|
||||||
|
|
||||||
// The menu is portaled to <body> and positioned `fixed` against the ⋯ button,
|
|
||||||
// because the row's ancestor (PageSidebar) is `overflow-hidden` and would clip
|
|
||||||
// an in-flow `absolute` menu — losing Delete on the lower rows of a long list.
|
|
||||||
// Re-anchor while the page moves under it.
|
|
||||||
useFollowTrigger(menuOpen)
|
|
||||||
|
|
||||||
const hostCount = p.egressHostCount ?? 0
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={`group relative flex items-start gap-3 px-3.5 py-3 transition-colors hover:bg-surface-secondary ${working ? 'opacity-60' : ''}`}>
|
|
||||||
<div className="relative mt-0.5 flex-none">
|
|
||||||
<span className="grid h-10 w-10 place-items-center rounded-[12px] border border-edge-faint bg-surface-secondary">
|
|
||||||
<PluginIcon name={p.icon} size={19} className="text-content-secondary" />
|
|
||||||
</span>
|
|
||||||
<Tooltip label={t(`admin.plugins.status.${p.status}` as never)}>
|
|
||||||
<span className={`absolute -bottom-0.5 -end-0.5 h-3 w-3 rounded-full ring-2 ring-surface-card ${HEALTH[p.status] || HEALTH.inactive}`} />
|
|
||||||
</Tooltip>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
|
||||||
<span className="min-w-0 truncate font-semibold tracking-[-.006em] text-content" style={fs(13.5, 'body')}>{p.name}</span>
|
|
||||||
{p.version && <span className="font-geist font-medium tabular-nums text-content-faint" style={fs(11)}>v{p.version}</span>}
|
|
||||||
{p.reviewed_at && <ReviewedBadge t={t} />}
|
|
||||||
{p.source_repo === 'local:upload' && <SideloadedBadge t={t} />}
|
|
||||||
{p.source_repo === 'local:link' && <DevLinkBadge t={t} />}
|
|
||||||
{/* Registry plugins only — a sideloaded/dev-linked plugin already says something
|
|
||||||
strictly stronger, and stacking "Unsigned" on top of it just dilutes the amber. */}
|
|
||||||
{isRegistrySourced(p.source_repo) && <TrustBadge signed={!!p.signed} t={t} />}
|
|
||||||
</div>
|
|
||||||
{p.description && <p className="m-0 mt-0.5 truncate text-content-muted" style={fs(12, 'body')}>{p.description}</p>}
|
|
||||||
{/* A refused update leaves a WORKING plugin pinned at its old version — so this is
|
|
||||||
its own row state, not an error state, and it persists until it is resolved
|
|
||||||
rather than dying with the toast that first reported it. */}
|
|
||||||
{blocked && p.updateBlock && (
|
|
||||||
<div className={`${ROW_NOTE} text-warning`} style={fs(11.5)}>
|
|
||||||
<ShieldAlert size={13} className="flex-none" />
|
|
||||||
<span className="truncate">{t('admin.plugins.updateBlocked', { reason: p.updateBlock.detail ?? p.updateBlock.code })}</span>
|
|
||||||
<button type="button" onClick={onReviewBlock}
|
|
||||||
className="flex-none font-semibold underline underline-offset-2 hover:opacity-80">
|
|
||||||
{t('admin.plugins.reviewBlock')}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{/* A newer version this TREK can't run — informational, never a button: the fix
|
|
||||||
is a TREK upgrade, so the row must not nag or offer a doomed install. */}
|
|
||||||
{newerIncompatible && (
|
|
||||||
<div className={`${ROW_NOTE} text-content-faint`} style={fs(11.5)}>
|
|
||||||
<Info size={13} className="flex-none" />
|
|
||||||
<span className="truncate">{t('admin.plugins.newerNeedsTrek', { version: newerIncompatible.version, range: newerIncompatible.range })}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{/* Held: the admin deliberately installed a non-latest version, so updates are
|
|
||||||
paused rather than nagged — resuming is one click, right where the pause shows. */}
|
|
||||||
{p.updateHold && (
|
|
||||||
<div className={`${ROW_NOTE} text-content-faint`} style={fs(11.5)}>
|
|
||||||
<PauseCircle size={13} className="flex-none" />
|
|
||||||
<span className="truncate">{t('admin.plugins.updatesHeld', { version: p.version ?? '' })}</span>
|
|
||||||
<button type="button" onClick={onResume} disabled={working}
|
|
||||||
className="flex-none font-semibold text-content-secondary underline underline-offset-2 hover:opacity-80 disabled:opacity-50">
|
|
||||||
{t('admin.plugins.resumeUpdates')}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{p.status === 'error' && p.last_error ? (
|
|
||||||
<div className={`${ROW_NOTE} text-danger`} style={fs(11.5)}>
|
|
||||||
<AlertTriangle size={13} className="flex-none" /><span className="truncate">{p.last_error}</span>
|
|
||||||
</div>
|
|
||||||
) : (caps.length > 0 || p.operatorEgress) && (
|
|
||||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
|
||||||
{caps.map((c, i) => (
|
|
||||||
<span key={i} className={`${CHIP} ${c.net ? CHIP_NET : CHIP_NEUTRAL}`} style={fs(11)}>
|
|
||||||
<c.icon size={12} className={c.net ? 'text-info' : 'text-content-muted'} /><span className="truncate">{c.label}</span>
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
{/* This plugin talks to a service only the OPERATOR can name (a self-hosted
|
|
||||||
Gotify/ntfy), so its manifest can't list the host — the admin adds it.
|
|
||||||
Actionable, and warning-toned until at least one host exists, because
|
|
||||||
until then the plugin cannot reach anything and looks silently broken. */}
|
|
||||||
{p.operatorEgress && (
|
|
||||||
<Tooltip label={t('admin.plugins.allowedHosts.hint')}>
|
|
||||||
<button type="button" onClick={onEgress}
|
|
||||||
className={`${CHIP} ${hostCount > 0 ? CHIP_NET : CHIP_WARN} hover:opacity-80`} style={fs(11)}>
|
|
||||||
<Globe size={12} />
|
|
||||||
{hostCount > 0
|
|
||||||
? t('admin.plugins.allowedHosts.count', { n: hostCount })
|
|
||||||
: t('admin.plugins.allowedHosts.add')}
|
|
||||||
</button>
|
|
||||||
</Tooltip>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{deps.length > 0 && (
|
|
||||||
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
|
|
||||||
{deps.map((d, i) => (
|
|
||||||
<span key={i} className={`${CHIP} ${d.blocked || d.warn ? CHIP_WARN : CHIP_NEUTRAL}`} style={fs(11)}>
|
|
||||||
<d.icon size={12} className={d.blocked || d.warn ? 'text-warning' : 'text-content-muted'} /><span className="truncate">{d.label}</span>
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-none items-center gap-2 self-center">
|
|
||||||
{hasUpdate && (
|
|
||||||
<button type="button" onClick={onUpdate} disabled={working}
|
|
||||||
className="inline-flex items-center gap-1.5 rounded-full bg-warning-soft px-2.5 py-1 font-semibold text-warning hover:opacity-90 disabled:opacity-50"
|
|
||||||
style={fs(11.5)}>
|
|
||||||
<ArrowUpCircle size={13} /> <span>{t('admin.plugins.updateTo', { version: latestVer })}</span>
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
<span className={`min-w-[42px] text-end font-medium ${on ? 'text-content-secondary' : 'text-content-faint'}`} style={fs(12)}>
|
|
||||||
{p.enabled === 1 ? t('admin.plugins.status.active') : t('admin.plugins.stateOff')}
|
|
||||||
</span>
|
|
||||||
<ToggleSwitch on={p.enabled === 1} label={t('admin.plugins.enabledToggle')} onToggle={onToggle} />
|
|
||||||
<div className="relative">
|
|
||||||
<Tooltip label={t('admin.table.actions')} disabled={menuOpen}>
|
|
||||||
<button type="button" ref={menuBtnRef} data-testid={`plugin-row-menu-btn-${p.id}`} onClick={() => setMenu(menuOpen ? null : `row:${p.id}`)}
|
|
||||||
aria-expanded={menuOpen} aria-label={t('admin.table.actions')}
|
|
||||||
className={`grid h-8 w-8 place-items-center rounded-[10px] transition-colors ${menuOpen ? 'bg-surface-card text-content shadow-sm ring-1 ring-edge-faint' : 'text-content-faint hover:bg-surface-card hover:text-content'}`}>
|
|
||||||
<MoreHorizontal size={17} />
|
|
||||||
</button>
|
|
||||||
</Tooltip>
|
|
||||||
{menuOpen && createPortal(
|
|
||||||
<div data-testid={`plugin-row-menu-${p.id}`} style={{ ...POPOVER, ...anchorMenu(menuBtnRef.current) }}
|
|
||||||
className="min-w-[200px]">
|
|
||||||
{p.enabled === 1 && (
|
|
||||||
<MenuItem icon={<RotateCw size={14} />} label={t('admin.plugins.restart')} onClick={onRestart} />
|
|
||||||
)}
|
|
||||||
{/* A plugin gets the item if it declares scope:'instance' fields OR actions —
|
|
||||||
an action-only plugin still needs the dialog to run its buttons. */}
|
|
||||||
{((p.instanceSettingsCount ?? 0) > 0 || (p.instanceActionsCount ?? 0) > 0) && (
|
|
||||||
<MenuItem icon={<SlidersHorizontal size={14} />} label={t('admin.plugins.instanceSettings')} onClick={onSettings} />
|
|
||||||
)}
|
|
||||||
<MenuItem icon={<Bug size={14} />} label={t('admin.plugins.viewErrors')} onClick={onErrors} />
|
|
||||||
{/* Only a plugin that DECLARED operatorEgress gets the item — an admin must
|
|
||||||
never be invited to widen egress for a plugin that didn't ask for it
|
|
||||||
(same rule the row's egress chip follows). */}
|
|
||||||
{p.operatorEgress && (
|
|
||||||
<MenuItem icon={<Globe size={14} />} label={t('admin.plugins.allowedHosts')} onClick={onEgress} />
|
|
||||||
)}
|
|
||||||
{/* Registry plugins only — a sideload/dev-link has no registry versions to pick from. */}
|
|
||||||
{isRegistrySourced(p.source_repo) && (
|
|
||||||
<MenuItem icon={<History size={14} />} label={t('admin.plugins.changeVersion')} onClick={onChangeVersion} />
|
|
||||||
)}
|
|
||||||
{p.source_repo && p.source_repo !== 'local:upload' && p.source_repo !== 'local:link' && (
|
|
||||||
<>
|
|
||||||
<a href={`https://github.com/${p.source_repo}`} target="_blank" rel="noreferrer" onClick={() => setMenu(null)}
|
|
||||||
className={`${MENU_ITEM} text-content-secondary`} style={fs(12.5, 'body')}>
|
|
||||||
<span className="flex w-4 flex-none justify-center text-content-muted"><Github size={14} /></span> {t('admin.plugins.sourceRepo')}
|
|
||||||
</a>
|
|
||||||
<a href={`https://github.com/${p.source_repo}/issues`} target="_blank" rel="noreferrer" onClick={() => setMenu(null)}
|
|
||||||
className={`${MENU_ITEM} text-content-secondary`} style={fs(12.5, 'body')}>
|
|
||||||
<span className="flex w-4 flex-none justify-center text-content-muted"><CircleDot size={14} /></span> {t('admin.plugins.reportIssue')}
|
|
||||||
</a>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<div className="mx-1.5 my-1 h-px bg-edge-faint" />
|
|
||||||
<MenuItem icon={<Trash2 size={14} />} label={t('common.delete')} danger onClick={onUninstall} />
|
|
||||||
</div>,
|
|
||||||
document.body,
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Tallest the ⋯ menu gets (6 items + divider + padding). Drives the flip. */
|
|
||||||
const ROW_MENU_MAX_H = 260
|
|
||||||
|
|
||||||
/** Pin a portaled menu to the right edge of its trigger, flipping up when the bottom is tight. */
|
|
||||||
function anchorMenu(trigger: HTMLElement | null): CSSProperties {
|
|
||||||
const r = trigger?.getBoundingClientRect()
|
|
||||||
if (!r) return { position: 'fixed', top: 0, right: 0, zIndex: 100 }
|
|
||||||
const spaceBelow = window.innerHeight - r.bottom
|
|
||||||
const openUp = spaceBelow < ROW_MENU_MAX_H && r.top > spaceBelow
|
|
||||||
return {
|
|
||||||
position: 'fixed',
|
|
||||||
right: Math.max(8, window.innerWidth - r.right),
|
|
||||||
...(openUp ? { bottom: window.innerHeight - r.top + 4 } : { top: r.bottom + 4 }),
|
|
||||||
zIndex: 100,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One entry of a popover menu, in the packing popovers' shape. */
|
|
||||||
const MENU_ITEM = 'flex w-full items-center gap-2.5 rounded-[9px] px-2.5 py-2 font-medium transition-colors hover:bg-surface-tertiary'
|
|
||||||
|
|
||||||
function MenuItem({ icon, label, onClick, danger }: { icon: ReactNode; label: string; onClick: () => void; danger?: boolean }) {
|
|
||||||
return (
|
|
||||||
<button type="button" onClick={onClick}
|
|
||||||
className={`${MENU_ITEM} ${danger ? 'text-danger hover:bg-danger-soft' : 'text-content-secondary'}`} style={fs(12.5, 'body')}>
|
|
||||||
<span className={`flex w-4 flex-none justify-center ${danger ? 'text-danger' : 'text-content-muted'}`}>{icon}</span> {label}
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function Screenshot({ url, className, iconSize = 28 }: { url: string | null; className: string; iconSize?: number }) {
|
function Screenshot({ url, className, iconSize = 28 }: { url: string | null; className: string; iconSize?: number }) {
|
||||||
const [failed, setFailed] = useState(false)
|
const [failed, setFailed] = useState(false)
|
||||||
return (
|
return (
|
||||||
@@ -751,6 +432,16 @@ function RegistryGrid({ items, onInstall, onOpenDetail, busy, t, installedIds, f
|
|||||||
<StatusPill icon={<ShieldCheck size={11} className="text-success" />}>{t('admin.plugins.reviewed')}</StatusPill>
|
<StatusPill icon={<ShieldCheck size={11} className="text-success" />}>{t('admin.plugins.reviewed')}</StatusPill>
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
{/* Says up front that this one has not been confirmed for the TREK it would run on,
|
||||||
|
so "Install" never reads as a plain install; the dialog explains the risk. */}
|
||||||
|
{!installed && offer.warn && (
|
||||||
|
// Solid, not the soft pill "Reviewed" uses: it has to stand out on any screenshot.
|
||||||
|
<span className="absolute start-2.5 top-2.5 inline-flex max-w-[62%] items-center gap-1 rounded-full bg-warning px-2 py-[3px] font-geist font-semibold text-[color:var(--surface-card)] shadow-md"
|
||||||
|
style={fs(11)}>
|
||||||
|
<AlertTriangle size={11} className="flex-none" />
|
||||||
|
<span className="truncate">{t('admin.plugins.untestedChip', { host: offer.warn.hostVersion })}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
<span className="absolute -bottom-4 start-3.5 z-[1] grid h-10 w-10 place-items-center rounded-[12px] border border-edge-faint bg-surface-card shadow-sm">
|
<span className="absolute -bottom-4 start-3.5 z-[1] grid h-10 w-10 place-items-center rounded-[12px] border border-edge-faint bg-surface-card shadow-sm">
|
||||||
<PluginIcon name={item.icon} size={20} className="text-content-secondary" />
|
<PluginIcon name={item.icon} size={20} className="text-content-secondary" />
|
||||||
</span>
|
</span>
|
||||||
@@ -829,8 +520,8 @@ function Tile({ children, warn }: { children: ReactNode; warn?: boolean }) {
|
|||||||
* The TREK_PLUGINS_IGNORE_TREK_RANGE warning (copy and modes from useRangeBypass). Its own
|
* The TREK_PLUGINS_IGNORE_TREK_RANGE warning (copy and modes from useRangeBypass). Its own
|
||||||
* component rather than ConfirmDialog because the notice mode has no cancel button.
|
* component rather than ConfirmDialog because the notice mode has no cancel button.
|
||||||
*/
|
*/
|
||||||
function RangeBypassDialog({ copy: { title, body, confirm }, onConfirm, onClose, t }: {
|
function RangeBypassDialog({ copy: { title, body, confirm, confirmLabel }, onConfirm, onClose, t }: {
|
||||||
copy: { title: string; body: string; confirm: boolean }; onConfirm: () => void; onClose: () => void; t: T
|
copy: { title: string; body: string; confirm: boolean; confirmLabel: string }; onConfirm: () => void; onClose: () => void; t: T
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<DialogShell
|
<DialogShell
|
||||||
@@ -844,7 +535,7 @@ function RangeBypassDialog({ copy: { title, body, confirm }, onConfirm, onClose,
|
|||||||
{confirm ? (
|
{confirm ? (
|
||||||
<>
|
<>
|
||||||
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
|
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
|
||||||
<DialogButton variant="primary" onClick={onConfirm}>{t('admin.plugins.installAnyway')}</DialogButton>
|
<DialogButton variant="primary" onClick={onConfirm}>{confirmLabel}</DialogButton>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<DialogButton variant="primary" onClick={onClose}>{t('common.ok')}</DialogButton>
|
<DialogButton variant="primary" onClick={onClose}>{t('common.ok')}</DialogButton>
|
||||||
@@ -1495,45 +1186,3 @@ function DependencyResolveDialog({ data, t, busy, installedIds, onDownload, onCl
|
|||||||
</DialogShell>
|
</DialogShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Footer: a plain-language note on what "Reviewed" means, plus a collapsible
|
|
||||||
// panel that lays out how plugins are contained, the limits, and the worst case.
|
|
||||||
function SecurityInfo({ t }: { t: T }) {
|
|
||||||
const [open, setOpen] = useState(false)
|
|
||||||
const sections: Array<[string, string]> = [
|
|
||||||
['admin.plugins.security.isolationTitle', 'admin.plugins.security.isolationBody'],
|
|
||||||
['admin.plugins.security.permsTitle', 'admin.plugins.security.permsBody'],
|
|
||||||
['admin.plugins.security.limitsTitle', 'admin.plugins.security.limitsBody'],
|
|
||||||
['admin.plugins.security.worstTitle', 'admin.plugins.security.worstBody'],
|
|
||||||
['admin.plugins.security.reviewedTitle', 'admin.plugins.security.reviewedBody'],
|
|
||||||
['admin.plugins.security.signedTitle', 'admin.plugins.security.signedBody'],
|
|
||||||
['admin.plugins.security.trustTitle', 'admin.plugins.security.trustBody'],
|
|
||||||
]
|
|
||||||
return (
|
|
||||||
<SettingsCard
|
|
||||||
icon={Lock}
|
|
||||||
title={(
|
|
||||||
<button type="button" onClick={() => setOpen(o => !o)} aria-expanded={open}
|
|
||||||
className="inline-flex max-w-full items-center gap-1.5 text-start font-bold text-content hover:opacity-80">
|
|
||||||
<span className="truncate">{t('admin.plugins.security.title')}</span>
|
|
||||||
<ChevronDown size={15} className={`flex-none text-content-faint transition-transform ${open ? 'rotate-180' : ''}`} />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="flex items-start gap-2.5">
|
|
||||||
<ShieldCheck size={14} className="mt-0.5 flex-none text-content-faint" />
|
|
||||||
<SettingsHint>{t('admin.plugins.reviewedMeaning')}</SettingsHint>
|
|
||||||
</div>
|
|
||||||
{open && (
|
|
||||||
<div className="grid gap-2.5 sm:grid-cols-2">
|
|
||||||
{sections.map(([h, b]) => (
|
|
||||||
<div key={h} className="rounded-[12px] border border-edge-faint bg-surface-card px-3.5 py-3">
|
|
||||||
<h4 className="m-0 font-semibold text-content" style={fs(12.5, 'body')}>{t(h as never)}</h4>
|
|
||||||
<p className="m-0 mt-1 leading-relaxed text-content-muted" style={fs(12, 'body')}>{t(b as never)}</p>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</SettingsCard>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ export default function AiAddonTile({
|
|||||||
icon={<Icon size={14} />}
|
icon={<Icon size={14} />}
|
||||||
title={label.name}
|
title={label.name}
|
||||||
description={label.description}
|
description={label.description}
|
||||||
|
badge={addon.id === 'ai_assistant' ? <BetaBadge label={t('assistant.setup.beta')} /> : undefined}
|
||||||
enabled={addon.enabled}
|
enabled={addon.enabled}
|
||||||
onToggle={() => onToggle(addon)}
|
onToggle={() => onToggle(addon)}
|
||||||
/>
|
/>
|
||||||
@@ -93,3 +94,16 @@ export default function AiAddonTile({
|
|||||||
</article>
|
</article>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The assistant is still young; its switch says so with a small accent pill. */
|
||||||
|
function BetaBadge({ label }: { label: string }): React.ReactElement {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className="inline-flex flex-none items-center gap-1 rounded-full bg-accent px-[7px] py-[2px] font-geist font-bold uppercase leading-none tracking-[.08em] text-accent-text shadow-sm"
|
||||||
|
style={fs(9)}
|
||||||
|
>
|
||||||
|
<Sparkles size={9} strokeWidth={2.6} aria-hidden />
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useSearchParams } from 'react-router';
|
import { useSearchParams } from 'react-router';
|
||||||
|
import { openrouterReturnCode } from '../../Settings/ai/aiConnectModel';
|
||||||
import type { Addon } from './addonModel';
|
import type { Addon } from './addonModel';
|
||||||
import { usesConnection } from './aiAddons';
|
import { usesConnection } from './aiAddons';
|
||||||
|
|
||||||
@@ -11,7 +12,7 @@ import { usesConnection } from './aiAddons';
|
|||||||
*/
|
*/
|
||||||
export function useAiAddonTile(aiAddons: Addon[]) {
|
export function useAiAddonTile(aiAddons: Addon[]) {
|
||||||
const [params] = useSearchParams();
|
const [params] = useSearchParams();
|
||||||
const [open, setOpen] = useState(() => params.get('ai') === 'openrouter');
|
const [open, setOpen] = useState(() => openrouterReturnCode(params) !== undefined);
|
||||||
const canSetUp = usesConnection(aiAddons);
|
const canSetUp = usesConnection(aiAddons);
|
||||||
return {
|
return {
|
||||||
enabledCount: aiAddons.filter((a) => a.enabled).length,
|
enabledCount: aiAddons.filter((a) => a.enabled).length,
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
// FE-HOOK-AI-ADMIN-001 to FE-HOOK-AI-ADMIN-007: the AI assistant's settings and connection for everyone.
|
// FE-HOOK-AI-ADMIN-001 to FE-HOOK-AI-ADMIN-008: the AI assistant's settings and connection for everyone.
|
||||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||||
import type { AiAdminConnectionResponse, AiAdminSettings } from '@trek/shared';
|
import type { AiAdminConnectionResponse, AiAdminSettings } from '@trek/shared';
|
||||||
import { MASKED_SETTING_VALUE } from '@trek/shared';
|
import { MASKED_SETTING_VALUE } from '@trek/shared';
|
||||||
import { createElement, type ReactNode } from 'react';
|
import { createElement, type ReactNode } from 'react';
|
||||||
import { MemoryRouter } from 'react-router';
|
import { MemoryRouter } from 'react-router';
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { seedStore } from '../../../../tests/helpers/store';
|
||||||
import { TranslationProvider } from '../../../i18n/TranslationContext';
|
import { TranslationProvider } from '../../../i18n/TranslationContext';
|
||||||
|
import { useAddonStore } from '../../../store/addonStore';
|
||||||
import { useAssistantStore } from '../../../store/assistantStore';
|
import { useAssistantStore } from '../../../store/assistantStore';
|
||||||
|
|
||||||
const repo = vi.hoisted(() => ({
|
const repo = vi.hoisted(() => ({
|
||||||
@@ -14,6 +16,7 @@ const repo = vi.hoisted(() => ({
|
|||||||
saveAdminSettings: vi.fn(),
|
saveAdminSettings: vi.fn(),
|
||||||
adminConnection: vi.fn(),
|
adminConnection: vi.fn(),
|
||||||
saveAdminConnection: vi.fn(),
|
saveAdminConnection: vi.fn(),
|
||||||
|
setAdminModel: vi.fn(),
|
||||||
removeAdminConnection: vi.fn(),
|
removeAdminConnection: vi.fn(),
|
||||||
adminModels: vi.fn(),
|
adminModels: vi.fn(),
|
||||||
}));
|
}));
|
||||||
@@ -59,6 +62,8 @@ async function renderLoaded() {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
useAssistantStore.setState({ status: null });
|
useAssistantStore.setState({ status: null });
|
||||||
|
// The settings show while the assistant is on, and only then is its status asked for.
|
||||||
|
seedStore(useAddonStore, { loaded: true, addons: [{ id: 'ai_assistant', enabled: true }] });
|
||||||
repo.status.mockRejectedValue(new Error('not needed'));
|
repo.status.mockRejectedValue(new Error('not needed'));
|
||||||
repo.adminSettings.mockResolvedValue(SETTINGS);
|
repo.adminSettings.mockResolvedValue(SETTINGS);
|
||||||
repo.saveAdminSettings.mockImplementation(async (next: AiAdminSettings) => next);
|
repo.saveAdminSettings.mockImplementation(async (next: AiAdminSettings) => next);
|
||||||
@@ -153,6 +158,29 @@ describe('useAiAdminConfig', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("FE-HOOK-AI-ADMIN-008: a shared ChatGPT plan's model is switched on its own, and the answer shows (#2783)", async () => {
|
||||||
|
const plan = (model: string): AiAdminConnectionResponse => ({
|
||||||
|
connection: {
|
||||||
|
scope: 'instance',
|
||||||
|
kind: 'chatgpt',
|
||||||
|
model,
|
||||||
|
hint: null,
|
||||||
|
status: 'ok',
|
||||||
|
host: 'api.openai.com',
|
||||||
|
baseUrl: null,
|
||||||
|
},
|
||||||
|
prefill: null,
|
||||||
|
});
|
||||||
|
repo.adminConnection.mockResolvedValue(plan('gpt-6.1-sol'));
|
||||||
|
repo.setAdminModel.mockResolvedValue(plan('gpt-6.1-sol-mini'));
|
||||||
|
const { result } = await renderLoaded();
|
||||||
|
await act(async () => result.current.instance.setModel('gpt-6.1-sol-mini'));
|
||||||
|
await waitFor(() => expect(repo.setAdminModel).toHaveBeenCalledWith('gpt-6.1-sol-mini'));
|
||||||
|
expect(repo.saveAdminConnection).not.toHaveBeenCalled();
|
||||||
|
await waitFor(() => expect(result.current.instance.live?.model).toBe('gpt-6.1-sol-mini'));
|
||||||
|
expect(toast.success).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('FE-HOOK-AI-ADMIN-007: removing asks first, then shows the setup again; replacing opens it beside the old one', async () => {
|
it('FE-HOOK-AI-ADMIN-007: removing asks first, then shows the setup again; replacing opens it beside the old one', async () => {
|
||||||
repo.adminConnection.mockResolvedValueOnce(LIVE).mockResolvedValue(NONE);
|
repo.adminConnection.mockResolvedValueOnce(LIVE).mockResolvedValue(NONE);
|
||||||
const { result } = await renderLoaded();
|
const { result } = await renderLoaded();
|
||||||
|
|||||||
@@ -124,9 +124,16 @@ function useInstanceConnection(onChanged: () => void) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Another model on the same connection: the stored key is kept by sending the mask in its place. */
|
/**
|
||||||
|
* Another model on the same connection: the stored key is kept by sending the mask in its place.
|
||||||
|
* A shared ChatGPT plan has a sign-in, not a key, so its model is switched on its own (#2783).
|
||||||
|
*/
|
||||||
const setModel = (model: string) => {
|
const setModel = (model: string) => {
|
||||||
if (!live || live.kind === 'chatgpt') return;
|
if (!live) return;
|
||||||
|
if (live.kind === 'chatgpt') {
|
||||||
|
void act(() => aiConnectionsRepo.setAdminModel(model), 'common.saved');
|
||||||
|
return;
|
||||||
|
}
|
||||||
const request: AiInstanceConnectionRequest =
|
const request: AiInstanceConnectionRequest =
|
||||||
live.kind === 'custom'
|
live.kind === 'custom'
|
||||||
? { kind: 'custom', baseUrl: live.baseUrl ?? '', model, ...(live.hint ? { apiKey: MASKED_SETTING_VALUE } : {}) }
|
? { kind: 'custom', baseUrl: live.baseUrl ?? '', model, ...(live.hint ? { apiKey: MASKED_SETTING_VALUE } : {}) }
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import { Check, ChevronDown, SlidersHorizontal } from 'lucide-react';
|
||||||
|
import { useRef } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import { POPOVER } from '../../Packing/packingPopoverStyles';
|
||||||
|
import { fs } from '../../shared/DialogShell';
|
||||||
|
import { anchorMenu, MENU_ITEM, useFollowTrigger } from './pluginMenu';
|
||||||
|
import { sortLabel, type SortKey, type StatusFilter, type T, type TypeFilter } from './pluginModel';
|
||||||
|
|
||||||
|
const MENU_ID = 'filters';
|
||||||
|
|
||||||
|
interface Section {
|
||||||
|
title: string;
|
||||||
|
value: string;
|
||||||
|
options: Array<[string, string]>;
|
||||||
|
onPick: (v: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Type, status and order of the plugin list behind one button instead of three, so the
|
||||||
|
* toolbar stays search plus one control. The button counts the filters that narrow the
|
||||||
|
* list (the order does not narrow it) and names the order it is in.
|
||||||
|
*/
|
||||||
|
export default function PluginFilterMenu({
|
||||||
|
t,
|
||||||
|
view,
|
||||||
|
typeFilter,
|
||||||
|
setTypeFilter,
|
||||||
|
statusFilter,
|
||||||
|
setStatusFilter,
|
||||||
|
sort,
|
||||||
|
setSort,
|
||||||
|
menu,
|
||||||
|
setMenu,
|
||||||
|
}: {
|
||||||
|
t: T;
|
||||||
|
view: 'installed' | 'discover';
|
||||||
|
typeFilter: TypeFilter;
|
||||||
|
setTypeFilter: (v: TypeFilter) => void;
|
||||||
|
statusFilter: StatusFilter;
|
||||||
|
setStatusFilter: (v: StatusFilter) => void;
|
||||||
|
sort: SortKey;
|
||||||
|
setSort: (v: SortKey) => void;
|
||||||
|
menu: string | null;
|
||||||
|
setMenu: (v: string | null) => void;
|
||||||
|
}) {
|
||||||
|
const open = menu === MENU_ID;
|
||||||
|
const btnRef = useRef<HTMLButtonElement>(null);
|
||||||
|
useFollowTrigger(open);
|
||||||
|
|
||||||
|
const sections: Section[] = [
|
||||||
|
{
|
||||||
|
title: t('admin.plugins.filterType'),
|
||||||
|
value: typeFilter,
|
||||||
|
options: [
|
||||||
|
['all', t('admin.plugins.allTypes')],
|
||||||
|
['widget', t('admin.plugins.type.widget')],
|
||||||
|
['integration', t('admin.plugins.type.integration')],
|
||||||
|
['page', t('admin.plugins.type.page')],
|
||||||
|
['trip-page', t('admin.plugins.type.trip-page')],
|
||||||
|
],
|
||||||
|
onPick: (v) => setTypeFilter(v as TypeFilter),
|
||||||
|
},
|
||||||
|
...(view === 'installed'
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
title: t('admin.plugins.filterStatus'),
|
||||||
|
value: statusFilter,
|
||||||
|
options: [
|
||||||
|
['all', t('admin.plugins.allStatuses')],
|
||||||
|
['on', t('admin.plugins.status.active')],
|
||||||
|
['off', t('admin.plugins.stateOff')],
|
||||||
|
['update', t('admin.plugins.filterUpdate')],
|
||||||
|
['err', t('admin.plugins.status.error')],
|
||||||
|
] as Array<[string, string]>,
|
||||||
|
onPick: (v: string) => setStatusFilter(v as StatusFilter),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
{
|
||||||
|
title: t('admin.plugins.sortBy'),
|
||||||
|
value: sort,
|
||||||
|
options:
|
||||||
|
view === 'discover'
|
||||||
|
? [
|
||||||
|
['name', t('admin.plugins.sortName')],
|
||||||
|
['recent', t('admin.plugins.sortRecent')],
|
||||||
|
['downloads', t('admin.plugins.sortDownloads')],
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
['name', t('admin.plugins.sortName')],
|
||||||
|
['recent', t('admin.plugins.sortRecent')],
|
||||||
|
['updates', t('admin.plugins.sortUpdates')],
|
||||||
|
],
|
||||||
|
onPick: (v) => setSort(v as SortKey),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const narrowing = (typeFilter !== 'all' ? 1 : 0) + (view === 'installed' && statusFilter !== 'all' ? 1 : 0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative flex-none">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
ref={btnRef}
|
||||||
|
onClick={() => setMenu(open ? null : MENU_ID)}
|
||||||
|
aria-expanded={open}
|
||||||
|
aria-haspopup="menu"
|
||||||
|
className={`inline-flex h-9 items-center gap-2 whitespace-nowrap rounded-[10px] border bg-surface-card px-3 text-content-secondary transition-colors hover:text-content ${
|
||||||
|
narrowing ? 'border-[color:var(--text-primary)]' : 'border-edge'
|
||||||
|
}`}
|
||||||
|
style={fs(12.5, 'body')}
|
||||||
|
>
|
||||||
|
<SlidersHorizontal size={14} className="flex-none text-content-faint" />
|
||||||
|
<span className="font-semibold text-content">{t('admin.plugins.filters')}</span>
|
||||||
|
{narrowing > 0 && (
|
||||||
|
<span
|
||||||
|
className="inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-accent px-1.5 font-geist font-bold tabular-nums text-accent-text"
|
||||||
|
style={fs(10.5)}
|
||||||
|
>
|
||||||
|
{narrowing}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span className="text-content-faint">{sortLabel(sort, t)}</span>
|
||||||
|
<ChevronDown
|
||||||
|
size={13}
|
||||||
|
className={`flex-none text-content-faint transition-transform ${open ? 'rotate-180' : ''}`}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
{open &&
|
||||||
|
createPortal(
|
||||||
|
<div
|
||||||
|
role="menu"
|
||||||
|
className="w-[240px] max-w-[calc(100vw-2rem)]"
|
||||||
|
style={{ ...POPOVER, ...anchorMenu(btnRef.current) }}
|
||||||
|
>
|
||||||
|
{sections.map((s, i) => (
|
||||||
|
<div key={s.title} className={i > 0 ? 'mt-1.5 border-t border-edge-faint pt-1.5' : undefined}>
|
||||||
|
<p
|
||||||
|
className="m-0 px-2.5 pb-1 pt-1 font-geist font-bold uppercase tracking-[.08em] text-content-faint"
|
||||||
|
style={fs(10)}
|
||||||
|
>
|
||||||
|
{s.title}
|
||||||
|
</p>
|
||||||
|
{s.options.map(([v, label]) => (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitemradio"
|
||||||
|
aria-checked={s.value === v}
|
||||||
|
key={v}
|
||||||
|
onClick={() => s.onPick(v)}
|
||||||
|
className={`${MENU_ITEM} ${s.value === v ? 'font-semibold text-content' : 'text-content-secondary'}`}
|
||||||
|
style={fs(12.5, 'body')}
|
||||||
|
>
|
||||||
|
<span className="min-w-0 flex-1 truncate text-start">{label}</span>
|
||||||
|
<Check
|
||||||
|
size={14}
|
||||||
|
className={`flex-none text-content-muted ${s.value === v ? 'opacity-100' : 'opacity-0'}`}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>,
|
||||||
|
document.body
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,426 @@
|
|||||||
|
import {
|
||||||
|
AlertTriangle,
|
||||||
|
ArrowUpCircle,
|
||||||
|
Bug,
|
||||||
|
CircleDot,
|
||||||
|
Github,
|
||||||
|
Globe,
|
||||||
|
History,
|
||||||
|
Info,
|
||||||
|
KeyRound,
|
||||||
|
Link2,
|
||||||
|
MoreHorizontal,
|
||||||
|
PauseCircle,
|
||||||
|
RotateCw,
|
||||||
|
ShieldAlert,
|
||||||
|
ShieldCheck,
|
||||||
|
SlidersHorizontal,
|
||||||
|
Trash2,
|
||||||
|
UploadCloud,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { useRef, type ComponentType, type ReactNode } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import { POPOVER } from '../../Packing/packingPopoverStyles';
|
||||||
|
import ToggleSwitch from '../../Settings/ToggleSwitch';
|
||||||
|
import { fs } from '../../shared/DialogShell';
|
||||||
|
import PluginIcon from '../../shared/PluginIcon';
|
||||||
|
import { Tooltip } from '../../shared/Tooltip';
|
||||||
|
import { deriveCaps } from '../pluginCaps';
|
||||||
|
import { anchorMenu, MENU_ITEM, useFollowTrigger } from './pluginMenu';
|
||||||
|
import { deriveDeps, isRegistrySourced, parseJson, type PluginRow, type T } from './pluginModel';
|
||||||
|
|
||||||
|
// Runtime health → dot colour on the icon tile.
|
||||||
|
const HEALTH: Record<string, string> = {
|
||||||
|
active: 'bg-success',
|
||||||
|
starting: 'bg-info animate-pulse',
|
||||||
|
error: 'bg-danger',
|
||||||
|
inactive: 'bg-content-faint/60',
|
||||||
|
disabled: 'bg-warning',
|
||||||
|
incompatible: 'bg-warning',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Every fact about a plugin wears the same chip; only its icon carries a colour. */
|
||||||
|
const FACT =
|
||||||
|
'inline-flex max-w-full items-center gap-1.5 rounded-full border border-edge-faint bg-surface-secondary px-2 py-[2px] font-medium text-content-secondary';
|
||||||
|
|
||||||
|
type Tone = 'warning' | 'danger' | 'neutral';
|
||||||
|
const NOTICE_LOOK: Record<Tone, string> = {
|
||||||
|
warning: 'bg-warning-soft text-warning',
|
||||||
|
danger: 'bg-danger-soft text-danger',
|
||||||
|
neutral: 'bg-surface-secondary text-content-muted',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A state of the plugin worth reading on its own line: what it means, and the one action that fixes it. */
|
||||||
|
interface Notice {
|
||||||
|
key: string;
|
||||||
|
tone: Tone;
|
||||||
|
icon: ComponentType<{ size?: number; className?: string }>;
|
||||||
|
text: string;
|
||||||
|
action?: { label: string; onClick: () => void; disabled?: boolean };
|
||||||
|
}
|
||||||
|
|
||||||
|
function Fact({
|
||||||
|
icon,
|
||||||
|
iconClass = 'text-content-muted',
|
||||||
|
hint,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
icon: ReactNode;
|
||||||
|
iconClass?: string;
|
||||||
|
hint?: string;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
const chip = (
|
||||||
|
<span className={FACT} style={fs(11)}>
|
||||||
|
<span className={`flex flex-none ${iconClass}`}>{icon}</span>
|
||||||
|
<span className="truncate">{children}</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
return hint ? (
|
||||||
|
<Tooltip label={hint}>
|
||||||
|
<span className="inline-flex max-w-full">{chip}</span>
|
||||||
|
</Tooltip>
|
||||||
|
) : (
|
||||||
|
chip
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function NoticeLine({ n }: { n: Notice }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`flex min-w-0 items-center gap-2 rounded-[10px] px-2.5 py-1.5 ${NOTICE_LOOK[n.tone]}`}
|
||||||
|
style={fs(11.5)}
|
||||||
|
>
|
||||||
|
<n.icon size={13} className="flex-none" />
|
||||||
|
<span className="min-w-0 flex-1 truncate">{n.text}</span>
|
||||||
|
{n.action && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={n.action.onClick}
|
||||||
|
disabled={n.action.disabled}
|
||||||
|
className="flex-none font-semibold underline underline-offset-2 hover:opacity-80 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{n.action.label}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function MenuItem({
|
||||||
|
icon,
|
||||||
|
label,
|
||||||
|
onClick,
|
||||||
|
danger,
|
||||||
|
}: {
|
||||||
|
icon: ReactNode;
|
||||||
|
label: string;
|
||||||
|
onClick: () => void;
|
||||||
|
danger?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClick}
|
||||||
|
className={`${MENU_ITEM} ${danger ? 'text-danger hover:bg-danger-soft' : 'text-content-secondary'}`}
|
||||||
|
style={fs(12.5, 'body')}
|
||||||
|
>
|
||||||
|
<span className={`flex w-4 flex-none justify-center ${danger ? 'text-danger' : 'text-content-muted'}`}>
|
||||||
|
{icon}
|
||||||
|
</span>{' '}
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InstalledRowProps {
|
||||||
|
p: PluginRow;
|
||||||
|
t: T;
|
||||||
|
busy: string | null;
|
||||||
|
menu: string | null;
|
||||||
|
setMenu: (v: string | null) => void;
|
||||||
|
hasUpdate: boolean;
|
||||||
|
latestVer?: string;
|
||||||
|
newerIncompatible: { version: string; range: string } | null;
|
||||||
|
blocked: boolean;
|
||||||
|
onToggle: () => void;
|
||||||
|
onUpdate: () => void;
|
||||||
|
onRestart: () => void;
|
||||||
|
onChangeVersion: () => void;
|
||||||
|
onResume: () => void;
|
||||||
|
onReviewBlock: () => void;
|
||||||
|
onErrors: () => void;
|
||||||
|
onEgress: () => void;
|
||||||
|
onSettings: () => void;
|
||||||
|
onUninstall: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One installed plugin, read top to bottom: its name and version, what it does, the
|
||||||
|
* facts about it as one row of alike chips (what it adds, whether it was reviewed and
|
||||||
|
* signed, where it may connect), then each state that needs attention on a line of its
|
||||||
|
* own with the action that resolves it. The controls stay on the right.
|
||||||
|
*/
|
||||||
|
export default function PluginInstalledRow(props: InstalledRowProps) {
|
||||||
|
const { p, t, busy, menu, setMenu, hasUpdate, latestVer, newerIncompatible, blocked } = props;
|
||||||
|
const caps = deriveCaps(
|
||||||
|
parseJson<string[]>(p.permissions, []),
|
||||||
|
parseJson<{ widget?: { slot?: string } }>(p.capabilities, {}),
|
||||||
|
t
|
||||||
|
);
|
||||||
|
const deps = deriveDeps(p, t);
|
||||||
|
const menuOpen = menu === `row:${p.id}`;
|
||||||
|
const menuBtnRef = useRef<HTMLButtonElement>(null);
|
||||||
|
const working = busy === p.id;
|
||||||
|
const hostCount = p.egressHostCount ?? 0;
|
||||||
|
|
||||||
|
// The menu is portaled to <body> and positioned `fixed` against the ⋯ button,
|
||||||
|
// because the row's ancestor (PageSidebar) is `overflow-hidden` and would clip
|
||||||
|
// an in-flow `absolute` menu — losing Delete on the lower rows of a long list.
|
||||||
|
useFollowTrigger(menuOpen);
|
||||||
|
|
||||||
|
const notices: Notice[] = [];
|
||||||
|
if (p.status === 'error' && p.last_error) {
|
||||||
|
notices.push({ key: 'error', tone: 'danger', icon: AlertTriangle, text: p.last_error });
|
||||||
|
}
|
||||||
|
// A refused update leaves a WORKING plugin pinned at its old version: its own state,
|
||||||
|
// kept until resolved rather than dying with the toast that first reported it.
|
||||||
|
if (blocked && p.updateBlock) {
|
||||||
|
notices.push({
|
||||||
|
key: 'block',
|
||||||
|
tone: 'warning',
|
||||||
|
icon: ShieldAlert,
|
||||||
|
text: t('admin.plugins.updateBlocked', { reason: p.updateBlock.detail ?? p.updateBlock.code }),
|
||||||
|
action: { label: t('admin.plugins.reviewBlock'), onClick: props.onReviewBlock },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (const [i, d] of deps.entries()) {
|
||||||
|
if (d.blocked || d.warn) notices.push({ key: `dep${i}`, tone: 'warning', icon: d.icon, text: d.label });
|
||||||
|
}
|
||||||
|
// Held: the admin deliberately installed a non-latest version, so updates are paused
|
||||||
|
// rather than nagged — resuming is one click, right where the pause shows.
|
||||||
|
if (p.updateHold) {
|
||||||
|
notices.push({
|
||||||
|
key: 'hold',
|
||||||
|
tone: 'neutral',
|
||||||
|
icon: PauseCircle,
|
||||||
|
text: t('admin.plugins.updatesHeld', { version: p.version ?? '' }),
|
||||||
|
action: { label: t('admin.plugins.resumeUpdates'), onClick: props.onResume, disabled: working },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// A newer version this TREK can't run: informational, never a button, the fix is a TREK upgrade.
|
||||||
|
if (newerIncompatible) {
|
||||||
|
notices.push({
|
||||||
|
key: 'newer',
|
||||||
|
tone: 'neutral',
|
||||||
|
icon: Info,
|
||||||
|
text: t('admin.plugins.newerNeedsTrek', { version: newerIncompatible.version, range: newerIncompatible.range }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`group relative flex items-start gap-3 px-3.5 py-3.5 transition-colors hover:bg-surface-secondary ${working ? 'opacity-60' : ''}`}
|
||||||
|
>
|
||||||
|
<div className="relative mt-0.5 flex-none">
|
||||||
|
<span className="grid h-10 w-10 place-items-center rounded-[12px] border border-edge-faint bg-surface-secondary">
|
||||||
|
<PluginIcon name={p.icon} size={19} className="text-content-secondary" />
|
||||||
|
</span>
|
||||||
|
<Tooltip label={t(`admin.plugins.status.${p.status}` as never)}>
|
||||||
|
<span
|
||||||
|
className={`absolute -bottom-0.5 -end-0.5 h-3 w-3 rounded-full ring-2 ring-surface-card ${HEALTH[p.status] || HEALTH.inactive}`}
|
||||||
|
/>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex min-w-0 items-baseline gap-2">
|
||||||
|
<span className="min-w-0 truncate font-semibold tracking-[-.006em] text-content" style={fs(13.5, 'body')}>
|
||||||
|
{p.name}
|
||||||
|
</span>
|
||||||
|
{p.version && (
|
||||||
|
<span className="flex-none font-geist font-medium tabular-nums text-content-faint" style={fs(11)}>
|
||||||
|
v{p.version}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{p.description && (
|
||||||
|
<p className="m-0 mt-0.5 truncate text-content-muted" style={fs(12, 'body')}>
|
||||||
|
{p.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||||
|
{caps.map((c, i) => (
|
||||||
|
<Fact key={i} icon={<c.icon size={12} />} iconClass={c.net ? 'text-info' : 'text-content-muted'}>
|
||||||
|
{c.label}
|
||||||
|
</Fact>
|
||||||
|
))}
|
||||||
|
{deps
|
||||||
|
.filter((d) => !d.blocked && !d.warn)
|
||||||
|
.map((d, i) => (
|
||||||
|
<Fact key={`d${i}`} icon={<d.icon size={12} />}>
|
||||||
|
{d.label}
|
||||||
|
</Fact>
|
||||||
|
))}
|
||||||
|
{p.reviewed_at && (
|
||||||
|
<Fact icon={<ShieldCheck size={12} />} iconClass="text-success">
|
||||||
|
{t('admin.plugins.reviewed')}
|
||||||
|
</Fact>
|
||||||
|
)}
|
||||||
|
{p.source_repo === 'local:upload' && (
|
||||||
|
<Fact icon={<UploadCloud size={12} />} iconClass="text-warning" hint={t('admin.plugins.sideloadedHint')}>
|
||||||
|
{t('admin.plugins.sideloaded')}
|
||||||
|
</Fact>
|
||||||
|
)}
|
||||||
|
{p.source_repo === 'local:link' && (
|
||||||
|
<Fact icon={<Link2 size={12} />} hint={t('admin.plugins.devLinkHint')}>
|
||||||
|
{t('admin.plugins.devLinkBadge')}
|
||||||
|
</Fact>
|
||||||
|
)}
|
||||||
|
{/* Registry plugins only: a sideloaded or dev-linked plugin already says something stronger. */}
|
||||||
|
{isRegistrySourced(p.source_repo) &&
|
||||||
|
(p.signed ? (
|
||||||
|
<Fact icon={<KeyRound size={12} />} hint={t('admin.plugins.signedHint')}>
|
||||||
|
{t('admin.plugins.signed')}
|
||||||
|
</Fact>
|
||||||
|
) : (
|
||||||
|
<Fact icon={<ShieldAlert size={12} />} iconClass="text-warning" hint={t('admin.plugins.unsignedHint')}>
|
||||||
|
{t('admin.plugins.unsigned')}
|
||||||
|
</Fact>
|
||||||
|
))}
|
||||||
|
{/* A service only the operator can name (a self-hosted Gotify/ntfy): the admin adds
|
||||||
|
its host, and until one exists the plugin reaches nothing, so it asks for it. */}
|
||||||
|
{p.operatorEgress && (
|
||||||
|
<Tooltip label={t('admin.plugins.allowedHosts.hint')}>
|
||||||
|
<button type="button" onClick={props.onEgress} className={`${FACT} hover:opacity-80`} style={fs(11)}>
|
||||||
|
<Globe size={12} className={hostCount > 0 ? 'text-info' : 'text-warning'} />
|
||||||
|
{hostCount > 0
|
||||||
|
? t('admin.plugins.allowedHosts.count', { n: hostCount })
|
||||||
|
: t('admin.plugins.allowedHosts.add')}
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{notices.length > 0 && (
|
||||||
|
<div className="mt-2.5 flex flex-col gap-1.5">
|
||||||
|
{notices.map((n) => (
|
||||||
|
<NoticeLine key={n.key} n={n} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-none items-center gap-2 self-center">
|
||||||
|
{hasUpdate && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={props.onUpdate}
|
||||||
|
disabled={working}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-full bg-warning-soft px-2.5 py-1 font-semibold text-warning hover:opacity-90 disabled:opacity-50"
|
||||||
|
style={fs(11.5)}
|
||||||
|
>
|
||||||
|
<ArrowUpCircle size={13} /> <span>{t('admin.plugins.updateTo', { version: latestVer })}</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<span
|
||||||
|
className={`min-w-[42px] text-end font-medium ${p.enabled === 1 ? 'text-content-secondary' : 'text-content-faint'}`}
|
||||||
|
style={fs(12)}
|
||||||
|
>
|
||||||
|
{p.enabled === 1 ? t('admin.plugins.status.active') : t('admin.plugins.stateOff')}
|
||||||
|
</span>
|
||||||
|
<ToggleSwitch on={p.enabled === 1} label={t('admin.plugins.enabledToggle')} onToggle={props.onToggle} />
|
||||||
|
<div className="relative">
|
||||||
|
<Tooltip label={t('admin.table.actions')} disabled={menuOpen}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
ref={menuBtnRef}
|
||||||
|
data-testid={`plugin-row-menu-btn-${p.id}`}
|
||||||
|
onClick={() => setMenu(menuOpen ? null : `row:${p.id}`)}
|
||||||
|
aria-expanded={menuOpen}
|
||||||
|
aria-label={t('admin.table.actions')}
|
||||||
|
className={`grid h-8 w-8 place-items-center rounded-[10px] transition-colors ${menuOpen ? 'bg-surface-card text-content shadow-sm ring-1 ring-edge-faint' : 'text-content-faint hover:bg-surface-card hover:text-content'}`}
|
||||||
|
>
|
||||||
|
<MoreHorizontal size={17} />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
{menuOpen &&
|
||||||
|
createPortal(
|
||||||
|
<div
|
||||||
|
data-testid={`plugin-row-menu-${p.id}`}
|
||||||
|
style={{ ...POPOVER, ...anchorMenu(menuBtnRef.current) }}
|
||||||
|
className="min-w-[200px]"
|
||||||
|
>
|
||||||
|
{p.enabled === 1 && (
|
||||||
|
<MenuItem
|
||||||
|
icon={<RotateCw size={14} />}
|
||||||
|
label={t('admin.plugins.restart')}
|
||||||
|
onClick={props.onRestart}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{/* Instance fields OR actions: an action-only plugin still needs the dialog to run its buttons. */}
|
||||||
|
{((p.instanceSettingsCount ?? 0) > 0 || (p.instanceActionsCount ?? 0) > 0) && (
|
||||||
|
<MenuItem
|
||||||
|
icon={<SlidersHorizontal size={14} />}
|
||||||
|
label={t('admin.plugins.instanceSettings')}
|
||||||
|
onClick={props.onSettings}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<MenuItem icon={<Bug size={14} />} label={t('admin.plugins.viewErrors')} onClick={props.onErrors} />
|
||||||
|
{/* Only a plugin that DECLARED operatorEgress: an admin is never invited to widen egress for one that did not ask. */}
|
||||||
|
{p.operatorEgress && (
|
||||||
|
<MenuItem
|
||||||
|
icon={<Globe size={14} />}
|
||||||
|
label={t('admin.plugins.allowedHosts')}
|
||||||
|
onClick={props.onEgress}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{/* Registry plugins only — a sideload/dev-link has no registry versions to pick from. */}
|
||||||
|
{isRegistrySourced(p.source_repo) && (
|
||||||
|
<MenuItem
|
||||||
|
icon={<History size={14} />}
|
||||||
|
label={t('admin.plugins.changeVersion')}
|
||||||
|
onClick={props.onChangeVersion}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{p.source_repo && p.source_repo !== 'local:upload' && p.source_repo !== 'local:link' && (
|
||||||
|
<>
|
||||||
|
<a
|
||||||
|
href={`https://github.com/${p.source_repo}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
onClick={() => setMenu(null)}
|
||||||
|
className={`${MENU_ITEM} text-content-secondary`}
|
||||||
|
style={fs(12.5, 'body')}
|
||||||
|
>
|
||||||
|
<span className="flex w-4 flex-none justify-center text-content-muted">
|
||||||
|
<Github size={14} />
|
||||||
|
</span>{' '}
|
||||||
|
{t('admin.plugins.sourceRepo')}
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={`https://github.com/${p.source_repo}/issues`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
onClick={() => setMenu(null)}
|
||||||
|
className={`${MENU_ITEM} text-content-secondary`}
|
||||||
|
style={fs(12.5, 'body')}
|
||||||
|
>
|
||||||
|
<span className="flex w-4 flex-none justify-center text-content-muted">
|
||||||
|
<CircleDot size={14} />
|
||||||
|
</span>{' '}
|
||||||
|
{t('admin.plugins.reportIssue')}
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<div className="mx-1.5 my-1 h-px bg-edge-faint" />
|
||||||
|
<MenuItem icon={<Trash2 size={14} />} label={t('common.delete')} danger onClick={props.onUninstall} />
|
||||||
|
</div>,
|
||||||
|
document.body
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { ShieldCheck } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
DialogButton,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogShell,
|
||||||
|
DialogTile,
|
||||||
|
FooterSpacer,
|
||||||
|
NEUTRAL_TINT,
|
||||||
|
fs,
|
||||||
|
} from '../../shared/DialogShell';
|
||||||
|
import type { T } from './pluginModel';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How plugins are contained and where that ends, opened from the shield in the panel's
|
||||||
|
* header. It used to sit under the list as a card of its own, which pushed a wall of
|
||||||
|
* text into the page every admin scrolls past.
|
||||||
|
*/
|
||||||
|
export default function PluginSecurityDialog({ t, onClose }: { t: T; onClose: () => void }) {
|
||||||
|
const sections: Array<[string, string]> = [
|
||||||
|
[t('admin.plugins.security.isolationTitle'), t('admin.plugins.security.isolationBody')],
|
||||||
|
[t('admin.plugins.security.permsTitle'), t('admin.plugins.security.permsBody')],
|
||||||
|
[t('admin.plugins.security.limitsTitle'), t('admin.plugins.security.limitsBody')],
|
||||||
|
[t('admin.plugins.security.worstTitle'), t('admin.plugins.security.worstBody')],
|
||||||
|
[t('admin.plugins.security.reviewedTitle'), t('admin.plugins.security.reviewedBody')],
|
||||||
|
[t('admin.plugins.security.signedTitle'), t('admin.plugins.security.signedBody')],
|
||||||
|
[t('admin.plugins.security.trustTitle'), t('admin.plugins.security.trustBody')],
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<DialogShell
|
||||||
|
onClose={onClose}
|
||||||
|
labelledBy="plugin-security-title"
|
||||||
|
width="detail"
|
||||||
|
header={
|
||||||
|
<DialogHeader
|
||||||
|
tile={
|
||||||
|
<DialogTile>
|
||||||
|
<ShieldCheck size={20} className="text-content-secondary" />
|
||||||
|
</DialogTile>
|
||||||
|
}
|
||||||
|
tint={NEUTRAL_TINT}
|
||||||
|
labelId="plugin-security-title"
|
||||||
|
title={t('admin.plugins.security.short')}
|
||||||
|
sub={t('admin.plugins.reviewedMeaning')}
|
||||||
|
subWraps
|
||||||
|
onClose={onClose}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
footer={
|
||||||
|
<DialogFooter>
|
||||||
|
<FooterSpacer />
|
||||||
|
<DialogButton variant="primary" onClick={onClose}>
|
||||||
|
{t('common.ok')}
|
||||||
|
</DialogButton>
|
||||||
|
</DialogFooter>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="grid gap-2.5 sm:grid-cols-2">
|
||||||
|
{sections.map(([h, b]) => (
|
||||||
|
<div key={h} className="rounded-[12px] border border-edge-faint bg-surface-card px-3.5 py-3">
|
||||||
|
<h4 className="m-0 font-semibold text-content" style={fs(12.5, 'body')}>
|
||||||
|
{h}
|
||||||
|
</h4>
|
||||||
|
<p className="m-0 mt-1 leading-relaxed text-content-muted" style={fs(12, 'body')}>
|
||||||
|
{b}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</DialogShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { useEffect, useState, type CSSProperties } from 'react';
|
||||||
|
|
||||||
|
/** The tallest a row's ⋯ menu gets; below that it opens upwards instead. */
|
||||||
|
const ROW_MENU_MAX_H = 260;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a portaled menu sits: right-aligned under its trigger, or above it when the
|
||||||
|
* window has no room below. Fixed, because the cards around the toolbar and the rows
|
||||||
|
* clip whatever overflows them.
|
||||||
|
*/
|
||||||
|
export function anchorMenu(trigger: HTMLElement | null): CSSProperties {
|
||||||
|
const r = trigger?.getBoundingClientRect();
|
||||||
|
if (!r) return { position: 'fixed', top: 0, right: 0, zIndex: 100 };
|
||||||
|
const spaceBelow = window.innerHeight - r.bottom;
|
||||||
|
const openUp = spaceBelow < ROW_MENU_MAX_H && r.top > spaceBelow;
|
||||||
|
return {
|
||||||
|
position: 'fixed',
|
||||||
|
right: Math.max(8, window.innerWidth - r.right),
|
||||||
|
...(openUp ? { bottom: window.innerHeight - r.top + 4 } : { top: r.bottom + 4 }),
|
||||||
|
zIndex: 100,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One entry of a popover menu, in the packing popovers' shape. */
|
||||||
|
export const MENU_ITEM =
|
||||||
|
'flex w-full items-center gap-2.5 rounded-[9px] px-2.5 py-2 font-medium transition-colors hover:bg-surface-tertiary';
|
||||||
|
|
||||||
|
/** Re-renders while the page moves under an open, portaled menu, so it stays pinned to its trigger. */
|
||||||
|
export function useFollowTrigger(open: boolean) {
|
||||||
|
const [, reanchor] = useState(0);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const onMove = () => reanchor((n) => n + 1);
|
||||||
|
window.addEventListener('scroll', onMove, true);
|
||||||
|
window.addEventListener('resize', onMove);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('scroll', onMove, true);
|
||||||
|
window.removeEventListener('resize', onMove);
|
||||||
|
};
|
||||||
|
}, [open]);
|
||||||
|
}
|
||||||
@@ -111,8 +111,14 @@ describe('pluginModel', () => {
|
|||||||
blocked: false,
|
blocked: false,
|
||||||
version: '0.9.0',
|
version: '0.9.0',
|
||||||
});
|
});
|
||||||
expect(installOffer(incompatible, t)).toMatchObject({ blocked: true, label: 'admin.plugins.incompatible' });
|
// Nothing fits this TREK: still an Install, behind the admin's own warning for this plugin.
|
||||||
expect(installOffer(incompatible, t, true)).toMatchObject({ blocked: false, label: 'admin.plugins.installAnyway' });
|
expect(installOffer(incompatible, t)).toMatchObject({
|
||||||
|
blocked: false,
|
||||||
|
label: 'admin.plugins.install',
|
||||||
|
warn: { acceptedByAdmin: true, trekRange: '>=9', hostVersion: '4.0.0' },
|
||||||
|
});
|
||||||
|
// TREK_PLUGINS_IGNORE_TREK_RANGE lets every plugin through, so the warning is not the admin's own choice.
|
||||||
|
expect(installOffer(incompatible, t, true)).toMatchObject({ blocked: false, warn: { acceptedByAdmin: false } });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('FE-ADMIN-PLUGIN-MODEL-008: deriveDeps marks the blockers among the declared dependencies', () => {
|
it('FE-ADMIN-PLUGIN-MODEL-008: deriveDeps marks the blockers among the declared dependencies', () => {
|
||||||
|
|||||||
@@ -298,7 +298,8 @@ export function installOffer(
|
|||||||
title,
|
title,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return { blocked: true, label: t('admin.plugins.incompatible'), title };
|
// No version fits this TREK: the admin may still install this one plugin at their own risk.
|
||||||
|
return bypassOffer(item, t, title, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// FE-ADMIN-PLUGINS-HOOK-001 to -012: the plugin admin logic behind both admin shells.
|
// FE-ADMIN-PLUGINS-HOOK-001 to -014: the plugin admin logic behind both admin shells.
|
||||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||||
import type { DragEvent } from 'react';
|
import type { DragEvent } from 'react';
|
||||||
|
|
||||||
@@ -266,4 +266,36 @@ describe('usePluginsAdmin', () => {
|
|||||||
expect(toast.success).toHaveBeenCalledWith('admin.plugins.uninstalled');
|
expect(toast.success).toHaveBeenCalledWith('admin.plugins.uninstalled');
|
||||||
expect(result.current.confirmUninstall).toBeNull();
|
expect(result.current.confirmUninstall).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-ADMIN-PLUGINS-HOOK-013: switching on a plugin outside its TREK range asks first, then runs it anyway', async () => {
|
||||||
|
serve([
|
||||||
|
row({ enabled: 0, dependencyStatus: 'hostIncompatible', trekRange: '>=3.2.0 <4.0.0', hostVersion: '5.0.0' }),
|
||||||
|
]);
|
||||||
|
vi.spyOn(adminApi, 'pluginActivate').mockResolvedValue({});
|
||||||
|
const { result } = await mounted();
|
||||||
|
act(() => result.current.toggle(result.current.plugins[0] as PluginRow));
|
||||||
|
expect(adminApi.pluginActivate).not.toHaveBeenCalled();
|
||||||
|
expect(result.current.bypass.warning).toMatchObject({
|
||||||
|
acceptedByAdmin: true,
|
||||||
|
action: 'activate',
|
||||||
|
trekRange: '>=3.2.0 <4.0.0',
|
||||||
|
});
|
||||||
|
await act(async () => {
|
||||||
|
result.current.bypass.confirm();
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(adminApi.pluginActivate).toHaveBeenCalledWith('alpha', false, true));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-ADMIN-PLUGINS-HOOK-014: installing behind the admin warning sends their consent for this plugin', async () => {
|
||||||
|
serve([], [entry({ id: 'beta', name: 'Beta' })]);
|
||||||
|
vi.spyOn(adminApi, 'pluginInstall').mockResolvedValue({ id: 'beta', version: '1.0.0', trekRangeBypassed: null });
|
||||||
|
const { result } = await mounted();
|
||||||
|
const warn = { name: 'Beta', trekRange: '<5.0.0', hostVersion: '5.0.0', acceptedByAdmin: true, onConfirm: null };
|
||||||
|
act(() => result.current.install('beta', undefined, warn));
|
||||||
|
expect(adminApi.pluginInstall).not.toHaveBeenCalled();
|
||||||
|
await act(async () => {
|
||||||
|
result.current.bypass.confirm();
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(adminApi.pluginInstall).toHaveBeenCalledWith('beta', { acceptTrekRange: true }));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -317,9 +317,14 @@ export function usePluginsAdmin() {
|
|||||||
act(
|
act(
|
||||||
id,
|
id,
|
||||||
() =>
|
() =>
|
||||||
adminApi.pluginInstall(id, version ? { version } : undefined).then((r) => {
|
adminApi
|
||||||
if (!warn) bypass.notice(id, r?.trekRangeBypassed);
|
.pluginInstall(id, {
|
||||||
}),
|
...(version ? { version } : {}),
|
||||||
|
...(warn?.acceptedByAdmin ? { acceptTrekRange: true } : {}),
|
||||||
|
})
|
||||||
|
.then((r) => {
|
||||||
|
if (!warn) bypass.notice(id, r?.trekRangeBypassed);
|
||||||
|
}),
|
||||||
t('admin.plugins.installed')
|
t('admin.plugins.installed')
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -392,10 +397,10 @@ export function usePluginsAdmin() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const attemptActivate = (p: PluginRow) => {
|
const attemptActivate = (p: PluginRow, acceptTrekRange = false) => {
|
||||||
const cascaded = autoEnabledDeps(p);
|
const cascaded = autoEnabledDeps(p);
|
||||||
return adminApi
|
return adminApi
|
||||||
.pluginActivate(p.id)
|
.pluginActivate(p.id, false, acceptTrekRange)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
toast.success(t('admin.plugins.activated'));
|
toast.success(t('admin.plugins.activated'));
|
||||||
if (cascaded.length)
|
if (cascaded.length)
|
||||||
@@ -415,12 +420,29 @@ export function usePluginsAdmin() {
|
|||||||
void act(p.id, () => adminApi.pluginDeactivate(p.id), t('admin.plugins.deactivated'));
|
void act(p.id, () => adminApi.pluginDeactivate(p.id), t('admin.plugins.deactivated'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setBusy(p.id);
|
const run = (acceptTrekRange: boolean) => {
|
||||||
setMenu(null);
|
setBusy(p.id);
|
||||||
attemptActivate(p).finally(() => {
|
setMenu(null);
|
||||||
setBusy(null);
|
attemptActivate(p, acceptTrekRange).finally(() => {
|
||||||
refresh();
|
setBusy(null);
|
||||||
});
|
refresh();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
// Outside the TREK versions its author declared: the admin may run it anyway, after
|
||||||
|
// reading what that risks. The choice holds for this version of the plugin only.
|
||||||
|
if (p.dependencyStatus === 'hostIncompatible') {
|
||||||
|
const warn: RangeWarning = {
|
||||||
|
name: p.name,
|
||||||
|
trekRange: p.trekRange ?? null,
|
||||||
|
hostVersion: p.hostVersion ?? '?',
|
||||||
|
acceptedByAdmin: true,
|
||||||
|
onConfirm: null,
|
||||||
|
action: 'activate',
|
||||||
|
};
|
||||||
|
bypass.guard(warn, () => run(true));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
run(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Download a missing/outdated plugin dependency (latest compatible for its range,
|
// Download a missing/outdated plugin dependency (latest compatible for its range,
|
||||||
|
|||||||
@@ -16,15 +16,23 @@ describe('rangeBypass helpers', () => {
|
|||||||
blocked: false, warn: true, label: 'admin.plugins.dep.trekBypassed:{"range":">=3.2.0 <4.0.0","host":"4.0.0"}',
|
blocked: false, warn: true, label: 'admin.plugins.dep.trekBypassed:{"range":">=3.2.0 <4.0.0","host":"4.0.0"}',
|
||||||
})
|
})
|
||||||
expect(bypassChip({ trekRange: null, hostVersion: '4.0.0' }, t)).toMatchObject({ label: 'admin.plugins.dep.trekBypassedUnknown' })
|
expect(bypassChip({ trekRange: null, hostVersion: '4.0.0' }, t)).toMatchObject({ label: 'admin.plugins.dep.trekBypassedUnknown' })
|
||||||
|
// An admin's own "run it anyway" for this one plugin says so, not "version checks off".
|
||||||
|
expect(bypassChip({ trekRange: '>=3.2.0 <4.0.0', hostVersion: '5.0.0', acceptedByAdmin: true }, t)).toMatchObject({
|
||||||
|
warn: true, label: 'admin.plugins.dep.trekAccepted:{"range":">=3.2.0 <4.0.0","host":"5.0.0"}',
|
||||||
|
})
|
||||||
|
expect(bypassChip({ trekRange: null, hostVersion: '5.0.0', acceptedByAdmin: true }, t)).toMatchObject({
|
||||||
|
label: 'admin.plugins.dep.trekAcceptedUnknown',
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('bypassOffer: an enabled "Install anyway" carrying what the dialog must say', () => {
|
it('bypassOffer: an enabled Install that carries what the dialog must say first', () => {
|
||||||
const offer = bypassOffer({ name: 'Gotify', trek: '>=4.0.0', hostVersion: '3.3.0' }, t, 'why')
|
const offer = bypassOffer({ name: 'Gotify', trek: '>=4.0.0', hostVersion: '3.3.0' }, t, 'why')
|
||||||
expect(offer).toEqual({
|
expect(offer).toEqual({
|
||||||
blocked: false, label: 'admin.plugins.installAnyway', title: 'why',
|
blocked: false, label: 'admin.plugins.install', title: 'why',
|
||||||
warn: { name: 'Gotify', trekRange: '>=4.0.0', hostVersion: '3.3.0', onConfirm: null },
|
warn: { name: 'Gotify', trekRange: '>=4.0.0', hostVersion: '3.3.0', acceptedByAdmin: false, onConfirm: null },
|
||||||
})
|
})
|
||||||
expect(bypassOffer({ name: 'X' }, t, 'why').warn).toMatchObject({ trekRange: null, hostVersion: '?' })
|
expect(bypassOffer({ name: 'X' }, t, 'why').warn).toMatchObject({ trekRange: null, hostVersion: '?' })
|
||||||
|
expect(bypassOffer({ name: 'X' }, t, 'why', true).warn).toMatchObject({ acceptedByAdmin: true })
|
||||||
})
|
})
|
||||||
|
|
||||||
it('rangeWarningCopy: confirm vs notice title, ranged vs rangeless body', () => {
|
it('rangeWarningCopy: confirm vs notice title, ranged vs rangeless body', () => {
|
||||||
@@ -32,10 +40,25 @@ describe('rangeBypass helpers', () => {
|
|||||||
expect(rangeWarningCopy({ ...ranged, onConfirm: () => {} }, t)).toEqual({
|
expect(rangeWarningCopy({ ...ranged, onConfirm: () => {} }, t)).toEqual({
|
||||||
confirm: true, title: 'admin.plugins.rangeBypass.title',
|
confirm: true, title: 'admin.plugins.rangeBypass.title',
|
||||||
body: 'admin.plugins.rangeBypass.body:{"name":"G","range":">=4.0.0","host":"3.3.0"}',
|
body: 'admin.plugins.rangeBypass.body:{"name":"G","range":">=4.0.0","host":"3.3.0"}',
|
||||||
|
confirmLabel: 'admin.plugins.installAnyway',
|
||||||
})
|
})
|
||||||
expect(rangeWarningCopy({ name: 'G', trekRange: null, hostVersion: '3.3.0', onConfirm: null }, t)).toEqual({
|
expect(rangeWarningCopy({ name: 'G', trekRange: null, hostVersion: '3.3.0', onConfirm: null }, t)).toEqual({
|
||||||
confirm: false, title: 'admin.plugins.rangeBypass.noticeTitle',
|
confirm: false, title: 'admin.plugins.rangeBypass.noticeTitle',
|
||||||
body: 'admin.plugins.rangeBypass.bodyUnknown:{"name":"G","host":"3.3.0"}',
|
body: 'admin.plugins.rangeBypass.bodyUnknown:{"name":"G","range":null,"host":"3.3.0"}',
|
||||||
|
confirmLabel: 'admin.plugins.installAnyway',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rangeWarningCopy: an admin choosing for one plugin gets the short title, their own body and the right button', () => {
|
||||||
|
const mine = { name: 'G', trekRange: '>=4.0.0', hostVersion: '5.0.0', acceptedByAdmin: true, onConfirm: () => {} }
|
||||||
|
expect(rangeWarningCopy(mine, t)).toEqual({
|
||||||
|
confirm: true, title: 'admin.plugins.rangeBypass.titleAdmin',
|
||||||
|
body: 'admin.plugins.rangeBypass.bodyAdmin:{"name":"G","range":">=4.0.0","host":"5.0.0"}',
|
||||||
|
confirmLabel: 'admin.plugins.installAnyway',
|
||||||
|
})
|
||||||
|
expect(rangeWarningCopy({ ...mine, trekRange: null, action: 'activate' }, t)).toMatchObject({
|
||||||
|
body: 'admin.plugins.rangeBypass.bodyAdminUnknown:{"name":"G","range":null,"host":"5.0.0"}',
|
||||||
|
confirmLabel: 'admin.plugins.activateAnyway',
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -4,10 +4,21 @@ import { useTranslation } from '../../i18n'
|
|||||||
|
|
||||||
type T = (k: string, p?: Record<string, unknown>) => string
|
type T = (k: string, p?: Record<string, unknown>) => string
|
||||||
|
|
||||||
/** The server's "this only went through because TREK_PLUGINS_IGNORE_TREK_RANGE is set" marker. */
|
/**
|
||||||
export interface TrekRangeBypass { trekRange: string | null; hostVersion: string }
|
* The server's "this only went through because the version check was set aside" marker:
|
||||||
/** What the range-bypass warning needs to say, and what to do if the admin accepts (null = a notice). */
|
* by an admin for this one plugin (`acceptedByAdmin`), or for every plugin through
|
||||||
export interface RangeWarning extends TrekRangeBypass { name: string; onConfirm: (() => void) | null }
|
* TREK_PLUGINS_IGNORE_TREK_RANGE.
|
||||||
|
*/
|
||||||
|
export interface TrekRangeBypass { trekRange: string | null; hostVersion: string; acceptedByAdmin?: boolean }
|
||||||
|
/**
|
||||||
|
* What the range-bypass warning needs to say, and what to do if the admin accepts (null = a
|
||||||
|
* notice). `action` names what the confirm button does: install (the default) or activate.
|
||||||
|
*/
|
||||||
|
export interface RangeWarning extends TrekRangeBypass {
|
||||||
|
name: string
|
||||||
|
onConfirm: (() => void) | null
|
||||||
|
action?: 'install' | 'activate'
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The chip a row carries while it runs outside its declared range on the operator's
|
* The chip a row carries while it runs outside its declared range on the operator's
|
||||||
@@ -16,29 +27,42 @@ export interface RangeWarning extends TrekRangeBypass { name: string; onConfirm:
|
|||||||
*/
|
*/
|
||||||
export function bypassChip(b: TrekRangeBypass | null | undefined, t: T) {
|
export function bypassChip(b: TrekRangeBypass | null | undefined, t: T) {
|
||||||
if (!b) return null
|
if (!b) return null
|
||||||
|
const label = b.acceptedByAdmin
|
||||||
|
? b.trekRange
|
||||||
|
? t('admin.plugins.dep.trekAccepted', { range: b.trekRange, host: b.hostVersion })
|
||||||
|
: t('admin.plugins.dep.trekAcceptedUnknown')
|
||||||
|
: b.trekRange
|
||||||
|
? t('admin.plugins.dep.trekBypassed', { range: b.trekRange, host: b.hostVersion })
|
||||||
|
: t('admin.plugins.dep.trekBypassedUnknown')
|
||||||
return {
|
return {
|
||||||
icon: AlertTriangle,
|
icon: AlertTriangle,
|
||||||
label: b.trekRange
|
label,
|
||||||
? t('admin.plugins.dep.trekBypassed', { range: b.trekRange, host: b.hostVersion })
|
|
||||||
: t('admin.plugins.dep.trekBypassedUnknown'),
|
|
||||||
blocked: false,
|
blocked: false,
|
||||||
warn: true,
|
warn: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Install button for a registry entry the server flagged incompatible, once the
|
* The Install button for a registry entry the server flagged incompatible: the server will
|
||||||
* operator set TREK_PLUGINS_IGNORE_TREK_RANGE: the server will take the newest version
|
* take the newest version regardless, so the button says exactly that — and carries what
|
||||||
* regardless, so the button says exactly that — and carries what the warning has to say
|
* the warning has to say first. `byAdmin` is the admin's own "install anyway" for this one
|
||||||
* first. `title` is the shell's existing "why" line (needs TREK X — this server runs Y).
|
* plugin; without it the operator set TREK_PLUGINS_IGNORE_TREK_RANGE for every plugin.
|
||||||
|
* `title` is the shell's existing "why" line (needs TREK X — this server runs Y).
|
||||||
*/
|
*/
|
||||||
export function bypassOffer(item: { name: string; trek?: string | null; hostVersion?: string }, t: T, title: string) {
|
export function bypassOffer(
|
||||||
return {
|
item: { name: string; trek?: string | null; hostVersion?: string },
|
||||||
blocked: false,
|
t: T,
|
||||||
label: t('admin.plugins.installAnyway'),
|
title: string,
|
||||||
title,
|
byAdmin = false
|
||||||
warn: { name: item.name, trekRange: item.trek ?? null, hostVersion: item.hostVersion ?? '?', onConfirm: null } as RangeWarning,
|
) {
|
||||||
|
const warn: RangeWarning = {
|
||||||
|
name: item.name,
|
||||||
|
trekRange: item.trek ?? null,
|
||||||
|
hostVersion: item.hostVersion ?? '?',
|
||||||
|
acceptedByAdmin: byAdmin,
|
||||||
|
onConfirm: null,
|
||||||
}
|
}
|
||||||
|
return { blocked: false, label: t('admin.plugins.install'), title, warn }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -48,14 +72,29 @@ export function bypassOffer(item: { name: string; trek?: string | null; hostVers
|
|||||||
* whole point: the admin is accepting that the author never vouched for this TREK and
|
* whole point: the admin is accepting that the author never vouched for this TREK and
|
||||||
* that, in rare cases, that can cost them data.
|
* that, in rare cases, that can cost them data.
|
||||||
*/
|
*/
|
||||||
export function rangeWarningCopy(w: RangeWarning, t: T): { title: string; body: string; confirm: boolean } {
|
export function rangeWarningCopy(
|
||||||
|
w: RangeWarning,
|
||||||
|
t: T
|
||||||
|
): { title: string; body: string; confirm: boolean; confirmLabel: string } {
|
||||||
const confirm = w.onConfirm !== null
|
const confirm = w.onConfirm !== null
|
||||||
|
const vars = { name: w.name, range: w.trekRange, host: w.hostVersion }
|
||||||
|
const body = w.acceptedByAdmin
|
||||||
|
? w.trekRange
|
||||||
|
? t('admin.plugins.rangeBypass.bodyAdmin', vars)
|
||||||
|
: t('admin.plugins.rangeBypass.bodyAdminUnknown', vars)
|
||||||
|
: w.trekRange
|
||||||
|
? t('admin.plugins.rangeBypass.body', vars)
|
||||||
|
: t('admin.plugins.rangeBypass.bodyUnknown', vars)
|
||||||
|
const title = w.acceptedByAdmin
|
||||||
|
? t('admin.plugins.rangeBypass.titleAdmin')
|
||||||
|
: confirm
|
||||||
|
? t('admin.plugins.rangeBypass.title')
|
||||||
|
: t('admin.plugins.rangeBypass.noticeTitle')
|
||||||
return {
|
return {
|
||||||
confirm,
|
confirm,
|
||||||
title: confirm ? t('admin.plugins.rangeBypass.title') : t('admin.plugins.rangeBypass.noticeTitle'),
|
title,
|
||||||
body: w.trekRange
|
body,
|
||||||
? t('admin.plugins.rangeBypass.body', { name: w.name, range: w.trekRange, host: w.hostVersion })
|
confirmLabel: w.action === 'activate' ? t('admin.plugins.activateAnyway') : t('admin.plugins.installAnyway'),
|
||||||
: t('admin.plugins.rangeBypass.bodyUnknown', { name: w.name, host: w.hostVersion }),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import type { AssistantChatTrip } from './assistantViewContext';
|
|||||||
import type { EntityTarget } from './cards/cardTypes';
|
import type { EntityTarget } from './cards/cardTypes';
|
||||||
import { chatPagePath, useAssistantHome, useRouteJournalChat } from './useAssistantHome';
|
import { chatPagePath, useAssistantHome, useRouteJournalChat } from './useAssistantHome';
|
||||||
import { useAssistantHotkey } from './useAssistantHotkey';
|
import { useAssistantHotkey } from './useAssistantHotkey';
|
||||||
|
import { useAssistantStatus } from './useAssistantStatus';
|
||||||
import { useAssistantThread } from './useAssistantThread';
|
import { useAssistantThread } from './useAssistantThread';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -202,15 +203,12 @@ export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap
|
|||||||
const available = useAssistantStore((s) => s.status?.available === true);
|
const available = useAssistantStore((s) => s.status?.available === true);
|
||||||
const open = useAssistantStore((s) => s.window.open);
|
const open = useAssistantStore((s) => s.window.open);
|
||||||
const minimized = useAssistantStore((s) => s.window.minimized);
|
const minimized = useAssistantStore((s) => s.window.minimized);
|
||||||
const loadStatus = useAssistantStore((s) => s.loadStatus);
|
|
||||||
const toggle = useAssistantStore((s) => s.toggle);
|
const toggle = useAssistantStore((s) => s.toggle);
|
||||||
const [picked, setPicked] = useState<WindowTrip | null>(null);
|
const [picked, setPicked] = useState<WindowTrip | null>(null);
|
||||||
const [wasOpen, setWasOpen] = useState(open);
|
const [wasOpen, setWasOpen] = useState(open);
|
||||||
const home = useAssistantHome(setPicked);
|
const home = useAssistantHome(setPicked);
|
||||||
|
|
||||||
useEffect(() => {
|
useAssistantStatus();
|
||||||
void loadStatus();
|
|
||||||
}, [loadStatus]);
|
|
||||||
useAssistantHotkey(available, toggle);
|
useAssistantHotkey(available, toggle);
|
||||||
|
|
||||||
// A trip picked outside the planner is only for this opening; the next one opens on the home chat again.
|
// A trip picked outside the planner is only for this opening; the next one opens on the home chat again.
|
||||||
|
|||||||
@@ -440,6 +440,8 @@ export const CHANGE_LABELS: Record<AssistantChangeLabelKey, { labelKey: string }
|
|||||||
currency: { labelKey: 'assistant.change.label.currency' },
|
currency: { labelKey: 'assistant.change.label.currency' },
|
||||||
stopType: { labelKey: 'assistant.change.label.stopType' },
|
stopType: { labelKey: 'assistant.change.label.stopType' },
|
||||||
text: { labelKey: 'assistant.change.label.text' },
|
text: { labelKey: 'assistant.change.label.text' },
|
||||||
|
title: { labelKey: 'assistant.change.label.title' },
|
||||||
|
content: { labelKey: 'assistant.change.label.content' },
|
||||||
icon: { labelKey: 'assistant.change.label.icon' },
|
icon: { labelKey: 'assistant.change.label.icon' },
|
||||||
color: { labelKey: 'assistant.change.label.color' },
|
color: { labelKey: 'assistant.change.label.color' },
|
||||||
position: { labelKey: 'assistant.change.label.position' },
|
position: { labelKey: 'assistant.change.label.position' },
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
/**
|
||||||
|
* FE-AI-STATUS-001 to FE-AI-STATUS-003
|
||||||
|
*
|
||||||
|
* The views of the assistant ask for its status through this hook: not while
|
||||||
|
* both addons that open /api/ai are off, where the server answers 404, and
|
||||||
|
* as soon as one comes on, which the addon list can say after the view
|
||||||
|
* mounted (the first load, an admin's switch). The assistant's own addon
|
||||||
|
* switching asks again while AI parsing keeps /api/ai open.
|
||||||
|
*/
|
||||||
|
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||||
|
import type { AiStatusResponse } from '@trek/shared';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||||
|
import { aiConnectionsRepo } from '../../repo/aiConnectionsRepo';
|
||||||
|
import { useAddonStore } from '../../store/addonStore';
|
||||||
|
import { useAssistantStore } from '../../store/assistantStore';
|
||||||
|
import { useAssistantStatus } from './useAssistantStatus';
|
||||||
|
|
||||||
|
const INITIAL = useAssistantStore.getState();
|
||||||
|
const STATUS = { available: true, retention: { mode: 'days', days: 90 } } as AiStatusResponse;
|
||||||
|
|
||||||
|
/** The addon list as it lands from the server, with these addons on. */
|
||||||
|
const addonsOn = (...ids: string[]) =>
|
||||||
|
seedStore(useAddonStore, { loaded: true, addons: ids.map((id) => ({ id, enabled: true })) });
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
resetAllStores();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
useAssistantStore.setState(INITIAL, true);
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useAssistantStatus', () => {
|
||||||
|
it('FE-AI-STATUS-001: asks nothing before the addon list or with both addons off, and asks once one comes on', async () => {
|
||||||
|
const status = vi.spyOn(aiConnectionsRepo, 'status').mockResolvedValue(STATUS);
|
||||||
|
renderHook(() => useAssistantStatus());
|
||||||
|
act(() => addonsOn('mcp'));
|
||||||
|
expect(status).not.toHaveBeenCalled();
|
||||||
|
expect(useAssistantStore.getState().status).toBeNull();
|
||||||
|
|
||||||
|
act(() => addonsOn('ai_assistant'));
|
||||||
|
await waitFor(() => expect(useAssistantStore.getState().status).toEqual(STATUS));
|
||||||
|
expect(status).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
// The list read again with the assistant still on asks nothing more.
|
||||||
|
act(() => addonsOn('ai_assistant', 'mcp'));
|
||||||
|
expect(status).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-AI-STATUS-002: with AI parsing on it asks at once, and the last addon going off hides the assistant', async () => {
|
||||||
|
const status = vi.spyOn(aiConnectionsRepo, 'status').mockResolvedValue(STATUS);
|
||||||
|
addonsOn('llm_parsing');
|
||||||
|
renderHook(() => useAssistantStatus());
|
||||||
|
await waitFor(() => expect(useAssistantStore.getState().status).toEqual(STATUS));
|
||||||
|
expect(status).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
act(() => addonsOn());
|
||||||
|
expect(useAssistantStore.getState().status).toBeNull();
|
||||||
|
expect(status).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-AI-STATUS-003: with AI parsing on, the assistant switched on or off asks again', async () => {
|
||||||
|
const status = vi.spyOn(aiConnectionsRepo, 'status').mockResolvedValue(STATUS);
|
||||||
|
addonsOn('llm_parsing');
|
||||||
|
renderHook(() => useAssistantStatus());
|
||||||
|
await waitFor(() => expect(status).toHaveBeenCalledTimes(1));
|
||||||
|
|
||||||
|
act(() => addonsOn('llm_parsing', 'ai_assistant'));
|
||||||
|
await waitFor(() => expect(status).toHaveBeenCalledTimes(2));
|
||||||
|
|
||||||
|
act(() => addonsOn('llm_parsing'));
|
||||||
|
await waitFor(() => expect(status).toHaveBeenCalledTimes(3));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
|
||||||
|
import { useAddonStore } from '../../store/addonStore';
|
||||||
|
import { aiRoutesOpen, useAssistantStore } from '../../store/assistantStore';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asks for the assistant's status when a view of it mounts, and again when
|
||||||
|
* either addon that opens /api/ai is switched: the addon list can land after
|
||||||
|
* the view, and an admin can switch either addon while it is open. The
|
||||||
|
* assistant's own addon counts on its own, since the status says it runs only
|
||||||
|
* while that one is on, even with AI parsing keeping /api/ai open. The store
|
||||||
|
* asks the server only while one is on (aiRoutesOpen).
|
||||||
|
*/
|
||||||
|
export function useAssistantStatus(): void {
|
||||||
|
const loadStatus = useAssistantStore((s) => s.loadStatus);
|
||||||
|
const routesOpen = useAddonStore(aiRoutesOpen);
|
||||||
|
const assistantOn = useAddonStore((s) => s.isEnabled('ai_assistant'));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadStatus();
|
||||||
|
}, [routesOpen, assistantOn, loadStatus]);
|
||||||
|
}
|
||||||
@@ -25,13 +25,25 @@ interface CollabLink {
|
|||||||
pinned: boolean | number
|
pinned: boolean | number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The glyph holds the place until a favicon has really arrived: a host that never
|
||||||
|
// answers, or answers with a blank pixel, left the chip with an empty square.
|
||||||
function LinkIcon({ url }: { url: string }) {
|
function LinkIcon({ url }: { url: string }) {
|
||||||
const [failed, setFailed] = useState(false)
|
const [state, setState] = useState<'loading' | 'loaded' | 'failed'>('loading')
|
||||||
let favicon = ''
|
let favicon = ''
|
||||||
try { favicon = new URL('/favicon.ico', url).href } catch { /* not a parseable url, fall through to the glyph */ }
|
try { favicon = new URL('/favicon.ico', url).href } catch { /* not a parseable url, fall through to the glyph */ }
|
||||||
|
const loaded = state === 'loaded'
|
||||||
return (
|
return (
|
||||||
<span className="collab-link-chip__icon" aria-hidden="true">
|
<span className="collab-link-chip__icon" aria-hidden="true">
|
||||||
{!favicon || failed ? <Link2 size={13} /> : <img src={favicon} alt="" onError={() => setFailed(true)} />}
|
{!loaded && <Link2 size={13} />}
|
||||||
|
{favicon && state !== 'failed' && (
|
||||||
|
<img
|
||||||
|
src={favicon}
|
||||||
|
alt=""
|
||||||
|
hidden={!loaded}
|
||||||
|
onLoad={(e) => setState(e.currentTarget.naturalWidth > 2 ? 'loaded' : 'failed')}
|
||||||
|
onError={() => setState('failed')}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<span className="collab-link-chip__go"><ExternalLink size={13} /></span>
|
<span className="collab-link-chip__go"><ExternalLink size={13} /></span>
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -38,6 +38,20 @@ function VoterChip({ name, src, offset }: { name: string; src: string | null; of
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The voters past the third, as a count on the end of the stack; their names on hover. */
|
||||||
|
function MoreVoters({ names }: { names: string[] }) {
|
||||||
|
return (
|
||||||
|
<Tooltip label={names.map((name) => name || '?').join(', ')}>
|
||||||
|
<span
|
||||||
|
className="grid h-[18px] min-w-[18px] flex-none place-items-center rounded-full border-[1.5px] border-surface-card bg-surface-tertiary px-[3px] font-bold tabular-nums text-content-muted"
|
||||||
|
style={{ ...fs(7), marginInlineStart: -5 }}
|
||||||
|
>
|
||||||
|
+{names.length}
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** A fact about the poll on its head band, set like the type chip on a booking card. */
|
/** A fact about the poll on its head band, set like the type chip on a booking card. */
|
||||||
export function PollChip({
|
export function PollChip({
|
||||||
icon,
|
icon,
|
||||||
@@ -138,6 +152,7 @@ export function PollOptionRow({
|
|||||||
{voters.slice(0, 3).map((voter, index) => (
|
{voters.slice(0, 3).map((voter, index) => (
|
||||||
<VoterChip key={voter.key} name={voter.name} src={voter.src} offset={index > 0} />
|
<VoterChip key={voter.key} name={voter.name} src={voter.src} offset={index > 0} />
|
||||||
))}
|
))}
|
||||||
|
{voters.length > 3 && <MoreVoters names={voters.slice(3).map((voter) => voter.name)} />}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{pending && <span className="sr-only">{pending.label}</span>}
|
{pending && <span className="sr-only">{pending.label}</span>}
|
||||||
|
|||||||
@@ -191,6 +191,18 @@ describe('CollabPolls', () => {
|
|||||||
expect(await screen.findByText(/closed/i)).toBeInTheDocument();
|
expect(await screen.findByText(/closed/i)).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-COMP-POLLS-025: past three voters the stack ends in a count of the rest', async () => {
|
||||||
|
const voters = ['anna', 'ben', 'cleo', 'dana', 'emil'].map((username, i) => ({ user_id: 10 + i, username, avatar_url: null }));
|
||||||
|
server.use(
|
||||||
|
http.get('/api/trips/1/collab/polls', () =>
|
||||||
|
HttpResponse.json({ polls: [buildPoll({ is_closed: true, options: [{ id: 1, text: 'Paris', label: 'Paris', voters }, { id: 2, text: 'Rome', label: 'Rome', voters: [] }] })] }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
render(<CollabPolls {...defaultProps} />);
|
||||||
|
expect(await screen.findByText('+2')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('D')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
it('FE-COMP-POLLS-011: closed poll options are disabled (cannot vote)', async () => {
|
it('FE-COMP-POLLS-011: closed poll options are disabled (cannot vote)', async () => {
|
||||||
server.use(
|
server.use(
|
||||||
http.get('/api/trips/1/collab/polls', () =>
|
http.get('/api/trips/1/collab/polls', () =>
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { render, screen } from '../../../tests/helpers/render'
|
import { render, screen } from '../../../tests/helpers/render'
|
||||||
|
import { http, HttpResponse } from 'msw'
|
||||||
|
import { server } from '../../../tests/helpers/msw/server'
|
||||||
|
import { buildTrip } from '../../../tests/helpers/factories'
|
||||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||||
import { useTripStore } from '../../store/tripStore'
|
import { useTripStore } from '../../store/tripStore'
|
||||||
import { useSettingsStore } from '../../store/settingsStore'
|
import { useSettingsStore } from '../../store/settingsStore'
|
||||||
@@ -171,6 +174,20 @@ describe('WhatsNextWidget', () => {
|
|||||||
expect(screen.getByText('TBD')).toBeInTheDocument()
|
expect(screen.getByText('TBD')).toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('FE-COMP-WHATSNEXT-018: a hotel without a time of its own shows the check-in of the stay it begins', async () => {
|
||||||
|
server.use(http.get('/api/trips/1/accommodations', () => HttpResponse.json({
|
||||||
|
accommodations: [{ id: 7, trip_id: 1, place_id: 40, start_day_id: 1, end_day_id: 2, check_in: '15:00', check_out: '11:00' }],
|
||||||
|
})))
|
||||||
|
seedStore(useTripStore, {
|
||||||
|
trip: buildTrip({ id: 1 }),
|
||||||
|
days: [{ id: 1, trip_id: 1, date: tomorrow, title: null, day_number: 0, assignments: [], notes_items: [], notes: null }],
|
||||||
|
assignments: { '1': [makeAssignment(40, { name: 'Hotel Kea', place_time: null })] },
|
||||||
|
})
|
||||||
|
render(<WhatsNextWidget />)
|
||||||
|
expect(await screen.findByText('15:00')).toBeInTheDocument()
|
||||||
|
expect(screen.queryByText('TBD')).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
it('FE-COMP-WHATSNEXT-009: renders address when provided', () => {
|
it('FE-COMP-WHATSNEXT-009: renders address when provided', () => {
|
||||||
seedStore(useTripStore, {
|
seedStore(useTripStore, {
|
||||||
days: [{ id: 1, trip_id: 1, date: tomorrow, title: null, day_number: 0, assignments: [], notes_items: [], notes: null }],
|
days: [{ id: 1, trip_id: 1, date: tomorrow, title: null, day_number: 0, assignments: [], notes_items: [], notes: null }],
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useMemo } from 'react'
|
import React, { useEffect, useMemo } from 'react'
|
||||||
import { avatarSrc } from '../../utils/avatarSrc'
|
import { avatarSrc } from '../../utils/avatarSrc'
|
||||||
import { useTripStore } from '../../store/tripStore'
|
import { useTripStore } from '../../store/tripStore'
|
||||||
import { useSettingsStore } from '../../store/settingsStore'
|
import { useSettingsStore } from '../../store/settingsStore'
|
||||||
@@ -8,6 +8,8 @@ import { fs } from '../shared/DialogShell'
|
|||||||
import CollabPanelHead from './CollabPanelHead'
|
import CollabPanelHead from './CollabPanelHead'
|
||||||
import EmptyState from '../shared/EmptyState'
|
import EmptyState from '../shared/EmptyState'
|
||||||
import { localToday } from '../Planner/today'
|
import { localToday } from '../Planner/today'
|
||||||
|
import { useTripStays } from '../Planner/useTripStays'
|
||||||
|
import { stayStartingOn } from '../../utils/dayMerge'
|
||||||
|
|
||||||
function formatTime(timeStr, is12h) {
|
function formatTime(timeStr, is12h) {
|
||||||
if (!timeStr) return ''
|
if (!timeStr) return ''
|
||||||
@@ -48,6 +50,10 @@ export default function WhatsNextWidget({ tripMembers = [] }: WhatsNextWidgetPro
|
|||||||
const { days, assignments } = useTripStore()
|
const { days, assignments } = useTripStore()
|
||||||
const { t, locale } = useTranslation()
|
const { t, locale } = useTranslation()
|
||||||
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
|
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
|
||||||
|
// A hotel on the day its stay begins is timed by the check-in when the stop has no time of its own.
|
||||||
|
const tripId = useTripStore(s => s.trip?.id ?? 0)
|
||||||
|
const { tripAccommodations, loadAccommodations } = useTripStays(tripId)
|
||||||
|
useEffect(() => { loadAccommodations() }, [loadAccommodations])
|
||||||
|
|
||||||
const upcoming = useMemo(() => {
|
const upcoming = useMemo(() => {
|
||||||
const now = new Date()
|
const now = new Date()
|
||||||
@@ -60,14 +66,15 @@ export default function WhatsNextWidget({ tripMembers = [] }: WhatsNextWidgetPro
|
|||||||
const dayAssignments = assignments[String(day.id)] || []
|
const dayAssignments = assignments[String(day.id)] || []
|
||||||
for (const a of dayAssignments) {
|
for (const a of dayAssignments) {
|
||||||
if (!a.place) continue
|
if (!a.place) continue
|
||||||
|
const time = a.place.place_time || stayStartingOn(tripAccommodations, a.place.id, day.id)?.check_in || null
|
||||||
// Include: today (not started yet, or still running) + all future days
|
// Include: today (not started yet, or still running) + all future days
|
||||||
const isFutureDay = day.date > nowDate
|
const isFutureDay = day.date > nowDate
|
||||||
const isTodayFuture = day.date === nowDate && (!a.place.place_time || a.place.place_time >= nowTime || (!!a.place.end_time && a.place.end_time >= nowTime))
|
const isTodayFuture = day.date === nowDate && (!time || time >= nowTime || (!!a.place.end_time && a.place.end_time >= nowTime))
|
||||||
if (isFutureDay || isTodayFuture) {
|
if (isFutureDay || isTodayFuture) {
|
||||||
items.push({
|
items.push({
|
||||||
id: a.id,
|
id: a.id,
|
||||||
name: a.place.name,
|
name: a.place.name,
|
||||||
time: a.place.place_time,
|
time,
|
||||||
endTime: a.place.end_time,
|
endTime: a.place.end_time,
|
||||||
date: day.date,
|
date: day.date,
|
||||||
dayTitle: day.title,
|
dayTitle: day.title,
|
||||||
@@ -88,7 +95,7 @@ export default function WhatsNextWidget({ tripMembers = [] }: WhatsNextWidgetPro
|
|||||||
})
|
})
|
||||||
|
|
||||||
return items.slice(0, 8)
|
return items.slice(0, 8)
|
||||||
}, [days, assignments, tripMembers])
|
}, [days, assignments, tripMembers, tripAccommodations])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// FE-DOCSYNC-BIND-001 to FE-DOCSYNC-BIND-030
|
// FE-DOCSYNC-BIND-001 to FE-DOCSYNC-BIND-032
|
||||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||||
import en from '@trek/shared/i18n/en'
|
import en from '@trek/shared/i18n/en'
|
||||||
import { render, screen, fireEvent, waitFor, within } from '../../../../tests/helpers/render'
|
import { render, screen, fireEvent, waitFor, within } from '../../../../tests/helpers/render'
|
||||||
@@ -66,6 +66,7 @@ function renderCard(
|
|||||||
canManage?: boolean
|
canManage?: boolean
|
||||||
providerName?: string
|
providerName?: string
|
||||||
onReconnect?: () => void
|
onReconnect?: () => void
|
||||||
|
onEditConnection?: () => void
|
||||||
} = {},
|
} = {},
|
||||||
) {
|
) {
|
||||||
const utils = render(
|
const utils = render(
|
||||||
@@ -75,6 +76,7 @@ function renderCard(
|
|||||||
sync={makeSync(opts.sync)}
|
sync={makeSync(opts.sync)}
|
||||||
canManage={opts.canManage ?? true}
|
canManage={opts.canManage ?? true}
|
||||||
onReconnect={opts.onReconnect}
|
onReconnect={opts.onReconnect}
|
||||||
|
onEditConnection={opts.onEditConnection}
|
||||||
/>,
|
/>,
|
||||||
)
|
)
|
||||||
const header = utils.container.querySelector('header') as HTMLElement
|
const header = utils.container.querySelector('header') as HTMLElement
|
||||||
@@ -421,3 +423,31 @@ describe('DocSyncBinding: the direction lanes', () => {
|
|||||||
expect(updateLink).not.toHaveBeenCalled()
|
expect(updateLink).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('DocSyncBinding: the connection behind it', () => {
|
||||||
|
const S = en as unknown as Record<string, string>
|
||||||
|
const editButton = () => screen.queryByRole('button', { name: S['docsync.connection.edit'] })
|
||||||
|
|
||||||
|
it('FE-DOCSYNC-BIND-031: the settings open the stored connection at any time, not only after a refusal', () => {
|
||||||
|
const onEditConnection = vi.fn()
|
||||||
|
renderCard({ link: { lastSyncState: 'ok' }, onEditConnection })
|
||||||
|
|
||||||
|
expect(editButton()).not.toBeInTheDocument()
|
||||||
|
openSettings()
|
||||||
|
expect(screen.getByText(S['docsync.connection.title'])).toBeInTheDocument()
|
||||||
|
fireEvent.click(editButton() as HTMLElement)
|
||||||
|
|
||||||
|
expect(onEditConnection).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('FE-DOCSYNC-BIND-032: a member, or a panel without the form, gets no way to the connection', () => {
|
||||||
|
const member = renderCard({ canManage: false, onEditConnection: vi.fn() })
|
||||||
|
expect(screen.queryByRole('button', { name: 'Settings' })).not.toBeInTheDocument()
|
||||||
|
expect(editButton()).not.toBeInTheDocument()
|
||||||
|
member.unmount()
|
||||||
|
|
||||||
|
renderCard()
|
||||||
|
openSettings()
|
||||||
|
expect(editButton()).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import {
|
import {
|
||||||
AlertTriangle, Check, ChevronDown, Clock, Copy, FolderOpen, Link2Off, RefreshCw,
|
AlertTriangle, Check, ChevronDown, Clock, Copy, FolderOpen, KeyRound, Link2Off, RefreshCw,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import ConfirmDialog from '../../shared/ConfirmDialog'
|
import ConfirmDialog from '../../shared/ConfirmDialog'
|
||||||
import CustomSelect from '../../shared/CustomSelect'
|
import CustomSelect from '../../shared/CustomSelect'
|
||||||
import ToggleSwitch from '../../Settings/ToggleSwitch'
|
import ToggleSwitch from '../../Settings/ToggleSwitch'
|
||||||
import Tooltip from '../../shared/Tooltip'
|
import Tooltip from '../../shared/Tooltip'
|
||||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||||
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/DocumentProviderIcons'
|
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/documentProviderIconMap'
|
||||||
import DocSyncFlow, { type SyncDirection } from './DocSyncFlow'
|
import DocSyncFlow, { type SyncDirection } from './DocSyncFlow'
|
||||||
import { Badge, CONFLICT_POLICIES, conflictPolicyKey, LastRun, StateBadge } from './DocSyncBits'
|
import { Badge, CONFLICT_POLICIES, conflictPolicyKey, LastRun, StateBadge } from './DocSyncBits'
|
||||||
import { bindingNotice, needsReauth, type DocSyncLink, type useDocSync } from './useDocSync'
|
import { bindingNotice, needsReauth, type DocSyncLink, type useDocSync } from './useDocSync'
|
||||||
@@ -27,6 +27,7 @@ export default function DocSyncBinding({
|
|||||||
sync,
|
sync,
|
||||||
canManage,
|
canManage,
|
||||||
onReconnect,
|
onReconnect,
|
||||||
|
onEditConnection,
|
||||||
}: {
|
}: {
|
||||||
link: DocSyncLink
|
link: DocSyncLink
|
||||||
providerName: string
|
providerName: string
|
||||||
@@ -38,6 +39,8 @@ export default function DocSyncBinding({
|
|||||||
* not carry; left out, a refused credential is reported but not curable.
|
* not carry; left out, a refused credential is reported but not curable.
|
||||||
*/
|
*/
|
||||||
onReconnect?: () => void
|
onReconnect?: () => void
|
||||||
|
/** The same form at any time, to change the address or the login, or to remove the connection. */
|
||||||
|
onEditConnection?: () => void
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
@@ -237,6 +240,21 @@ export default function DocSyncBinding({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{onEditConnection && (
|
||||||
|
<Row label={t('docsync.connection.title')} hint={t('docsync.connection.hint')}>
|
||||||
|
<span className="flex justify-end">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onEditConnection}
|
||||||
|
className="flex items-center gap-1.5 rounded-lg border border-edge bg-surface px-2.5 py-1.5 text-caption font-medium text-content-secondary transition-colors hover:bg-surface-hover"
|
||||||
|
>
|
||||||
|
<KeyRound size={13} />
|
||||||
|
{t('docsync.connection.edit')}
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</Row>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// FE-DOCSYNC-CONNECT-001 to FE-DOCSYNC-CONNECT-027
|
// FE-DOCSYNC-CONNECT-001 to FE-DOCSYNC-CONNECT-030
|
||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
import en from '@trek/shared/i18n/en'
|
import en from '@trek/shared/i18n/en'
|
||||||
import { render, screen, fireEvent, waitFor, act, within } from '../../../../tests/helpers/render'
|
import { render, screen, fireEvent, waitFor, act, within } from '../../../../tests/helpers/render'
|
||||||
@@ -13,6 +13,7 @@ const listLinks = vi.fn(async (_tripId: number | string): Promise<unknown> => []
|
|||||||
const status = vi.fn(async (_tripId: number | string): Promise<unknown> => ({ items: {}, links: [] }))
|
const status = vi.fn(async (_tripId: number | string): Promise<unknown> => ({ items: {}, links: [] }))
|
||||||
const saveConnection = vi.fn(async (_tripId: number | string, _data: unknown): Promise<unknown> => ({ id: 1 }))
|
const saveConnection = vi.fn(async (_tripId: number | string, _data: unknown): Promise<unknown> => ({ id: 1 }))
|
||||||
const testConnection = vi.fn(async (_tripId: number | string, _data: unknown): Promise<unknown> => ({ connected: true }))
|
const testConnection = vi.fn(async (_tripId: number | string, _data: unknown): Promise<unknown> => ({ connected: true }))
|
||||||
|
const deleteConnection = vi.fn(async (_tripId: number | string, _id: number): Promise<unknown> => ({ success: true }))
|
||||||
|
|
||||||
vi.mock('../../../api/client', async (importOriginal) => {
|
vi.mock('../../../api/client', async (importOriginal) => {
|
||||||
const actual = await importOriginal<typeof import('../../../api/client')>()
|
const actual = await importOriginal<typeof import('../../../api/client')>()
|
||||||
@@ -26,6 +27,7 @@ vi.mock('../../../api/client', async (importOriginal) => {
|
|||||||
listLinks: (tripId: number | string) => listLinks(tripId),
|
listLinks: (tripId: number | string) => listLinks(tripId),
|
||||||
saveConnection: (tripId: number | string, data: unknown) => saveConnection(tripId, data),
|
saveConnection: (tripId: number | string, data: unknown) => saveConnection(tripId, data),
|
||||||
testConnection: (tripId: number | string, data: unknown) => testConnection(tripId, data),
|
testConnection: (tripId: number | string, data: unknown) => testConnection(tripId, data),
|
||||||
|
deleteConnection: (tripId: number | string, id: number) => deleteConnection(tripId, id),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -81,11 +83,13 @@ function Harness({
|
|||||||
provider,
|
provider,
|
||||||
onClose,
|
onClose,
|
||||||
onConnected,
|
onConnected,
|
||||||
|
onRemoved,
|
||||||
waitForConnection,
|
waitForConnection,
|
||||||
}: {
|
}: {
|
||||||
provider: DocSyncProvider
|
provider: DocSyncProvider
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
onConnected: (providerId: string) => void
|
onConnected: (providerId: string) => void
|
||||||
|
onRemoved?: () => void
|
||||||
/**
|
/**
|
||||||
* Hold the dialog back until the stored connection is in hand, the way the
|
* Hold the dialog back until the stored connection is in hand, the way the
|
||||||
* panel does: it only offers "connect" once it knows what is already there.
|
* panel does: it only offers "connect" once it knows what is already there.
|
||||||
@@ -94,7 +98,9 @@ function Harness({
|
|||||||
}) {
|
}) {
|
||||||
const sync = useDocSync(TRIP_ID, true)
|
const sync = useDocSync(TRIP_ID, true)
|
||||||
if (waitForConnection && !sync.connectionFor(provider.id)) return null
|
if (waitForConnection && !sync.connectionFor(provider.id)) return null
|
||||||
return <DocSyncConnectModal provider={provider} sync={sync} onClose={onClose} onConnected={onConnected} />
|
return (
|
||||||
|
<DocSyncConnectModal provider={provider} sync={sync} onClose={onClose} onConnected={onConnected} onRemoved={onRemoved} />
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Let the hook's initial load land before anything is asserted. */
|
/** Let the hook's initial load land before anything is asserted. */
|
||||||
@@ -492,3 +498,52 @@ describe('DocSyncConnectModal with a connection already stored', () => {
|
|||||||
expect(saveConnection).toHaveBeenCalledWith(TRIP_ID, expect.objectContaining({ baseUrl: 'https://cloud.example.com' }))
|
expect(saveConnection).toHaveBeenCalledWith(TRIP_ID, expect.objectContaining({ baseUrl: 'https://cloud.example.com' }))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('DocSyncConnectModal removal', () => {
|
||||||
|
const removeButton = () => screen.queryByRole('button', { name: tx('docsync.connection.remove') })
|
||||||
|
// The confirmation is portalled after the dialog, so its button is the last one of that name.
|
||||||
|
const confirmRemoval = () => {
|
||||||
|
const named = screen.getAllByRole('button', { name: tx('docsync.connection.remove') })
|
||||||
|
return named[named.length - 1]
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openWithRemoval(stored: boolean) {
|
||||||
|
if (stored) listConnections.mockResolvedValue([connection()])
|
||||||
|
const onRemoved = vi.fn()
|
||||||
|
render(<Harness provider={nextcloud} onClose={vi.fn()} onConnected={vi.fn()} onRemoved={onRemoved} waitForConnection={stored} />)
|
||||||
|
await flush()
|
||||||
|
return onRemoved
|
||||||
|
}
|
||||||
|
|
||||||
|
it('FE-DOCSYNC-CONNECT-028: a stored connection can be removed after a confirmation, and the dialog is told', async () => {
|
||||||
|
const onRemoved = await openWithRemoval(true)
|
||||||
|
await waitFor(() => expect(removeButton()).toBeInTheDocument())
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: tx('docsync.connection.remove') }))
|
||||||
|
expect(deleteConnection).not.toHaveBeenCalled()
|
||||||
|
await screen.findByText(tx('docsync.connection.confirmRemove'))
|
||||||
|
fireEvent.click(confirmRemoval())
|
||||||
|
|
||||||
|
await waitFor(() => expect(deleteConnection).toHaveBeenCalledWith(TRIP_ID, 9))
|
||||||
|
await waitFor(() => expect(onRemoved).toHaveBeenCalled())
|
||||||
|
})
|
||||||
|
|
||||||
|
it('FE-DOCSYNC-CONNECT-029: a refused removal keeps the dialog and says why', async () => {
|
||||||
|
deleteConnection.mockRejectedValueOnce({ response: { status: 403, data: { error: 'forbidden' } } })
|
||||||
|
const onRemoved = await openWithRemoval(true)
|
||||||
|
await waitFor(() => expect(removeButton()).toBeInTheDocument())
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: tx('docsync.connection.remove') }))
|
||||||
|
await screen.findByText(tx('docsync.connection.confirmRemove'))
|
||||||
|
fireEvent.click(confirmRemoval())
|
||||||
|
|
||||||
|
await waitFor(() => expect(deleteConnection).toHaveBeenCalled())
|
||||||
|
expect(onRemoved).not.toHaveBeenCalled()
|
||||||
|
expect(await screen.findByText(tx('docsync.error.forbidden'))).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('FE-DOCSYNC-CONNECT-030: a first connection has nothing to remove', async () => {
|
||||||
|
await openWithRemoval(false)
|
||||||
|
expect(removeButton()).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { useId, useState } from 'react'
|
import { useId, useState } from 'react'
|
||||||
import { AlertTriangle, Check, Loader2, Plug, ShieldAlert } from 'lucide-react'
|
import { AlertTriangle, Check, Loader2, Plug, ShieldAlert } from 'lucide-react'
|
||||||
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT } from '../../shared/DialogShell'
|
import { DeleteButton, DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT } from '../../shared/DialogShell'
|
||||||
|
import ConfirmDialog from '../../shared/ConfirmDialog'
|
||||||
import { Tooltip } from '../../shared/Tooltip'
|
import { Tooltip } from '../../shared/Tooltip'
|
||||||
import ToggleSwitch from '../../Settings/ToggleSwitch'
|
import ToggleSwitch from '../../Settings/ToggleSwitch'
|
||||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||||
import { useConnectForm } from './useConnectForm'
|
import { useConnectForm } from './useConnectForm'
|
||||||
import { Badge } from './DocSyncBits'
|
import { Badge } from './DocSyncBits'
|
||||||
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/DocumentProviderIcons'
|
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/documentProviderIconMap'
|
||||||
import type { DocSyncProvider, DocSyncVerdict, useDocSync } from './useDocSync'
|
import type { DocSyncProvider, DocSyncVerdict, useDocSync } from './useDocSync'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -22,11 +23,14 @@ export default function DocSyncConnectModal({
|
|||||||
sync,
|
sync,
|
||||||
onClose,
|
onClose,
|
||||||
onConnected,
|
onConnected,
|
||||||
|
onRemoved,
|
||||||
}: {
|
}: {
|
||||||
provider: DocSyncProvider
|
provider: DocSyncProvider
|
||||||
sync: ReturnType<typeof useDocSync>
|
sync: ReturnType<typeof useDocSync>
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
onConnected: (providerId: string) => void
|
onConnected: (providerId: string) => void
|
||||||
|
/** After the stored connection was removed from here; left out, the form offers no removal. */
|
||||||
|
onRemoved?: () => void
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const existing = sync.connectionFor(provider.id)
|
const existing = sync.connectionFor(provider.id)
|
||||||
@@ -34,6 +38,11 @@ export default function DocSyncConnectModal({
|
|||||||
|
|
||||||
const form = useConnectForm(provider, existing, sync)
|
const form = useConnectForm(provider, existing, sync)
|
||||||
const [verdict, setVerdict] = useState<DocSyncVerdict | null>(null)
|
const [verdict, setVerdict] = useState<DocSyncVerdict | null>(null)
|
||||||
|
const [confirmRemove, setConfirmRemove] = useState(false)
|
||||||
|
|
||||||
|
const remove = async () => {
|
||||||
|
if (existing && (await sync.removeConnection(existing.id))) onRemoved?.()
|
||||||
|
}
|
||||||
|
|
||||||
const test = async () => setVerdict(await form.probe())
|
const test = async () => setVerdict(await form.probe())
|
||||||
const labelId = useId()
|
const labelId = useId()
|
||||||
@@ -46,6 +55,7 @@ export default function DocSyncConnectModal({
|
|||||||
<DialogShell
|
<DialogShell
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
labelledBy={labelId}
|
labelledBy={labelId}
|
||||||
|
blocked={confirmRemove}
|
||||||
header={(
|
header={(
|
||||||
<DialogHeader
|
<DialogHeader
|
||||||
tile={<DialogTile>{Icon ? <Icon className="h-5 w-5 text-content" /> : <Plug size={20} strokeWidth={1.9} className="text-content-muted" />}</DialogTile>}
|
tile={<DialogTile>{Icon ? <Icon className="h-5 w-5 text-content" /> : <Plug size={20} strokeWidth={1.9} className="text-content-muted" />}</DialogTile>}
|
||||||
@@ -57,6 +67,13 @@ export default function DocSyncConnectModal({
|
|||||||
)}
|
)}
|
||||||
footer={(
|
footer={(
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
|
{existing && onRemoved && (
|
||||||
|
<DeleteButton
|
||||||
|
label={t('docsync.connection.remove')}
|
||||||
|
onClick={() => setConfirmRemove(true)}
|
||||||
|
disabled={sync.busy === 'connection'}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<Verdict verdict={verdict} busy={sync.busy === 'test'} failure={sync.error} />
|
<Verdict verdict={verdict} busy={sync.busy === 'test'} failure={sync.error} />
|
||||||
<FooterSpacer />
|
<FooterSpacer />
|
||||||
<DialogButton onClick={() => void test()} disabled={!form.complete || sync.busy === 'test'}>
|
<DialogButton onClick={() => void test()} disabled={!form.complete || sync.busy === 'test'}>
|
||||||
@@ -101,6 +118,15 @@ export default function DocSyncConnectModal({
|
|||||||
</span>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
isOpen={confirmRemove}
|
||||||
|
onClose={() => setConfirmRemove(false)}
|
||||||
|
onConfirm={() => void remove()}
|
||||||
|
title={t('docsync.connection.remove')}
|
||||||
|
message={t('docsync.connection.confirmRemove')}
|
||||||
|
confirmLabel={t('docsync.connection.remove')}
|
||||||
|
/>
|
||||||
</DialogShell>
|
</DialogShell>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { ArrowLeft, ArrowRight } from 'lucide-react'
|
import { ArrowLeft, ArrowRight } from 'lucide-react'
|
||||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||||
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/DocumentProviderIcons'
|
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/documentProviderIconMap'
|
||||||
import TrekIcon from '../../shared/TrekIcon'
|
import TrekIcon from '../../shared/TrekIcon'
|
||||||
import { Badge } from './DocSyncBits'
|
import { Badge } from './DocSyncBits'
|
||||||
import { toggledDirection, type SyncDirection } from './docSyncModel'
|
import { toggledDirection, type SyncDirection } from './docSyncModel'
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useEffect, useId, useMemo, useState } from 'react'
|
|||||||
import { AlertCircle, ArrowRight, Check, FolderSync, Loader2, Plus } from 'lucide-react'
|
import { AlertCircle, ArrowRight, Check, FolderSync, Loader2, Plus } from 'lucide-react'
|
||||||
import { DialogHeader, DialogShell, DialogTile, NEUTRAL_TINT } from '../../shared/DialogShell'
|
import { DialogHeader, DialogShell, DialogTile, NEUTRAL_TINT } from '../../shared/DialogShell'
|
||||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||||
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/DocumentProviderIcons'
|
import { DOCUMENT_PROVIDER_ICONS } from '../../shared/documentProviderIconMap'
|
||||||
import { StateBadge } from './DocSyncBits'
|
import { StateBadge } from './DocSyncBits'
|
||||||
import { slugFor } from './docSyncModel'
|
import { slugFor } from './docSyncModel'
|
||||||
import { useConflicts } from './useConflicts'
|
import { useConflicts } from './useConflicts'
|
||||||
@@ -62,6 +62,9 @@ export default function DocSyncPanel({
|
|||||||
setSelected(prev => (sync.links.some(l => l.id === prev) ? prev : (sync.links[0]?.id ?? null)))
|
setSelected(prev => (sync.links.some(l => l.id === prev) ? prev : (sync.links[0]?.id ?? null)))
|
||||||
}, [sync.links])
|
}, [sync.links])
|
||||||
|
|
||||||
|
// The connection behind the folder picker, which the picker can send back to.
|
||||||
|
const scopeProvider = scopeFor ? sync.providers.find(p => p.id === scopeFor) : undefined
|
||||||
|
|
||||||
const attention = ATTENTION_STATES.reduce((n, k) => n + (sync.itemCounts[k] ?? 0), 0)
|
const attention = ATTENTION_STATES.reduce((n, k) => n + (sync.itemCounts[k] ?? 0), 0)
|
||||||
const labelId = useId()
|
const labelId = useId()
|
||||||
|
|
||||||
@@ -113,6 +116,7 @@ export default function DocSyncPanel({
|
|||||||
sync={sync}
|
sync={sync}
|
||||||
canManage={canManage}
|
canManage={canManage}
|
||||||
onReconnect={activeProvider ? () => setReconnecting(activeProvider) : undefined}
|
onReconnect={activeProvider ? () => setReconnecting(activeProvider) : undefined}
|
||||||
|
onEditConnection={canManage && activeProvider ? () => setReconnecting(activeProvider) : undefined}
|
||||||
/>
|
/>
|
||||||
{/* Every action in this column reports here: a refused run, a
|
{/* Every action in this column reports here: a refused run, a
|
||||||
switch that flipped back, a conflict the server would not
|
switch that flipped back, a conflict the server would not
|
||||||
@@ -141,6 +145,7 @@ export default function DocSyncPanel({
|
|||||||
sync={sync}
|
sync={sync}
|
||||||
onClose={() => setConnecting(null)}
|
onClose={() => setConnecting(null)}
|
||||||
onConnected={id => { setConnecting(null); setScopeFor(id) }}
|
onConnected={id => { setConnecting(null); setScopeFor(id) }}
|
||||||
|
onRemoved={() => setConnecting(null)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -149,6 +154,7 @@ export default function DocSyncPanel({
|
|||||||
provider={reconnecting}
|
provider={reconnecting}
|
||||||
sync={sync}
|
sync={sync}
|
||||||
onClose={() => setReconnecting(null)}
|
onClose={() => setReconnecting(null)}
|
||||||
|
onRemoved={() => setReconnecting(null)}
|
||||||
onConnected={id => {
|
onConnected={id => {
|
||||||
setReconnecting(null)
|
setReconnecting(null)
|
||||||
// Run straight away, as binding does: the card still reports the
|
// Run straight away, as binding does: the card still reports the
|
||||||
@@ -168,6 +174,7 @@ export default function DocSyncPanel({
|
|||||||
sync={sync}
|
sync={sync}
|
||||||
onClose={() => setScopeFor(null)}
|
onClose={() => setScopeFor(null)}
|
||||||
onBound={() => setScopeFor(null)}
|
onBound={() => setScopeFor(null)}
|
||||||
|
onEditConnection={scopeProvider ? () => { setScopeFor(null); setConnecting(scopeProvider) } : undefined}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// FE-DOCSYNC-SCOPE-001 to FE-DOCSYNC-SCOPE-023
|
// FE-DOCSYNC-SCOPE-001 to FE-DOCSYNC-SCOPE-024
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The folder picker of the document-sync dialog.
|
* The folder picker of the document-sync dialog.
|
||||||
@@ -84,9 +84,10 @@ function deferred<T>() {
|
|||||||
return { promise, resolve, reject }
|
return { promise, resolve, reject }
|
||||||
}
|
}
|
||||||
|
|
||||||
function Harness({ suggestedName = 'trek-paris-42', providerName = 'Paperless' }: {
|
function Harness({ suggestedName = 'trek-paris-42', providerName = 'Paperless', onEditConnection }: {
|
||||||
suggestedName?: string
|
suggestedName?: string
|
||||||
providerName?: string
|
providerName?: string
|
||||||
|
onEditConnection?: () => void
|
||||||
}) {
|
}) {
|
||||||
const sync = useDocSync(TRIP_ID, false)
|
const sync = useDocSync(TRIP_ID, false)
|
||||||
return (
|
return (
|
||||||
@@ -97,6 +98,7 @@ function Harness({ suggestedName = 'trek-paris-42', providerName = 'Paperless' }
|
|||||||
sync={sync}
|
sync={sync}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
onBound={onBound}
|
onBound={onBound}
|
||||||
|
onEditConnection={onEditConnection}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -381,3 +383,20 @@ describe('DocSyncScopeModal errors', () => {
|
|||||||
expect(createButton()).toBeEnabled()
|
expect(createButton()).toBeEnabled()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('DocSyncScopeModal connection', () => {
|
||||||
|
it('FE-DOCSYNC-SCOPE-024: leads back to the stored connection before a folder is chosen', async () => {
|
||||||
|
const editButton = () => screen.queryByRole('button', { name: S['docsync.connection.edit'] })
|
||||||
|
const onEditConnection = vi.fn()
|
||||||
|
const first = render(<Harness onEditConnection={onEditConnection} />)
|
||||||
|
await waitFor(() => expect(listScopes).toHaveBeenCalled())
|
||||||
|
|
||||||
|
fireEvent.click(editButton() as HTMLElement)
|
||||||
|
expect(onEditConnection).toHaveBeenCalledTimes(1)
|
||||||
|
expect(createLink).not.toHaveBeenCalled()
|
||||||
|
first.unmount()
|
||||||
|
|
||||||
|
render(<Harness />)
|
||||||
|
expect(editButton()).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useId, useMemo, useState } from 'react'
|
import { useId, useMemo, useState } from 'react'
|
||||||
import { FolderPlus, Loader2, Search } from 'lucide-react'
|
import { FolderPlus, KeyRound, Loader2, Search } from 'lucide-react'
|
||||||
import { DialogHeader, DialogShell, DialogTile, NEUTRAL_TINT } from '../../shared/DialogShell'
|
import { DialogHeader, DialogShell, DialogTile, NEUTRAL_TINT } from '../../shared/DialogShell'
|
||||||
import { useTranslation } from '../../../i18n/TranslationContext'
|
import { useTranslation } from '../../../i18n/TranslationContext'
|
||||||
import type { DocSyncConnection, useDocSync } from './useDocSync'
|
import type { DocSyncConnection, useDocSync } from './useDocSync'
|
||||||
@@ -22,6 +22,7 @@ export default function DocSyncScopeModal({
|
|||||||
sync,
|
sync,
|
||||||
onClose,
|
onClose,
|
||||||
onBound,
|
onBound,
|
||||||
|
onEditConnection,
|
||||||
}: {
|
}: {
|
||||||
connection: DocSyncConnection
|
connection: DocSyncConnection
|
||||||
providerName: string
|
providerName: string
|
||||||
@@ -30,6 +31,8 @@ export default function DocSyncScopeModal({
|
|||||||
sync: ReturnType<typeof useDocSync>
|
sync: ReturnType<typeof useDocSync>
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
onBound: () => void
|
onBound: () => void
|
||||||
|
/** Back to the stored connection, to change the login or remove it before choosing a folder. */
|
||||||
|
onEditConnection?: () => void
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const labelId = useId()
|
const labelId = useId()
|
||||||
@@ -63,7 +66,19 @@ export default function DocSyncScopeModal({
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<p className="text-caption text-content-muted">{t('docsync.scope.intro')}</p>
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<p className="text-caption text-content-muted">{t('docsync.scope.intro')}</p>
|
||||||
|
{onEditConnection && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onEditConnection}
|
||||||
|
className="flex shrink-0 items-center gap-1.5 rounded-lg border border-edge px-2.5 py-1 text-caption font-medium text-content-secondary transition-colors hover:bg-surface-hover"
|
||||||
|
>
|
||||||
|
<KeyRound size={13} />
|
||||||
|
{t('docsync.connection.edit')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="rounded-xl border border-edge bg-surface-secondary p-3">
|
<div className="rounded-xl border border-edge bg-surface-secondary p-3">
|
||||||
<span className="mb-2 block text-body font-medium text-content">{t('docsync.scope.createTitle')}</span>
|
<span className="mb-2 block text-body font-medium text-content">{t('docsync.scope.createTitle')}</span>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// FE-DOCSYNC-HOOK-001 to FE-DOCSYNC-HOOK-030
|
// FE-DOCSYNC-HOOK-001 to FE-DOCSYNC-HOOK-032
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The document-sync hook.
|
* The document-sync hook.
|
||||||
@@ -22,6 +22,7 @@ const testConnectionApi = vi.fn(async (_tripId: number | string, _data: unknown)
|
|||||||
const updateLinkApi = vi.fn(async (_tripId: number | string, _linkId: number, _patch: unknown): Promise<unknown> => ({}))
|
const updateLinkApi = vi.fn(async (_tripId: number | string, _linkId: number, _patch: unknown): Promise<unknown> => ({}))
|
||||||
const syncNowApi = vi.fn(async (_tripId: number | string, _linkId: number, _full: boolean): Promise<unknown> => ({}))
|
const syncNowApi = vi.fn(async (_tripId: number | string, _linkId: number, _full: boolean): Promise<unknown> => ({}))
|
||||||
const listScopesApi = vi.fn(async (_tripId: number | string, _connectionId: number, _q?: string): Promise<unknown> => ({ scopes: [] }))
|
const listScopesApi = vi.fn(async (_tripId: number | string, _connectionId: number, _q?: string): Promise<unknown> => ({ scopes: [] }))
|
||||||
|
const deleteConnectionApi = vi.fn(async (_tripId: number | string, _id: number): Promise<unknown> => ({ success: true }))
|
||||||
const resolveApi = vi.fn(async (_tripId: number | string, _itemId: number, _keep: string): Promise<unknown> => ({ success: true }))
|
const resolveApi = vi.fn(async (_tripId: number | string, _itemId: number, _keep: string): Promise<unknown> => ({ success: true }))
|
||||||
|
|
||||||
vi.mock('../../../api/client', async (importOriginal) => {
|
vi.mock('../../../api/client', async (importOriginal) => {
|
||||||
@@ -40,6 +41,7 @@ vi.mock('../../../api/client', async (importOriginal) => {
|
|||||||
syncNow: (tripId: number | string, linkId: number, full: boolean) => syncNowApi(tripId, linkId, full),
|
syncNow: (tripId: number | string, linkId: number, full: boolean) => syncNowApi(tripId, linkId, full),
|
||||||
listScopes: (tripId: number | string, connectionId: number, q?: string) => listScopesApi(tripId, connectionId, q),
|
listScopes: (tripId: number | string, connectionId: number, q?: string) => listScopesApi(tripId, connectionId, q),
|
||||||
resolve: (tripId: number | string, itemId: number, keep: string) => resolveApi(tripId, itemId, keep),
|
resolve: (tripId: number | string, itemId: number, keep: string) => resolveApi(tripId, itemId, keep),
|
||||||
|
deleteConnection: (tripId: number | string, id: number) => deleteConnectionApi(tripId, id),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -126,6 +128,7 @@ beforeEach(() => {
|
|||||||
syncNowApi.mockResolvedValue({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 })
|
syncNowApi.mockResolvedValue({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 })
|
||||||
listScopesApi.mockResolvedValue({ scopes: [] })
|
listScopesApi.mockResolvedValue({ scopes: [] })
|
||||||
resolveApi.mockResolvedValue({ success: true })
|
resolveApi.mockResolvedValue({ success: true })
|
||||||
|
deleteConnectionApi.mockResolvedValue({ success: true })
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('useDocSync initial load', () => {
|
describe('useDocSync initial load', () => {
|
||||||
@@ -471,6 +474,38 @@ describe('useDocSync resolveConflict', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('useDocSync removeConnection', () => {
|
||||||
|
it('FE-DOCSYNC-HOOK-031: forgets the connection and reloads, so its bindings leave the screen too', async () => {
|
||||||
|
const { result } = await mountLoaded()
|
||||||
|
expect(result.current.links).toHaveLength(1)
|
||||||
|
// The server drops the bindings with the connection (ON DELETE CASCADE).
|
||||||
|
listConnectionsApi.mockResolvedValue([])
|
||||||
|
listLinksApi.mockResolvedValue([])
|
||||||
|
|
||||||
|
let ok: boolean | undefined
|
||||||
|
await act(async () => { ok = await result.current.removeConnection(9) })
|
||||||
|
|
||||||
|
expect(ok).toBe(true)
|
||||||
|
expect(deleteConnectionApi).toHaveBeenCalledWith(TRIP, 9)
|
||||||
|
expect(result.current.connectionFor('nextcloud')).toBeNull()
|
||||||
|
expect(result.current.links).toEqual([])
|
||||||
|
expect(result.current.busy).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('FE-DOCSYNC-HOOK-032: a refused removal keeps everything and says why', async () => {
|
||||||
|
deleteConnectionApi.mockRejectedValueOnce({ response: { status: 403, data: { error: 'forbidden' } } })
|
||||||
|
const { result } = await mountLoaded()
|
||||||
|
|
||||||
|
let ok: boolean | undefined
|
||||||
|
await act(async () => { ok = await result.current.removeConnection(9) })
|
||||||
|
|
||||||
|
expect(ok).toBe(false)
|
||||||
|
expect(result.current.error).toBe('forbidden')
|
||||||
|
expect(result.current.connectionFor('nextcloud')).not.toBeNull()
|
||||||
|
expect(result.current.busy).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('needsReauth', () => {
|
describe('needsReauth', () => {
|
||||||
it('FE-DOCSYNC-HOOK-030: reads a refused credential off either the state or the error code', () => {
|
it('FE-DOCSYNC-HOOK-030: reads a refused credential off either the state or the error code', () => {
|
||||||
expect(needsReauth({ lastSyncState: 'needs_reauth', lastSyncError: null })).toBe(true)
|
expect(needsReauth({ lastSyncState: 'needs_reauth', lastSyncError: null })).toBe(true)
|
||||||
|
|||||||
@@ -264,6 +264,27 @@ export function useDocSync(tripId: number | string, enabled: boolean) {
|
|||||||
}
|
}
|
||||||
}, [tripId, load])
|
}, [tripId, load])
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forget a stored connection, and with it every binding of this trip that
|
||||||
|
* runs through it. The documents stay on both sides; what goes is the
|
||||||
|
* address and the login TREK kept for the store, which is the one thing a
|
||||||
|
* person changing accounts or folders had no way to take back.
|
||||||
|
*/
|
||||||
|
const removeConnection = useCallback(async (connectionId: number) => {
|
||||||
|
setBusy('connection')
|
||||||
|
setError(null)
|
||||||
|
try {
|
||||||
|
await docsyncApi.deleteConnection(tripId, connectionId)
|
||||||
|
await load()
|
||||||
|
return true
|
||||||
|
} catch (e: unknown) {
|
||||||
|
setError(readError(e))
|
||||||
|
return false
|
||||||
|
} finally {
|
||||||
|
setBusy(null)
|
||||||
|
}
|
||||||
|
}, [tripId, load])
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Probe without saving. Always resolves to a verdict object: the route
|
* Probe without saving. Always resolves to a verdict object: the route
|
||||||
* answers 200 even for an unreachable instance, because a form showing a typo
|
* answers 200 even for an unreachable instance, because a form showing a typo
|
||||||
@@ -427,7 +448,7 @@ export function useDocSync(tripId: number | string, enabled: boolean) {
|
|||||||
connections, links, itemCounts,
|
connections, links, itemCounts,
|
||||||
loading, busy, error,
|
loading, busy, error,
|
||||||
connectionFor, load,
|
connectionFor, load,
|
||||||
saveConnection, testConnection,
|
saveConnection, testConnection, removeConnection,
|
||||||
loadScopes, createScope,
|
loadScopes, createScope,
|
||||||
createLink, updateLink, removeLink, syncNow, resolveConflict,
|
createLink, updateLink, removeLink, syncNow, resolveConflict,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// FE-COMP-JOURNEYDATEPICKER-001 to FE-COMP-JOURNEYDATEPICKER-007
|
// FE-COMP-JOURNEYDATEPICKER-001 to FE-COMP-JOURNEYDATEPICKER-008
|
||||||
import React from 'react'
|
import React from 'react'
|
||||||
import { describe, it, expect, vi } from 'vitest'
|
import { describe, it, expect, vi } from 'vitest'
|
||||||
import { render, screen } from '../../../tests/helpers/render'
|
import { render, screen } from '../../../tests/helpers/render'
|
||||||
@@ -119,3 +119,28 @@ describe('DatePicker week start (#2029)', () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('DatePicker inside a clipping dialog (#2858)', () => {
|
||||||
|
it('FE-COMP-JOURNEYDATEPICKER-008: the calendar floats over the page, stays inside the viewport and closes on a click away', async () => {
|
||||||
|
const user = userEvent.setup()
|
||||||
|
const { container } = render(
|
||||||
|
<div style={{ overflow: 'hidden' }}>
|
||||||
|
<DatePicker value="2026-03-15" onChange={vi.fn()} />
|
||||||
|
</div>,
|
||||||
|
)
|
||||||
|
const trigger = screen.getByText(/Mar 15, 2026/).closest('button') as HTMLButtonElement
|
||||||
|
// A trigger at the right edge, where the end date of a range sits.
|
||||||
|
trigger.getBoundingClientRect = () => ({ top: 100, bottom: 136, left: window.innerWidth - 120, right: window.innerWidth - 8, width: 112, height: 36, x: 0, y: 0, toJSON: () => ({}) })
|
||||||
|
await user.click(trigger)
|
||||||
|
|
||||||
|
const day31 = screen.getByRole('button', { name: '31' })
|
||||||
|
// Rendered outside the dialog that would clip it.
|
||||||
|
expect(container.contains(day31)).toBe(false)
|
||||||
|
const panel = day31.closest('.fixed') as HTMLElement
|
||||||
|
expect(panel.style.top).toBe('140px')
|
||||||
|
expect(parseFloat(panel.style.left)).toBe(window.innerWidth - 280 - 8)
|
||||||
|
|
||||||
|
await user.click(document.querySelector('[role="presentation"]') as HTMLElement)
|
||||||
|
expect(screen.queryByRole('button', { name: '31' })).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { useState } from 'react'
|
import { useRef, useState } from 'react'
|
||||||
|
import { createPortal } from 'react-dom'
|
||||||
import { localIsoDate } from '../../utils/localDate'
|
import { localIsoDate } from '../../utils/localDate'
|
||||||
import { ArrowLeft, ChevronRight, Calendar } from 'lucide-react'
|
import { ArrowLeft, ChevronRight, Calendar } from 'lucide-react'
|
||||||
import { useTranslation } from '../../i18n'
|
import { useTranslation } from '../../i18n'
|
||||||
import { useWeekStartDay } from '../../hooks/useWeekStartDay'
|
import { useWeekStartDay } from '../../hooks/useWeekStartDay'
|
||||||
import { leadingBlanks, weekdayLabels } from '../../utils/calendarWeek'
|
import { leadingBlanks, weekdayLabels } from '../../utils/calendarWeek'
|
||||||
|
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The header steps up a level on each click, days → months → years, and a
|
* The header steps up a level on each click, days → months → years, and a
|
||||||
@@ -14,6 +16,9 @@ import { leadingBlanks, weekdayLabels } from '../../utils/calendarWeek'
|
|||||||
*/
|
*/
|
||||||
type CalendarView = 'days' | 'months' | 'years'
|
type CalendarView = 'days' | 'months' | 'years'
|
||||||
const YEAR_PAGE_SIZE = 12
|
const YEAR_PAGE_SIZE = 12
|
||||||
|
/** The calendar's width; `w-[280px]` below. */
|
||||||
|
const PANEL_WIDTH = 280
|
||||||
|
const VIEWPORT_PAD = 8
|
||||||
|
|
||||||
export function DatePicker({ value, onChange, tripDates }: {
|
export function DatePicker({ value, onChange, tripDates }: {
|
||||||
value: string
|
value: string
|
||||||
@@ -23,6 +28,13 @@ export function DatePicker({ value, onChange, tripDates }: {
|
|||||||
const { t, locale } = useTranslation()
|
const { t, locale } = useTranslation()
|
||||||
const weekStart = useWeekStartDay()
|
const weekStart = useWeekStartDay()
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
|
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||||
|
// The calendar used to hang absolutely under its trigger, inside dialogs that clip
|
||||||
|
// their content: the photo picker cut off the last week and, for the end date in
|
||||||
|
// the right-hand column, the last weekday (#2858). It now floats over the page,
|
||||||
|
// pinned to the trigger, flipped above it when below is too short and kept inside
|
||||||
|
// the viewport sideways.
|
||||||
|
const anchored = useAnchoredPosition(triggerRef, open, { estimatedHeight: 340, matchWidth: false })
|
||||||
const [view, setView] = useState<CalendarView>('days')
|
const [view, setView] = useState<CalendarView>('days')
|
||||||
const [yearPageStart, setYearPageStart] = useState(0)
|
const [yearPageStart, setYearPageStart] = useState(0)
|
||||||
const [viewMonth, setViewMonth] = useState(() => {
|
const [viewMonth, setViewMonth] = useState(() => {
|
||||||
@@ -107,6 +119,7 @@ export function DatePicker({ value, onChange, tripDates }: {
|
|||||||
return (
|
return (
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<button
|
<button
|
||||||
|
ref={triggerRef}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={toggleOpen}
|
onClick={toggleOpen}
|
||||||
className="w-full px-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg text-[13px] bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white text-start flex items-center justify-between"
|
className="w-full px-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg text-[13px] bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white text-start flex items-center justify-between"
|
||||||
@@ -122,12 +135,20 @@ export function DatePicker({ value, onChange, tripDates }: {
|
|||||||
<Calendar size={13} className="text-zinc-400" />
|
<Calendar size={13} className="text-zinc-400" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{open && (
|
{open && anchored && createPortal(
|
||||||
<>
|
<>
|
||||||
{/* Click-away catcher — no semantics of its own; the trigger button
|
{/* Click-away catcher — no semantics of its own; the trigger button
|
||||||
above closes the popover again from the keyboard. */}
|
above closes the popover again from the keyboard. */}
|
||||||
<div role="presentation" className="fixed inset-0 z-[10]" onClick={() => setOpen(false)} />
|
<div role="presentation" className="fixed inset-0 z-[var(--z-toast)]" onClick={() => setOpen(false)} />
|
||||||
<div className="absolute top-full start-0 mt-1 z-[20] bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-xl shadow-lg p-3 w-[280px]">
|
<div
|
||||||
|
className="fixed z-[var(--z-toast)] overflow-y-auto bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-xl shadow-lg p-3 w-[280px]"
|
||||||
|
style={{
|
||||||
|
top: anchored.top,
|
||||||
|
bottom: anchored.bottom,
|
||||||
|
left: Math.max(VIEWPORT_PAD, Math.min(anchored.left, window.innerWidth - PANEL_WIDTH - VIEWPORT_PAD)),
|
||||||
|
maxHeight: anchored.maxHeight,
|
||||||
|
}}
|
||||||
|
>
|
||||||
{/* Header: arrows step the current view, the label climbs to the next one up */}
|
{/* Header: arrows step the current view, the label climbs to the next one up */}
|
||||||
<div className="flex items-center justify-between mb-2">
|
<div className="flex items-center justify-between mb-2">
|
||||||
<button type="button" onClick={handlePrev} aria-label={prevLabel} className={navButton}>
|
<button type="button" onClick={handlePrev} aria-label={prevLabel} className={navButton}>
|
||||||
@@ -200,7 +221,7 @@ export function DatePicker({ value, onChange, tripDates }: {
|
|||||||
>
|
>
|
||||||
{day}
|
{day}
|
||||||
{isTrip && !isSelected && (
|
{isTrip && !isSelected && (
|
||||||
<span className="absolute bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-indigo-500" />
|
<span className="absolute bottom-1 inset-x-0 mx-auto w-1 h-1 rounded-full bg-indigo-500" />
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
@@ -209,7 +230,8 @@ export function DatePicker({ value, onChange, tripDates }: {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>,
|
||||||
|
document.body,
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -375,11 +375,12 @@ describe('ProviderPicker', () => {
|
|||||||
await user.click(screen.getByRole('button', { name: 'Search' }))
|
await user.click(screen.getByRole('button', { name: 'Search' }))
|
||||||
expect(ranges).toHaveLength(0)
|
expect(ranges).toHaveLength(0)
|
||||||
|
|
||||||
|
// The calendar opens in a portal, so its days are looked up on the page, not under the trigger.
|
||||||
const [fromPicker, toPicker] = Array.from(baseElement.querySelectorAll('.flex-1 > .relative')) as HTMLElement[]
|
const [fromPicker, toPicker] = Array.from(baseElement.querySelectorAll('.flex-1 > .relative')) as HTMLElement[]
|
||||||
await user.click(within(fromPicker).getByRole('button'))
|
await user.click(within(fromPicker).getByRole('button'))
|
||||||
await user.click(within(fromPicker).getByRole('button', { name: '3' }))
|
await user.click(screen.getByRole('button', { name: '3' }))
|
||||||
await user.click(within(toPicker).getByRole('button'))
|
await user.click(within(toPicker).getByRole('button'))
|
||||||
await user.click(within(toPicker).getByRole('button', { name: '9' }))
|
await user.click(screen.getByRole('button', { name: '9' }))
|
||||||
await user.click(screen.getByRole('button', { name: 'Search' }))
|
await user.click(screen.getByRole('button', { name: 'Search' }))
|
||||||
|
|
||||||
await waitFor(() => expect(ranges).toHaveLength(1))
|
await waitFor(() => expect(ranges).toHaveLength(1))
|
||||||
|
|||||||
@@ -50,16 +50,10 @@ import { pluginsApi, type PluginMapMarker, type PluginMapLayer } from '../../api
|
|||||||
import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'
|
import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'
|
||||||
import { alongShortestArc, computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport'
|
import { alongShortestArc, computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport'
|
||||||
import { selectedPlaceTarget } from './selectedPlaceTarget'
|
import { selectedPlaceTarget } from './selectedPlaceTarget'
|
||||||
import { PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID } from './placeClusterLayers'
|
import {
|
||||||
|
PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID, PLACE_CLUSTER_SOURCE_ID,
|
||||||
// Marker grouping for the GL map (#1385): MapLibre/Mapbox can't show the rich
|
addPlaceClusterLayers, drawClusterBubbles, expandCluster,
|
||||||
// HTML photo markers *and* cluster them natively, so we feed the place points
|
} from './placeClusterLayers'
|
||||||
// into a clustered GeoJSON source. The cluster bubbles render as GL circles +
|
|
||||||
// a count label; the individual rich HTML markers are then only drawn for the
|
|
||||||
// points the source reports as currently unclustered. Grouping is always on,
|
|
||||||
// matching the Leaflet map's MarkerClusterGroup.
|
|
||||||
const PLACE_CLUSTER_SOURCE_ID = 'trip-place-clusters'
|
|
||||||
const PLACE_UNCLUSTERED_LAYER_ID = 'trip-place-unclustered-hit'
|
|
||||||
|
|
||||||
type PlaceWithCoords = Place & { lat: number; lng: number }
|
type PlaceWithCoords = Place & { lat: number; lng: number }
|
||||||
|
|
||||||
@@ -112,72 +106,6 @@ interface Props extends MapViewProps {
|
|||||||
gl: any
|
gl: any
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* How eagerly place markers merge into a cluster.
|
|
||||||
*
|
|
||||||
* The overview band the Leaflet map clusters in as well (`CLUSTER_UNTIL_ZOOM` there),
|
|
||||||
* kept as plain numbers rather than shared constants so the GL bundle does not have to
|
|
||||||
* carry Leaflet for them. Above the cutoff supercluster hands every point back on its
|
|
||||||
* own, and the stops that share a coordinate are folded together at the pin level
|
|
||||||
* instead — see the reconcile below.
|
|
||||||
*/
|
|
||||||
const CLUSTER_RADIUS = 20
|
|
||||||
const CLUSTER_MAX_ZOOM = 8
|
|
||||||
|
|
||||||
/** The cluster source and the three layers over it. Extracted so the rebuild on a mode
|
|
||||||
* change and the initial build cannot drift apart. */
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
function addPlaceClusterLayers(map: any): void {
|
|
||||||
map.addSource(PLACE_CLUSTER_SOURCE_ID, {
|
|
||||||
type: 'geojson',
|
|
||||||
data: { type: 'FeatureCollection', features: [] },
|
|
||||||
cluster: true,
|
|
||||||
clusterRadius: CLUSTER_RADIUS,
|
|
||||||
clusterMaxZoom: CLUSTER_MAX_ZOOM,
|
|
||||||
})
|
|
||||||
map.addLayer({
|
|
||||||
id: PLACE_CLUSTER_CIRCLE_LAYER_ID,
|
|
||||||
type: 'circle',
|
|
||||||
source: PLACE_CLUSTER_SOURCE_ID,
|
|
||||||
filter: ['has', 'point_count'],
|
|
||||||
paint: {
|
|
||||||
'circle-color': '#111827',
|
|
||||||
'circle-opacity': 0.97,
|
|
||||||
'circle-radius': ['step', ['get', 'point_count'], 18, 10, 21, 50, 24],
|
|
||||||
'circle-stroke-width': 2.5,
|
|
||||||
'circle-stroke-color': 'rgba(255,255,255,0.9)',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
map.addLayer({
|
|
||||||
id: PLACE_CLUSTER_COUNT_LAYER_ID,
|
|
||||||
type: 'symbol',
|
|
||||||
source: PLACE_CLUSTER_SOURCE_ID,
|
|
||||||
filter: ['has', 'point_count'],
|
|
||||||
layout: {
|
|
||||||
'text-field': ['get', 'point_count_abbreviated'],
|
|
||||||
'text-size': 12,
|
|
||||||
'text-allow-overlap': true,
|
|
||||||
},
|
|
||||||
paint: {
|
|
||||||
'text-color': '#ffffff',
|
|
||||||
'text-halo-color': 'rgba(17,24,39,0.35)',
|
|
||||||
'text-halo-width': 1,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
map.addLayer({
|
|
||||||
id: PLACE_UNCLUSTERED_LAYER_ID,
|
|
||||||
type: 'circle',
|
|
||||||
source: PLACE_CLUSTER_SOURCE_ID,
|
|
||||||
filter: ['!', ['has', 'point_count']],
|
|
||||||
paint: {
|
|
||||||
'circle-radius': 24,
|
|
||||||
'circle-opacity': 0,
|
|
||||||
'circle-stroke-opacity': 0,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function createMarkerElement(place: Place & PlaceMarkerFlags & { category_color?: string; category_icon?: string }, photoUrl: string | null, orderNumbers: number[] | null, selected: boolean): HTMLDivElement {
|
function createMarkerElement(place: Place & PlaceMarkerFlags & { category_color?: string; category_icon?: string }, photoUrl: string | null, orderNumbers: number[] | null, selected: boolean): HTMLDivElement {
|
||||||
// A stop that interrupts the drive gets its own small disc, decided before the photo
|
// A stop that interrupts the drive gets its own small disc, decided before the photo
|
||||||
// branch: the brand logo a fuel search comes back with is exactly what this replaces.
|
// branch: the brand logo a fuel search comes back with is exactly what this replaces.
|
||||||
@@ -612,6 +540,8 @@ export function MapViewGL({
|
|||||||
useDawarichTrailGL(mapRef.current, mapReady, dawarichTrack, dawarichSelectedDate, 'trip-route-casing', dawarichHiddenDates)
|
useDawarichTrailGL(mapRef.current, mapReady, dawarichTrack, dawarichSelectedDate, 'trip-route-casing', dawarichHiddenDates)
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const markersRef = useRef<Map<number, PlacePin>>(new Map())
|
const markersRef = useRef<Map<number, PlacePin>>(new Map())
|
||||||
|
/** The count bubbles, one per cluster the source currently reports. */
|
||||||
|
const clusterPinsRef = useRef<PlacePin[]>([])
|
||||||
// Own layer for the hand-positioned place pins (MapLibre path, see makePlacePin).
|
// Own layer for the hand-positioned place pins (MapLibre path, see makePlacePin).
|
||||||
const pinLayerRef = useRef<HTMLDivElement | null>(null)
|
const pinLayerRef = useRef<HTMLDivElement | null>(null)
|
||||||
const locationMarkerRef = useRef<LocationMarkerHandle | null>(null)
|
const locationMarkerRef = useRef<LocationMarkerHandle | null>(null)
|
||||||
@@ -642,6 +572,7 @@ export function MapViewGL({
|
|||||||
// in the same frame the canvas draws, or the ones left out swim against the ones in.
|
// in the same frame the canvas draws, or the ones left out swim against the ones in.
|
||||||
const repositionPins = useCallback(() => {
|
const repositionPins = useCallback(() => {
|
||||||
markersRef.current.forEach(pin => pin.reposition())
|
markersRef.current.forEach(pin => pin.reposition())
|
||||||
|
clusterPinsRef.current.forEach(pin => pin.reposition())
|
||||||
poiMarkersRef.current.forEach(pin => pin.reposition())
|
poiMarkersRef.current.forEach(pin => pin.reposition())
|
||||||
pluginMarkersRef.current.forEach(pin => pin.reposition())
|
pluginMarkersRef.current.forEach(pin => pin.reposition())
|
||||||
routeViaMarkersRef.current.forEach(pin => pin.reposition())
|
routeViaMarkersRef.current.forEach(pin => pin.reposition())
|
||||||
@@ -1304,21 +1235,7 @@ export function MapViewGL({
|
|||||||
? map.queryRenderedFeatures(e.point, { layers: [PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID] })
|
? map.queryRenderedFeatures(e.point, { layers: [PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID] })
|
||||||
: []
|
: []
|
||||||
const feature = features?.[0]
|
const feature = features?.[0]
|
||||||
const clusterId = feature?.properties?.cluster_id
|
expandCluster(map, feature?.properties?.cluster_id, feature?.geometry?.coordinates)
|
||||||
const coordinates = feature?.geometry?.coordinates
|
|
||||||
if (clusterId == null || !Array.isArray(coordinates)) return
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const source = map.getSource(PLACE_CLUSTER_SOURCE_ID) as any
|
|
||||||
const easeToZoom = (nextZoom: number) => {
|
|
||||||
try { map.easeTo({ center: coordinates, zoom: nextZoom, duration: 350 }) } catch { /* noop */ }
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const maybeZoom = source?.getClusterExpansionZoom?.(clusterId, (err: Error | null, nextZoom: number) => {
|
|
||||||
if (!err && typeof nextZoom === 'number') easeToZoom(nextZoom)
|
|
||||||
})
|
|
||||||
if (typeof maybeZoom === 'number') easeToZoom(maybeZoom)
|
|
||||||
else if (maybeZoom && typeof maybeZoom.then === 'function') maybeZoom.then(easeToZoom).catch(() => {})
|
|
||||||
} catch { /* noop */ }
|
|
||||||
}
|
}
|
||||||
const setClusterCursor = () => {
|
const setClusterCursor = () => {
|
||||||
const canvas = typeof map.getCanvas === 'function' ? map.getCanvas() : null
|
const canvas = typeof map.getCanvas === 'function' ? map.getCanvas() : null
|
||||||
@@ -1704,8 +1621,17 @@ export function MapViewGL({
|
|||||||
source.setData(buildPlaceClusterData(places) as any)
|
source.setData(buildPlaceClusterData(places) as any)
|
||||||
const placesById = new Map<number, PlaceWithCoords>(validPlaces.map(place => [place.id, place]))
|
const placesById = new Map<number, PlaceWithCoords>(validPlaces.map(place => [place.id, place]))
|
||||||
let raf: number | null = null
|
let raf: number | null = null
|
||||||
|
const dropClusterPins = () => {
|
||||||
|
clusterPinsRef.current.forEach(pin => pin.remove())
|
||||||
|
clusterPinsRef.current = []
|
||||||
|
}
|
||||||
|
const reconcileClusterPins = () => {
|
||||||
|
dropClusterPins()
|
||||||
|
clusterPinsRef.current = drawClusterBubbles(map, (el, lng, lat) => attachPin(map, gl, pinLayerRef.current, el, lng, lat))
|
||||||
|
}
|
||||||
const runReconcile = () => {
|
const runReconcile = () => {
|
||||||
raf = null
|
raf = null
|
||||||
|
reconcileClusterPins()
|
||||||
const features = map.querySourceFeatures(PLACE_CLUSTER_SOURCE_ID, { filter: ['!', ['has', 'point_count']] }) || []
|
const features = map.querySourceFeatures(PLACE_CLUSTER_SOURCE_ID, { filter: ['!', ['has', 'point_count']] }) || []
|
||||||
const seen = new Set<number>()
|
const seen = new Set<number>()
|
||||||
const visiblePlaces: PlaceWithCoords[] = []
|
const visiblePlaces: PlaceWithCoords[] = []
|
||||||
@@ -1752,6 +1678,7 @@ export function MapViewGL({
|
|||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
if (raf !== null) cancelAnimationFrame(raf)
|
if (raf !== null) cancelAnimationFrame(raf)
|
||||||
|
dropClusterPins()
|
||||||
map.off('moveend', scheduleReconcile)
|
map.off('moveend', scheduleReconcile)
|
||||||
map.off('zoomend', scheduleReconcile)
|
map.off('zoomend', scheduleReconcile)
|
||||||
map.off('idle', scheduleReconcile)
|
map.off('idle', scheduleReconcile)
|
||||||
|
|||||||
@@ -426,6 +426,23 @@ describe('calculateRouteWithLegs', () => {
|
|||||||
expect(second).toBe(first)
|
expect(second).toBe(first)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('FE-COMP-ROUTECALCULATOR-035b: a route answered once is still there after a reload, without asking the router (#2794)', async () => {
|
||||||
|
let hits = 0
|
||||||
|
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => { hits++; return HttpResponse.json(buildLegsResponse()) }))
|
||||||
|
const wps = freshWaypoints()
|
||||||
|
const first = await calculateRouteWithLegs(wps)
|
||||||
|
const { offlineDb } = await import('../../db/offlineDb')
|
||||||
|
await vi.waitFor(async () => expect(await offlineDb.routeCache.count()).toBeGreaterThan(0))
|
||||||
|
|
||||||
|
// A reload: the module, and with it the cache in memory, starts over.
|
||||||
|
vi.resetModules()
|
||||||
|
const reloaded = await import('./RouteCalculator')
|
||||||
|
const again = await reloaded.calculateRouteWithLegs(wps)
|
||||||
|
|
||||||
|
expect(hits).toBe(1)
|
||||||
|
expect(again).toEqual(first)
|
||||||
|
})
|
||||||
|
|
||||||
it('FE-COMP-ROUTECALCULATOR-036: switching the distance unit re-fetches instead of reusing stale text (#1300)', async () => {
|
it('FE-COMP-ROUTECALCULATOR-036: switching the distance unit re-fetches instead of reusing stale text (#1300)', async () => {
|
||||||
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json(buildLegsResponse())))
|
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json(buildLegsResponse())))
|
||||||
const wps = freshWaypoints()
|
const wps = freshWaypoints()
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import type { DistanceUnit, RouteResult, RouteSegment, RouteWithLegs, SnappedWay
|
|||||||
import { haversineKm } from '../../utils/geo'
|
import { haversineKm } from '../../utils/geo'
|
||||||
import { formatDistance } from '../../utils/units'
|
import { formatDistance } from '../../utils/units'
|
||||||
import { countRoute } from './routeUsageCounter'
|
import { countRoute } from './routeUsageCounter'
|
||||||
|
import { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore'
|
||||||
import { valhallaRouteAvoiding, valhallaRun, valhallaAvailable, valhallaAlternates, valhallaSpacing, legAvoids, type AvoidClass, type ValhallaLeg } from './valhallaRoute'
|
import { valhallaRouteAvoiding, valhallaRun, valhallaAvailable, valhallaAlternates, valhallaSpacing, legAvoids, type AvoidClass, type ValhallaLeg } from './valhallaRoute'
|
||||||
import { furthestFrom, sameRoad, type RouteUsageSurface } from '@trek/shared'
|
import { furthestFrom, sameRoad, type RouteUsageSurface } from '@trek/shared'
|
||||||
|
|
||||||
@@ -196,10 +197,6 @@ function retryAfterMs(response: Response): number | null {
|
|||||||
return Number.isNaN(at) ? null : Math.max(0, at - Date.now())
|
return Number.isNaN(at) ? null : Math.max(0, at - Date.now())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cache route responses keyed by the exact waypoint list. Routes are stable, so
|
|
||||||
// this avoids re-hitting the public OSRM demo server on every day switch / reorder.
|
|
||||||
const routeCache = new Map<string, RouteWithLegs>()
|
|
||||||
const ROUTE_CACHE_MAX = 200
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A route profile is either one of the built-in OSRM profiles or a plugin profile
|
* A route profile is either one of the built-in OSRM profiles or a plugin profile
|
||||||
@@ -540,7 +537,10 @@ export async function calculateRouteWithLegs(
|
|||||||
const avoidScope = avoiding.length ? `:avoid=${avoiding.join(',')}` : ''
|
const avoidScope = avoiding.length ? `:avoid=${avoiding.join(',')}` : ''
|
||||||
const plainKey = `${profile}:${getDistanceUnit()}:${coords}${pluginScope}`
|
const plainKey = `${profile}:${getDistanceUnit()}:${coords}${pluginScope}`
|
||||||
const cacheKey = `${plainKey}${avoidScope}`
|
const cacheKey = `${plainKey}${avoidScope}`
|
||||||
const cached = routeCache.get(cacheKey)
|
// A plugin route stays in memory: its answer depends on the trip and the day,
|
||||||
|
// and may carry live data such as charging stops. The rest is kept on the device
|
||||||
|
// too, so a trip that shows its whole route opens drawn (#2794).
|
||||||
|
const cached = pluginScope ? routeInMemory(cacheKey) : await storedRoute(cacheKey)
|
||||||
if (cached) return cached
|
if (cached) return cached
|
||||||
|
|
||||||
if (avoiding.length) {
|
if (avoiding.length) {
|
||||||
@@ -552,7 +552,7 @@ export async function calculateRouteWithLegs(
|
|||||||
// Null is a Valhalla that could not answer at all. OSRM keeps the day drawn rather
|
// Null is a Valhalla that could not answer at all. OSRM keeps the day drawn rather
|
||||||
// than blank, and the answer says that nothing was avoided, with the reason, so the
|
// than blank, and the answer says that nothing was avoided, with the reason, so the
|
||||||
// rail flags the day instead of implying the setting held on a road nobody weighed.
|
// rail flags the day instead of implying the setting held on a road nobody weighed.
|
||||||
const plain = routeCache.get(plainKey) ?? await osrmWithLegs(waypoints, coords, profile, signal)
|
const plain = (await storedRoute(plainKey)) ?? await osrmWithLegs(waypoints, coords, profile, signal)
|
||||||
cacheRoute(plainKey, plain)
|
cacheRoute(plainKey, plain)
|
||||||
return { ...plain, avoidance: { asked: avoiding, achieved: [], fellBack: true } }
|
return { ...plain, avoidance: { asked: avoiding, achieved: [], fellBack: true } }
|
||||||
}
|
}
|
||||||
@@ -591,11 +591,7 @@ export async function calculateRouteWithLegs(
|
|||||||
legs,
|
legs,
|
||||||
...(route.viaPoints.length ? { vias: route.viaPoints } : {}),
|
...(route.viaPoints.length ? { vias: route.viaPoints } : {}),
|
||||||
}
|
}
|
||||||
routeCache.set(cacheKey, result)
|
rememberRoute(cacheKey, result)
|
||||||
if (routeCache.size > ROUTE_CACHE_MAX) {
|
|
||||||
const oldest = routeCache.keys().next().value
|
|
||||||
if (oldest !== undefined) routeCache.delete(oldest)
|
|
||||||
}
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -638,15 +634,6 @@ async function osrmWithLegs(
|
|||||||
return { coordinates, distance: route.distance, duration: route.duration, legs, ...(snapped ? { snapped } : {}) }
|
return { coordinates, distance: route.distance, duration: route.duration, legs, ...(snapped ? { snapped } : {}) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Store a route and drop the oldest once the cache is over its cap. */
|
|
||||||
function cacheRoute(key: string, route: RouteWithLegs): void {
|
|
||||||
routeCache.set(key, route)
|
|
||||||
if (routeCache.size > ROUTE_CACHE_MAX) {
|
|
||||||
const oldest = routeCache.keys().next().value
|
|
||||||
if (oldest !== undefined) routeCache.delete(oldest)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A whole chain from the second engine, weighted away from some road classes.
|
* A whole chain from the second engine, weighted away from some road classes.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import L from 'leaflet'
|
import L from 'leaflet'
|
||||||
import { STACK_RADIUS_PX } from './coincidentPlaces'
|
import { STACK_RADIUS_PX } from './coincidentPlaces'
|
||||||
|
import { clusterBubbleSize } from './placeClusterLayers'
|
||||||
|
|
||||||
/** Up to here the map is an overview, where stops merge to keep the world readable. */
|
/** Up to here the map is an overview, where stops merge to keep the world readable. */
|
||||||
export const CLUSTER_UNTIL_ZOOM = 9
|
export const CLUSTER_UNTIL_ZOOM = 9
|
||||||
@@ -66,7 +67,7 @@ export interface ClusterLike {
|
|||||||
/** A count bubble sized by its count, styled by `.marker-cluster-custom` in index.css. */
|
/** A count bubble sized by its count, styled by `.marker-cluster-custom` in index.css. */
|
||||||
export function createClusterIcon(cluster: ClusterLike) {
|
export function createClusterIcon(cluster: ClusterLike) {
|
||||||
const count = cluster.getChildCount()
|
const count = cluster.getChildCount()
|
||||||
const size = count < 10 ? 36 : count < 50 ? 42 : 48
|
const size = clusterBubbleSize(count)
|
||||||
return L.divIcon({
|
return L.divIcon({
|
||||||
html: `<div class="marker-cluster-custom" style="width:${size}px;height:${size}px;"><span>${count}</span></div>`,
|
html: `<div class="marker-cluster-custom" style="width:${size}px;height:${size}px;"><span>${count}</span></div>`,
|
||||||
className: 'marker-cluster-wrapper',
|
className: 'marker-cluster-wrapper',
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import {
|
||||||
|
type ClusterMap,
|
||||||
|
PLACE_CLUSTER_SOURCE_ID,
|
||||||
|
addPlaceClusterLayers,
|
||||||
|
clusterBubbleSize,
|
||||||
|
createClusterBubble,
|
||||||
|
drawClusterBubbles,
|
||||||
|
} from './placeClusterLayers';
|
||||||
|
|
||||||
|
function fakeMap(features: unknown[], expansionZoom: unknown = 11) {
|
||||||
|
const source = { getClusterExpansionZoom: vi.fn(() => expansionZoom) };
|
||||||
|
const map = {
|
||||||
|
addSource: vi.fn(),
|
||||||
|
addLayer: vi.fn(),
|
||||||
|
getSource: vi.fn((id: string) => (id === PLACE_CLUSTER_SOURCE_ID ? source : undefined)),
|
||||||
|
easeTo: vi.fn(),
|
||||||
|
querySourceFeatures: vi.fn((_id: string, query: { filter: unknown[] }) =>
|
||||||
|
query.filter[0] === 'has' ? features : []
|
||||||
|
),
|
||||||
|
};
|
||||||
|
return { map: map as unknown as ClusterMap & typeof map, source };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('cluster bubbles', () => {
|
||||||
|
it('FE-COMP-PLACECLUSTER-001: a bubble grows in three steps with its count', () => {
|
||||||
|
expect([1, 9, 10, 49, 50, 500].map(clusterBubbleSize)).toEqual([36, 36, 42, 42, 48, 48]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-COMP-PLACECLUSTER-002: the GL bubble is the Leaflet markup inside a bare wrapper the pin can move', () => {
|
||||||
|
const wrapper = createClusterBubble(38);
|
||||||
|
expect(wrapper.className).toBe('');
|
||||||
|
const bubble = wrapper.firstElementChild as HTMLElement;
|
||||||
|
expect(bubble.className).toBe('marker-cluster-custom');
|
||||||
|
expect(bubble.style.width).toBe('42px');
|
||||||
|
expect(bubble.style.height).toBe('42px');
|
||||||
|
expect(bubble.textContent).toBe('38');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-COMP-PLACECLUSTER-003: the canvas circle and count stay as an invisible hit area', () => {
|
||||||
|
const { map } = fakeMap([]);
|
||||||
|
addPlaceClusterLayers(map);
|
||||||
|
expect(map.addSource).toHaveBeenCalledWith(PLACE_CLUSTER_SOURCE_ID, expect.objectContaining({ cluster: true }));
|
||||||
|
const layers = map.addLayer.mock.calls.map(([layer]) => layer as { id: string; paint: Record<string, unknown> });
|
||||||
|
expect(layers.find((l) => l.id === 'trip-place-clusters-circle')?.paint['circle-opacity']).toBe(0);
|
||||||
|
expect(layers.find((l) => l.id === 'trip-place-clusters-count')?.paint['text-opacity']).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-COMP-PLACECLUSTER-004: one bubble per cluster, placed at its centre, that zooms in on a click', () => {
|
||||||
|
const cluster = { properties: { cluster_id: 5, point_count: 12 }, geometry: { coordinates: [139.7, 35.6] } };
|
||||||
|
const { map, source } = fakeMap([
|
||||||
|
cluster,
|
||||||
|
cluster, // the same cluster crossing a tile edge
|
||||||
|
{ properties: { cluster_id: 6 }, geometry: { coordinates: [1, 1] } }, // no count
|
||||||
|
{ properties: { cluster_id: 7, point_count: 3 } }, // no geometry
|
||||||
|
]);
|
||||||
|
const placed: { el: HTMLElement; lng: number; lat: number }[] = [];
|
||||||
|
const pins = drawClusterBubbles(map, (el, lng, lat) => {
|
||||||
|
placed.push({ el, lng, lat });
|
||||||
|
return lng;
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(pins).toEqual([139.7]);
|
||||||
|
expect(placed[0].el.textContent).toBe('12');
|
||||||
|
expect(placed[0].lat).toBe(35.6);
|
||||||
|
|
||||||
|
const onMapClick = vi.fn();
|
||||||
|
document.body.appendChild(placed[0].el);
|
||||||
|
document.body.addEventListener('click', onMapClick);
|
||||||
|
placed[0].el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
|
document.body.removeEventListener('click', onMapClick);
|
||||||
|
placed[0].el.remove();
|
||||||
|
|
||||||
|
// The click is the bubble's: the map underneath never sees it.
|
||||||
|
expect(onMapClick).not.toHaveBeenCalled();
|
||||||
|
expect(source.getClusterExpansionZoom).toHaveBeenCalledWith(5, expect.any(Function));
|
||||||
|
expect(map.easeTo).toHaveBeenCalledWith({ center: [139.7, 35.6], zoom: 11, duration: 350 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-COMP-PLACECLUSTER-005: a source that reports nothing draws nothing', () => {
|
||||||
|
const { map } = fakeMap([]);
|
||||||
|
map.querySourceFeatures.mockReturnValue(null as never);
|
||||||
|
expect(drawClusterBubbles(map, () => 1)).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -5,3 +5,169 @@
|
|||||||
*/
|
*/
|
||||||
export const PLACE_CLUSTER_CIRCLE_LAYER_ID = 'trip-place-clusters-circle';
|
export const PLACE_CLUSTER_CIRCLE_LAYER_ID = 'trip-place-clusters-circle';
|
||||||
export const PLACE_CLUSTER_COUNT_LAYER_ID = 'trip-place-clusters-count';
|
export const PLACE_CLUSTER_COUNT_LAYER_ID = 'trip-place-clusters-count';
|
||||||
|
|
||||||
|
// Marker grouping for the GL map (#1385): MapLibre/Mapbox can't show the rich
|
||||||
|
// HTML photo markers *and* cluster them natively, so we feed the place points
|
||||||
|
// into a clustered GeoJSON source. The source decides what is clustered; the
|
||||||
|
// bubbles are drawn as DOM (`drawClusterBubbles`) and the individual rich HTML
|
||||||
|
// markers only for the points the source reports as currently unclustered.
|
||||||
|
// Grouping is always on, matching the Leaflet map's MarkerClusterGroup.
|
||||||
|
export const PLACE_CLUSTER_SOURCE_ID = 'trip-place-clusters';
|
||||||
|
const PLACE_UNCLUSTERED_LAYER_ID = 'trip-place-unclustered-hit';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How eagerly place markers merge into a cluster.
|
||||||
|
*
|
||||||
|
* The overview band the Leaflet map clusters in as well (`CLUSTER_UNTIL_ZOOM` there),
|
||||||
|
* kept as plain numbers rather than shared constants so the GL bundle does not have to
|
||||||
|
* carry Leaflet for them. Above the cutoff supercluster hands every point back on its
|
||||||
|
* own, and the stops that share a coordinate are folded together at the pin level
|
||||||
|
* instead — see the reconcile in MapViewGL.
|
||||||
|
*/
|
||||||
|
const CLUSTER_RADIUS = 20;
|
||||||
|
const CLUSTER_MAX_ZOOM = 8;
|
||||||
|
|
||||||
|
/** The part of either SDK's map the cluster code calls. */
|
||||||
|
export interface ClusterMap {
|
||||||
|
addSource: (id: string, source: object) => void;
|
||||||
|
addLayer: (layer: object) => void;
|
||||||
|
getSource: (id: string) => unknown;
|
||||||
|
easeTo: (options: { center: unknown[]; zoom: number; duration: number }) => void;
|
||||||
|
querySourceFeatures: (id: string, options: { filter: unknown[] }) => ClusterFeature[] | null | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClusterFeature {
|
||||||
|
properties?: { cluster_id?: unknown; point_count?: unknown } | null;
|
||||||
|
geometry?: { coordinates?: unknown };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClusterSource {
|
||||||
|
getClusterExpansionZoom?: (id: unknown, done: (err: Error | null, zoom: number) => void) => unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The cluster source and the three layers over it. Extracted so the rebuild on a mode
|
||||||
|
* change and the initial build cannot drift apart. */
|
||||||
|
export function addPlaceClusterLayers(map: Pick<ClusterMap, 'addSource' | 'addLayer'>): void {
|
||||||
|
map.addSource(PLACE_CLUSTER_SOURCE_ID, {
|
||||||
|
type: 'geojson',
|
||||||
|
data: { type: 'FeatureCollection', features: [] },
|
||||||
|
cluster: true,
|
||||||
|
clusterRadius: CLUSTER_RADIUS,
|
||||||
|
clusterMaxZoom: CLUSTER_MAX_ZOOM,
|
||||||
|
});
|
||||||
|
// Invisible: the bubble the user sees is DOM (createClusterBubble), these two
|
||||||
|
// layers stay as the hit area the track and route layers check a click against.
|
||||||
|
map.addLayer({
|
||||||
|
id: PLACE_CLUSTER_CIRCLE_LAYER_ID,
|
||||||
|
type: 'circle',
|
||||||
|
source: PLACE_CLUSTER_SOURCE_ID,
|
||||||
|
filter: ['has', 'point_count'],
|
||||||
|
paint: {
|
||||||
|
'circle-opacity': 0,
|
||||||
|
'circle-stroke-opacity': 0,
|
||||||
|
'circle-radius': ['step', ['get', 'point_count'], 18, 10, 21, 50, 24],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
map.addLayer({
|
||||||
|
id: PLACE_CLUSTER_COUNT_LAYER_ID,
|
||||||
|
type: 'symbol',
|
||||||
|
source: PLACE_CLUSTER_SOURCE_ID,
|
||||||
|
filter: ['has', 'point_count'],
|
||||||
|
layout: {
|
||||||
|
'text-field': ['get', 'point_count_abbreviated'],
|
||||||
|
'text-size': 12,
|
||||||
|
'text-allow-overlap': true,
|
||||||
|
},
|
||||||
|
paint: { 'text-opacity': 0 },
|
||||||
|
});
|
||||||
|
map.addLayer({
|
||||||
|
id: PLACE_UNCLUSTERED_LAYER_ID,
|
||||||
|
type: 'circle',
|
||||||
|
source: PLACE_CLUSTER_SOURCE_ID,
|
||||||
|
filter: ['!', ['has', 'point_count']],
|
||||||
|
paint: {
|
||||||
|
'circle-radius': 24,
|
||||||
|
'circle-opacity': 0,
|
||||||
|
'circle-stroke-opacity': 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Eases the map in to the zoom a cluster falls apart at. Both SDKs answer that
|
||||||
|
* question, one through a callback and one through a promise. */
|
||||||
|
export function expandCluster(
|
||||||
|
map: Pick<ClusterMap, 'getSource' | 'easeTo'>,
|
||||||
|
clusterId: unknown,
|
||||||
|
coordinates: unknown
|
||||||
|
): void {
|
||||||
|
if (clusterId == null || !Array.isArray(coordinates)) return;
|
||||||
|
const source = map.getSource(PLACE_CLUSTER_SOURCE_ID) as ClusterSource | undefined;
|
||||||
|
const easeToZoom = (nextZoom: number) => {
|
||||||
|
try {
|
||||||
|
map.easeTo({ center: coordinates, zoom: nextZoom, duration: 350 });
|
||||||
|
} catch {
|
||||||
|
/* noop */
|
||||||
|
}
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const maybeZoom = source?.getClusterExpansionZoom?.(clusterId, (err, nextZoom) => {
|
||||||
|
if (!err && typeof nextZoom === 'number') easeToZoom(nextZoom);
|
||||||
|
});
|
||||||
|
if (typeof maybeZoom === 'number') easeToZoom(maybeZoom);
|
||||||
|
else if (maybeZoom instanceof Promise) maybeZoom.then(easeToZoom).catch(() => {});
|
||||||
|
} catch {
|
||||||
|
/* noop */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Puts one count bubble on the map per cluster the source currently reports, through
|
||||||
|
* `place` (the caller's pin factory), and returns what `place` handed back. A cluster
|
||||||
|
* crossing a tile edge comes back once per tile, so bubbles are keyed by cluster id.
|
||||||
|
*/
|
||||||
|
export function drawClusterBubbles<T>(map: ClusterMap, place: (el: HTMLElement, lng: number, lat: number) => T): T[] {
|
||||||
|
const pins: T[] = [];
|
||||||
|
const seen = new Set<unknown>();
|
||||||
|
for (const feature of map.querySourceFeatures(PLACE_CLUSTER_SOURCE_ID, { filter: ['has', 'point_count'] }) ?? []) {
|
||||||
|
const clusterId = feature?.properties?.cluster_id;
|
||||||
|
const count = feature?.properties?.point_count;
|
||||||
|
const coordinates = feature?.geometry?.coordinates;
|
||||||
|
if (typeof count !== 'number' || !Array.isArray(coordinates) || seen.has(clusterId)) continue;
|
||||||
|
seen.add(clusterId);
|
||||||
|
const el = createClusterBubble(count);
|
||||||
|
el.addEventListener('click', (ev) => {
|
||||||
|
ev.stopPropagation();
|
||||||
|
expandCluster(map, clusterId, coordinates);
|
||||||
|
});
|
||||||
|
pins.push(place(el, coordinates[0], coordinates[1]));
|
||||||
|
}
|
||||||
|
return pins;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A count bubble's diameter in pixels: both renderers size their bubbles by it. */
|
||||||
|
export function clusterBubbleSize(count: number): number {
|
||||||
|
return count < 10 ? 36 : count < 50 ? 42 : 48;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A count bubble as DOM, styled by `.marker-cluster-custom` in index.css.
|
||||||
|
*
|
||||||
|
* The GL map draws its bubbles with this element rather than as canvas text, so they
|
||||||
|
* read in the app's own font and get the same hover the Leaflet map has. A canvas
|
||||||
|
* symbol layer can only use the glyphs the map style ships and knows no `:hover`.
|
||||||
|
* The bubble sits in a bare wrapper because the pin positions its element through
|
||||||
|
* `transform`, which would otherwise override the hover's scale.
|
||||||
|
*/
|
||||||
|
export function createClusterBubble(count: number): HTMLDivElement {
|
||||||
|
const size = clusterBubbleSize(count);
|
||||||
|
const bubble = document.createElement('div');
|
||||||
|
bubble.className = 'marker-cluster-custom';
|
||||||
|
bubble.style.width = `${size}px`;
|
||||||
|
bubble.style.height = `${size}px`;
|
||||||
|
const label = document.createElement('span');
|
||||||
|
label.textContent = String(count);
|
||||||
|
bubble.appendChild(label);
|
||||||
|
const wrapper = document.createElement('div');
|
||||||
|
wrapper.appendChild(bubble);
|
||||||
|
return wrapper;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { routeCacheRepo } from '../../repo/routeCacheRepo';
|
||||||
|
import type { RouteWithLegs } from '../../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Route answers by RouteCalculator's cache key (profile, unit, waypoints,
|
||||||
|
* avoided roads). Routes are stable, so this keeps the router from being asked
|
||||||
|
* again on every day switch or reorder: in memory for this visit, and on the
|
||||||
|
* device for the next one, so a trip that shows its whole route opens drawn
|
||||||
|
* instead of routing every leg again, one a second (#2794).
|
||||||
|
*/
|
||||||
|
const inMemory = new Map<string, RouteWithLegs>();
|
||||||
|
const MEMORY_MAX = 200;
|
||||||
|
|
||||||
|
/** Keeps a route for this visit only, dropping the oldest past the limit. */
|
||||||
|
export function rememberRoute(key: string, route: RouteWithLegs): void {
|
||||||
|
inMemory.set(key, route);
|
||||||
|
if (inMemory.size > MEMORY_MAX) {
|
||||||
|
const oldest = inMemory.keys().next().value;
|
||||||
|
if (oldest !== undefined) inMemory.delete(oldest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The route this visit already holds, without asking the device. */
|
||||||
|
export function routeInMemory(key: string): RouteWithLegs | undefined {
|
||||||
|
return inMemory.get(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keeps a route the router just answered, in memory and on the device. */
|
||||||
|
export function cacheRoute(key: string, route: RouteWithLegs): void {
|
||||||
|
rememberRoute(key, route);
|
||||||
|
void routeCacheRepo.put(key, route);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The route kept in memory, else the one kept on the device, which then stays in memory too. */
|
||||||
|
export async function storedRoute(key: string): Promise<RouteWithLegs | null> {
|
||||||
|
const held = inMemory.get(key);
|
||||||
|
if (held) return held;
|
||||||
|
const kept = await routeCacheRepo.get<RouteWithLegs>(key);
|
||||||
|
if (kept) rememberRoute(key, kept);
|
||||||
|
return kept;
|
||||||
|
}
|
||||||
@@ -485,6 +485,17 @@ describe('KategorieGruppe — inline add item', () => {
|
|||||||
expect(onAddItem).not.toHaveBeenCalled()
|
expect(onAddItem).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('FE-W5CAT-028a: Enter on the first item typed into the placeholder row opens the add field (#2825)', async () => {
|
||||||
|
server.use(http.put('/api/trips/1/packing/1', () => HttpResponse.json({ item: buildPackingItem({ id: 1, name: 'Tent', category: 'Gear' }) })))
|
||||||
|
setup({ items: [buildPackingItem({ id: 1, name: '...', category: 'Gear' })] })
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('...'))
|
||||||
|
fireEvent.change(screen.getByPlaceholderText('...'), { target: { value: 'Tent' } })
|
||||||
|
fireEvent.keyDown(screen.getByPlaceholderText('...'), { key: 'Enter' })
|
||||||
|
|
||||||
|
await waitFor(() => expect(screen.getByPlaceholderText('Item name...')).toHaveFocus())
|
||||||
|
})
|
||||||
|
|
||||||
it('FE-W5CAT-028: the confirm button adds the item, and stays inert while empty', () => {
|
it('FE-W5CAT-028: the confirm button adds the item, and stays inert while empty', () => {
|
||||||
const onAddItem = vi.fn(async () => {})
|
const onAddItem = vi.fn(async () => {})
|
||||||
const { container } = setup({ onAddItem })
|
const { container } = setup({ onAddItem })
|
||||||
|
|||||||
@@ -86,6 +86,7 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
|
|||||||
const [showAddItem, setShowAddItem] = useState(false)
|
const [showAddItem, setShowAddItem] = useState(false)
|
||||||
const [newItemName, setNewItemName] = useState('')
|
const [newItemName, setNewItemName] = useState('')
|
||||||
const addItemRef = useRef<HTMLInputElement>(null)
|
const addItemRef = useRef<HTMLInputElement>(null)
|
||||||
|
const openAddItem = () => { setShowAddItem(true); setTimeout(() => addItemRef.current?.focus(), 30) }
|
||||||
const menuBtnRef = useRef<HTMLButtonElement>(null)
|
const menuBtnRef = useRef<HTMLButtonElement>(null)
|
||||||
const assigneeDropdownRef = useRef<HTMLDivElement>(null)
|
const assigneeDropdownRef = useRef<HTMLDivElement>(null)
|
||||||
const { togglePackingItem } = useTripStore()
|
const { togglePackingItem } = useTripStore()
|
||||||
@@ -292,7 +293,7 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
|
|||||||
const contributions = contribFor(item.id)
|
const contributions = contribFor(item.id)
|
||||||
return (
|
return (
|
||||||
<React.Fragment key={item.id}>
|
<React.Fragment key={item.id}>
|
||||||
<ArtikelZeile item={item} tripId={tripId} categories={allCategories} onCategoryChange={() => {}} onDelete={onDeleteItem} bagTrackingEnabled={bagTrackingEnabled} bags={bags} onCreateBag={onCreateBag} canEdit={canEdit} divider={index > 0}
|
<ArtikelZeile item={item} tripId={tripId} categories={allCategories} onCategoryChange={() => {}} onDelete={onDeleteItem} onPlaceholderFilled={openAddItem} bagTrackingEnabled={bagTrackingEnabled} bags={bags} onCreateBag={onCreateBag} canEdit={canEdit} divider={index > 0}
|
||||||
tripMembers={tripMembers} currentUserId={currentUserId} onSetSharing={onSetSharing} onClone={onClone} onJoin={onJoin} onLeave={onLeave}
|
tripMembers={tripMembers} currentUserId={currentUserId} onSetSharing={onSetSharing} onClone={onClone} onJoin={onJoin} onLeave={onLeave}
|
||||||
drag={canEdit && reorderable ? {
|
drag={canEdit && reorderable ? {
|
||||||
isDragging: dragId === item.id,
|
isDragging: dragId === item.id,
|
||||||
@@ -343,7 +344,7 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
|
|||||||
// A row of its own on a faint tint, so it closes the card instead
|
// A row of its own on a faint tint, so it closes the card instead
|
||||||
// of trailing off: a dashed box in the checkbox column (past the drag
|
// of trailing off: a dashed box in the checkbox column (past the drag
|
||||||
// grip's width) and the label where an item's name sits.
|
// grip's width) and the label where an item's name sits.
|
||||||
<button type="button" onClick={() => { setShowAddItem(true); setTimeout(() => addItemRef.current?.focus(), 30) }}
|
<button type="button" onClick={openAddItem}
|
||||||
style={{ display: 'flex', alignItems: 'center', gap: 9, width: 'calc(100% - 8px)', margin: '6px 4px 0', paddingBlock: 8, paddingInlineEnd: 10, paddingInlineStart: 28, borderRadius: 10, border: 'none', background: 'var(--bg-secondary)', cursor: 'pointer', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, color: 'var(--text-faint)', fontFamily: 'inherit', textAlign: 'start' }}
|
style={{ display: 'flex', alignItems: 'center', gap: 9, width: 'calc(100% - 8px)', margin: '6px 4px 0', paddingBlock: 8, paddingInlineEnd: 10, paddingInlineStart: 28, borderRadius: 10, border: 'none', background: 'var(--bg-secondary)', cursor: 'pointer', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, color: 'var(--text-faint)', fontFamily: 'inherit', textAlign: 'start' }}
|
||||||
onMouseEnter={e => e.currentTarget.style.color = 'var(--text-secondary)'}
|
onMouseEnter={e => e.currentTarget.style.color = 'var(--text-secondary)'}
|
||||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
|
||||||
|
|||||||
@@ -257,6 +257,23 @@ describe('ArtikelZeile — renaming', () => {
|
|||||||
await waitFor(() => expect(screen.getByText('...')).toBeInTheDocument())
|
await waitFor(() => expect(screen.getByText('...')).toBeInTheDocument())
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('FE-W5ROW-008b: Enter on a filled placeholder row hands the typing on, a blur does not (#2825)', async () => {
|
||||||
|
server.use(http.put('/api/trips/1/packing/1', () => HttpResponse.json({ item: buildPackingItem({ id: 1, name: 'Tent' }) })))
|
||||||
|
const onPlaceholderFilled = vi.fn()
|
||||||
|
setup({ item: buildPackingItem({ id: 1, name: '...', category: 'Gear' }), onPlaceholderFilled })
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('...'))
|
||||||
|
fireEvent.change(screen.getByPlaceholderText('...'), { target: { value: 'Tent' } })
|
||||||
|
fireEvent.blur(screen.getByPlaceholderText('...'))
|
||||||
|
await waitFor(() => expect(screen.queryByPlaceholderText('...')).toBeNull())
|
||||||
|
expect(onPlaceholderFilled).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('...'))
|
||||||
|
fireEvent.change(screen.getByPlaceholderText('...'), { target: { value: 'Tent' } })
|
||||||
|
fireEvent.keyDown(screen.getByPlaceholderText('...'), { key: 'Enter' })
|
||||||
|
await waitFor(() => expect(onPlaceholderFilled).toHaveBeenCalledTimes(1))
|
||||||
|
})
|
||||||
|
|
||||||
it('FE-W5ROW-009: a failing rename surfaces a save error', async () => {
|
it('FE-W5ROW-009: a failing rename surfaces a save error', async () => {
|
||||||
server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 })))
|
server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 })))
|
||||||
setup()
|
setup()
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ interface ArtikelZeileProps {
|
|||||||
categories: string[]
|
categories: string[]
|
||||||
onCategoryChange: () => void
|
onCategoryChange: () => void
|
||||||
onDelete?: (item: PackingItem) => Promise<void>
|
onDelete?: (item: PackingItem) => Promise<void>
|
||||||
|
/** Enter on the filled '...' row, so the category's add field can take over the typing (#2825). */
|
||||||
|
onPlaceholderFilled?: () => void
|
||||||
bagTrackingEnabled?: boolean
|
bagTrackingEnabled?: boolean
|
||||||
bags?: PackingBag[]
|
bags?: PackingBag[]
|
||||||
onCreateBag: (name: string) => Promise<PackingBag | undefined>
|
onCreateBag: (name: string) => Promise<PackingBag | undefined>
|
||||||
@@ -49,7 +51,7 @@ interface ArtikelZeileProps {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ArtikelZeile({ item, tripId, categories, onCategoryChange: _onCategoryChange, onDelete, bagTrackingEnabled, bags = [], onCreateBag, canEdit = true, tripMembers = [], currentUserId, onSetSharing, onClone, onJoin, onLeave, divider = false, drag }: ArtikelZeileProps) {
|
export function ArtikelZeile({ item, tripId, categories, onCategoryChange: _onCategoryChange, onDelete, onPlaceholderFilled, bagTrackingEnabled, bags = [], onCreateBag, canEdit = true, tripMembers = [], currentUserId, onSetSharing, onClone, onJoin, onLeave, divider = false, drag }: ArtikelZeileProps) {
|
||||||
const isPlaceholder = item.name === PACKING_PLACEHOLDER_NAME
|
const isPlaceholder = item.name === PACKING_PLACEHOLDER_NAME
|
||||||
const [editing, setEditing] = useState(false)
|
const [editing, setEditing] = useState(false)
|
||||||
const [editName, setEditName] = useState(isPlaceholder ? '' : item.name)
|
const [editName, setEditName] = useState(isPlaceholder ? '' : item.name)
|
||||||
@@ -80,9 +82,12 @@ export function ArtikelZeile({ item, tripId, categories, onCategoryChange: _onCa
|
|||||||
|
|
||||||
const handleToggle = () => togglePackingItem(tripId, item.id, !item.checked)
|
const handleToggle = () => togglePackingItem(tripId, item.id, !item.checked)
|
||||||
|
|
||||||
const handleSaveName = async () => {
|
const handleSaveName = async (viaEnter = false) => {
|
||||||
if (!editName.trim()) { setEditing(false); setEditName(isPlaceholder ? '' : item.name); return }
|
if (!editName.trim()) { setEditing(false); setEditName(isPlaceholder ? '' : item.name); return }
|
||||||
try { await updatePackingItem(tripId, item.id, { name: editName.trim() }); setEditing(false) }
|
try {
|
||||||
|
await updatePackingItem(tripId, item.id, { name: editName.trim() }); setEditing(false)
|
||||||
|
if (viaEnter && isPlaceholder) onPlaceholderFilled?.()
|
||||||
|
}
|
||||||
catch { toast.error(t('packing.toast.saveError')) }
|
catch { toast.error(t('packing.toast.saveError')) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,8 +193,8 @@ export function ArtikelZeile({ item, tripId, categories, onCategoryChange: _onCa
|
|||||||
type="text" value={editName} autoFocus
|
type="text" value={editName} autoFocus
|
||||||
placeholder={isPlaceholder ? '...' : undefined}
|
placeholder={isPlaceholder ? '...' : undefined}
|
||||||
onChange={e => setEditName(e.target.value)}
|
onChange={e => setEditName(e.target.value)}
|
||||||
onBlur={handleSaveName}
|
onBlur={() => void handleSaveName()}
|
||||||
onKeyDown={e => { if (e.key === 'Enter') void handleSaveName(); if (e.key === 'Escape') { setEditing(false); setEditName(isPlaceholder ? '' : item.name) } }}
|
onKeyDown={e => { if (e.key === 'Enter') void handleSaveName(true); if (e.key === 'Escape') { setEditing(false); setEditName(isPlaceholder ? '' : item.name) } }}
|
||||||
style={{ flex: 1, minWidth: 0, fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', padding: '2px 8px', borderRadius: 6, border: '1px solid var(--border-primary)', outline: 'none', fontFamily: 'inherit' }}
|
style={{ flex: 1, minWidth: 0, fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', padding: '2px 8px', borderRadius: 6, border: '1px solid var(--border-primary)', outline: 'none', fontFamily: 'inherit' }}
|
||||||
/>
|
/>
|
||||||
) : canEdit ? (
|
) : canEdit ? (
|
||||||
|
|||||||
@@ -5,19 +5,22 @@ import { useLocationBias } from '../../hooks/useLocationBias'
|
|||||||
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage'
|
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage'
|
||||||
import { useSuggestionDropdown } from './useSuggestionDropdown'
|
import { useSuggestionDropdown } from './useSuggestionDropdown'
|
||||||
import { PlaceSuggestion, SuggestionList, SuggestionRow } from './SuggestionDropdown'
|
import { PlaceSuggestion, SuggestionList, SuggestionRow } from './SuggestionDropdown'
|
||||||
|
import type { MapMatch } from '../../repo/mapMatchRepo'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
value: string
|
value: string
|
||||||
onChange: (value: string) => void
|
onChange: (value: string) => void
|
||||||
placeholder?: string
|
placeholder?: string
|
||||||
className?: string
|
className?: string
|
||||||
|
/** A picked suggestion's spot on the map, for a form that saves where the address is (an imported stay). */
|
||||||
|
onPick?: (match: MapMatch) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
// Free-text address input with location autocomplete, backed by the same maps
|
// Free-text address input with location autocomplete, backed by the same maps
|
||||||
// search as LocationSelect. Unlike LocationSelect the typed text is
|
// search as LocationSelect. Unlike LocationSelect the typed text is
|
||||||
// authoritative: every keystroke reaches the parent so a hand-written address
|
// authoritative: every keystroke reaches the parent so a hand-written address
|
||||||
// is never lost, and picking a suggestion just replaces the text (#1496).
|
// is never lost, and picking a suggestion just replaces the text (#1496).
|
||||||
export default function AddressInput({ value, onChange, placeholder, className }: Props) {
|
export default function AddressInput({ value, onChange, placeholder, className, onPick }: Props) {
|
||||||
const { locale } = useTranslation()
|
const { locale } = useTranslation()
|
||||||
const placeLang = usePlaceLanguage()
|
const placeLang = usePlaceLanguage()
|
||||||
// Ohne Reisekontext ist der Hinweis leer, und die Suche laeuft wie bisher.
|
// Ohne Reisekontext ist der Hinweis leer, und die Suche laeuft wie bisher.
|
||||||
@@ -60,6 +63,9 @@ export default function AddressInput({ value, onChange, placeholder, className }
|
|||||||
// A response still on its way must not repopulate the list behind the pick.
|
// A response still on its way must not repopulate the list behind the pick.
|
||||||
reqIdRef.current++
|
reqIdRef.current++
|
||||||
onChange(r.address || r.name || '')
|
onChange(r.address || r.name || '')
|
||||||
|
if (onPick && Number.isFinite(r.lat) && Number.isFinite(r.lng)) {
|
||||||
|
onPick({ lat: r.lat, lng: r.lng, label: [r.name, r.address].filter(Boolean).join(', ') })
|
||||||
|
}
|
||||||
setOpen(false)
|
setOpen(false)
|
||||||
setResults([])
|
setResults([])
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
|||||||
@@ -118,9 +118,10 @@ export function DayPlanPlaceSubline({
|
|||||||
const description = place.description || place.address || cat?.name;
|
const description = place.description || place.address || cat?.name;
|
||||||
if (!(dayRowTour || place.place_time || hasPlannedTimes(tourTimes) || description)) return null;
|
if (!(dayRowTour || place.place_time || hasPlannedTimes(tourTimes) || description)) return null;
|
||||||
return (
|
return (
|
||||||
// One line like the row's name: when the hover controls come out, the description
|
// The description stays on one line and gives way first. The pills wrap rather
|
||||||
// gives way and the pills keep their place instead of wrapping onto a second line.
|
// than run out of the row: a tour carries a time, its duration and its distance,
|
||||||
<div className="trek-fade-end mt-0.5 flex min-w-0 flex-nowrap items-center gap-1.5 overflow-hidden">
|
// and in the narrow day column the last of them used to be cut off unseen.
|
||||||
|
<div className="trek-fade-end mt-0.5 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 overflow-hidden">
|
||||||
{place.place_time && dayRowTour && (
|
{place.place_time && dayRowTour && (
|
||||||
// TIME-02: a tour's end, typed or worked out from its start and its time.
|
// TIME-02: a tour's end, typed or worked out from its start and its time.
|
||||||
<TimePill quiet>
|
<TimePill quiet>
|
||||||
|
|||||||
@@ -201,9 +201,9 @@ describe('DayPlanSidebar', () => {
|
|||||||
const view = render(<DayPlanSidebar {...props} />);
|
const view = render(<DayPlanSidebar {...props} />);
|
||||||
const tourPreview = view.container.querySelector('[data-testid="trip-plan-tour-description"]') as HTMLElement;
|
const tourPreview = view.container.querySelector('[data-testid="trip-plan-tour-description"]') as HTMLElement;
|
||||||
expect(tourPreview).toHaveTextContent(description);
|
expect(tourPreview).toHaveTextContent(description);
|
||||||
// One line like the row's name, so hover controls make the description give way instead of wrapping.
|
// The description keeps to one line; the pills beside it wrap rather than run out of the row.
|
||||||
expect(tourPreview).toHaveStyle({ whiteSpace: 'nowrap', maxHeight: '1.3em' });
|
expect(tourPreview).toHaveStyle({ whiteSpace: 'nowrap', maxHeight: '1.3em' });
|
||||||
expect(tourPreview.parentElement).toHaveClass('flex-nowrap', 'overflow-hidden');
|
expect(tourPreview.parentElement).toHaveClass('flex-wrap', 'overflow-hidden');
|
||||||
expect(screen.getByTestId('trip-plan-tour-walking-time')).toHaveTextContent('Walk: 1 h');
|
expect(screen.getByTestId('trip-plan-tour-walking-time')).toHaveTextContent('Walk: 1 h');
|
||||||
expect(screen.getByTestId('trip-plan-tour-breaks')).toHaveTextContent('Breaks: 35 min');
|
expect(screen.getByTestId('trip-plan-tour-breaks')).toHaveTextContent('Breaks: 35 min');
|
||||||
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('Planned: 1 h 35 min');
|
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('Planned: 1 h 35 min');
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import { useReservationForm } from './useReservationForm'
|
|||||||
import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, travelersChanged, filesNeedConnection, uploadBookingFiles } from './bookingFormModel'
|
import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, travelersChanged, filesNeedConnection, uploadBookingFiles } from './bookingFormModel'
|
||||||
import { useBookingExpenseIntent } from './useBookingExpenseIntent'
|
import { useBookingExpenseIntent } from './useBookingExpenseIntent'
|
||||||
import { useBookingFileAttach } from './useBookingFileAttach'
|
import { useBookingFileAttach } from './useBookingFileAttach'
|
||||||
|
import StayPinStatus from './StayPinStatus'
|
||||||
|
|
||||||
const EMPTY_FORM = {
|
const EMPTY_FORM = {
|
||||||
title: '', type: 'other', status: 'pending',
|
title: '', type: 'other', status: 'pending',
|
||||||
@@ -81,7 +82,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
|
|||||||
const {
|
const {
|
||||||
form, setForm, set, isSaving, setIsSaving, pendingFiles, setPendingFiles, travelerIds, setTravelerIds, toggleTraveler,
|
form, setForm, set, isSaving, setIsSaving, pendingFiles, setPendingFiles, travelerIds, setTravelerIds, toggleTraveler,
|
||||||
isEndBeforeStart, endTimeBeforeStartTime, dateBounds: tripDateRange, startDate, startTime, setStartDate, setStartTime, takeStopDay,
|
isEndBeforeStart, endTimeBeforeStartTime, dateBounds: tripDateRange, startDate, startTime, setStartDate, setStartTime, takeStopDay,
|
||||||
pickPlace, pickHotelPlace, pickHotelStart, pickHotelEnd, saveData: buildSaveData,
|
pickPlace, pickHotelPlace, pickHotelStart, pickHotelEnd, stayPin, saveData: buildSaveData,
|
||||||
} = useReservationForm(EMPTY_FORM, days, places)
|
} = useReservationForm(EMPTY_FORM, days, places)
|
||||||
const attach = useBookingFileAttach({ reservation, files, onFileUpload, setPendingFiles, toast, t })
|
const attach = useBookingFileAttach({ reservation, files, onFileUpload, setPendingFiles, toast, t })
|
||||||
|
|
||||||
@@ -102,17 +103,22 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
|
|||||||
}
|
}
|
||||||
|
|
||||||
setTravelerIds(travelerIdsOf(reservation))
|
setTravelerIds(travelerIdsOf(reservation))
|
||||||
|
stayPin.reset()
|
||||||
if (reservation) {
|
if (reservation) {
|
||||||
setForm({ ...reservationFieldsFrom(reservation, accommodations, places, true), assignment_id: reservation.assignment_id || '' })
|
setForm({ ...reservationFieldsFrom(reservation, accommodations, places, true), assignment_id: reservation.assignment_id || '' })
|
||||||
} else if (prefill) {
|
} else if (prefill) {
|
||||||
// Review-before-save: populate from a parsed import item, stay in create mode.
|
// Review-before-save: populate from a parsed import item, stay in create mode.
|
||||||
|
const hotelPlaceId = matchPlaceId(prefill._venue?.name || prefill.title)
|
||||||
setForm({
|
setForm({
|
||||||
...reservationFieldsFromPrefill(prefill, days, true),
|
...reservationFieldsFromPrefill(prefill, days, true),
|
||||||
assignment_id: defaultAssignmentId ?? '',
|
assignment_id: defaultAssignmentId ?? '',
|
||||||
accommodation_id: '',
|
accommodation_id: '',
|
||||||
place_id: '',
|
place_id: '',
|
||||||
hotel_place_id: matchPlaceId(prefill._venue?.name || prefill.title),
|
hotel_place_id: hotelPlaceId,
|
||||||
})
|
})
|
||||||
|
// A stay the trip does not hold yet: find it on the map now, so the review
|
||||||
|
// says whether it will show there before it is saved.
|
||||||
|
if (prefill.type === 'hotel' && !hotelPlaceId) stayPin.lookUp(prefill._venue?.name || prefill.title, prefill._venue?.address)
|
||||||
// Seed the booking's Files with the document this item was parsed from.
|
// Seed the booking's Files with the document this item was parsed from.
|
||||||
setPendingFiles(prefill._sourceFiles ?? [])
|
setPendingFiles(prefill._sourceFiles ?? [])
|
||||||
} else {
|
} else {
|
||||||
@@ -362,8 +368,14 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
|
|||||||
</div>
|
</div>
|
||||||
<EditorField label={t('reservations.locationAddress')}>
|
<EditorField label={t('reservations.locationAddress')}>
|
||||||
<AddressInput value={form.hotel_address} onChange={v => set('hotel_address', v)}
|
<AddressInput value={form.hotel_address} onChange={v => set('hotel_address', v)}
|
||||||
|
onPick={stayPin.pick}
|
||||||
placeholder={t('reservations.locationPlaceholder')} className={INPUT} />
|
placeholder={t('reservations.locationPlaceholder')} className={INPUT} />
|
||||||
</EditorField>
|
</EditorField>
|
||||||
|
<StayPinStatus
|
||||||
|
pin={stayPin.pin}
|
||||||
|
hidden={!!form.hotel_place_id}
|
||||||
|
onRetry={() => stayPin.lookUp(form.title, form.hotel_address)}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { fireEvent, render, screen } from '@testing-library/react';
|
||||||
|
import { createElement } from 'react';
|
||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { TranslationProvider } from '../../i18n/TranslationContext';
|
||||||
|
import StayPinStatus from './StayPinStatus';
|
||||||
|
import type { StayPin } from './useStayPin';
|
||||||
|
|
||||||
|
function show(pin: StayPin, onRetry = vi.fn()) {
|
||||||
|
render(createElement(TranslationProvider, null, createElement(StayPinStatus, { pin, onRetry })));
|
||||||
|
return onRetry;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('StayPinStatus', () => {
|
||||||
|
it('FE-STAY-PIN-STATUS-001: shows nothing before a lookup', () => {
|
||||||
|
const { container } = render(
|
||||||
|
createElement(
|
||||||
|
TranslationProvider,
|
||||||
|
null,
|
||||||
|
createElement(StayPinStatus, { pin: { status: 'idle' }, onRetry: vi.fn() })
|
||||||
|
)
|
||||||
|
);
|
||||||
|
expect(container.textContent).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STAY-PIN-STATUS-001b: a stay already linked to a place of the trip shows nothing', () => {
|
||||||
|
const { container } = render(
|
||||||
|
createElement(
|
||||||
|
TranslationProvider,
|
||||||
|
null,
|
||||||
|
createElement(StayPinStatus, { pin: { status: 'missing' }, hidden: true, onRetry: vi.fn() })
|
||||||
|
)
|
||||||
|
);
|
||||||
|
expect(container.textContent).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STAY-PIN-STATUS-002: says it is looking, then where it found the stay', () => {
|
||||||
|
show({ status: 'searching' });
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('Looking for it on the map');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STAY-PIN-STATUS-003: a found stay names the match, so a wrong one is plain', () => {
|
||||||
|
show({ status: 'found', match: { lat: 1, lng: 2, label: 'Hotel Gracery Shinjuku, Tokyo' } });
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('On the map');
|
||||||
|
expect(screen.getByText('Hotel Gracery Shinjuku, Tokyo')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STAY-PIN-STATUS-004: a missing stay says so and offers to search again', () => {
|
||||||
|
const onRetry = show({ status: 'missing' });
|
||||||
|
expect(screen.getByText('Not on the map yet')).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /search again/i }));
|
||||||
|
expect(onRetry).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { MapPin, MapPinOff, RotateCw } from 'lucide-react';
|
||||||
|
|
||||||
|
import { useTranslation } from '../../i18n';
|
||||||
|
import type { StayPin } from './useStayPin';
|
||||||
|
|
||||||
|
interface StayPinStatusProps {
|
||||||
|
pin: StayPin;
|
||||||
|
/** A stay already linked to a place of the trip shows on the map through that place. */
|
||||||
|
hidden?: boolean;
|
||||||
|
/** Asks the map again with what the form now holds. */
|
||||||
|
onRetry: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether an imported stay will show on the map, under its address in the
|
||||||
|
* review: being looked up, found (and where, so a wrong match is plain), or not
|
||||||
|
* found, with a way to search again before it is saved without a pin. Shared by
|
||||||
|
* the desktop booking dialog and the phone's booking sheet.
|
||||||
|
*/
|
||||||
|
export default function StayPinStatus({ pin, hidden = false, onRetry }: StayPinStatusProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
if (hidden || pin.status === 'idle') return null;
|
||||||
|
|
||||||
|
if (pin.status === 'searching') {
|
||||||
|
return (
|
||||||
|
<div role="status" className="flex items-center gap-2 px-1 text-caption text-content-muted">
|
||||||
|
<span className="h-3.5 w-3.5 flex-none animate-spin rounded-full border-2 border-edge border-t-content-muted" />
|
||||||
|
{t('reservations.import.pinSearching')}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pin.status === 'found') {
|
||||||
|
return (
|
||||||
|
<div role="status" className="flex min-w-0 items-center gap-2 rounded-lg bg-success-soft px-3 py-2 text-caption">
|
||||||
|
<MapPin size={14} strokeWidth={2.2} className="flex-none text-success" />
|
||||||
|
<span className="flex-none font-semibold text-success">{t('reservations.import.pinFound')}</span>
|
||||||
|
<span className="min-w-0 truncate text-content-secondary" title={pin.match.label}>
|
||||||
|
{pin.match.label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div role="status" className="flex items-start gap-3 rounded-xl bg-warning-soft px-3.5 py-3">
|
||||||
|
<MapPinOff size={16} strokeWidth={2.2} className="mt-0.5 flex-none text-warning" />
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="m-0 text-body font-semibold text-content">{t('reservations.import.pinMissingTitle')}</p>
|
||||||
|
<p className="m-0 mt-0.5 text-caption text-content-muted">{t('reservations.import.pinMissingBody')}</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onRetry}
|
||||||
|
className="mt-2 inline-flex items-center gap-1.5 rounded-lg border border-edge bg-surface-card px-2.5 py-1 text-caption font-medium text-content hover:bg-surface-hover"
|
||||||
|
>
|
||||||
|
<RotateCw size={12} strokeWidth={2.2} />
|
||||||
|
{t('reservations.import.pinRetry')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -138,6 +138,34 @@ describe('TransitSearchPanel', () => {
|
|||||||
expect(payload.metadata.transit.legs[1]).toMatchObject({ mode: 'SUBWAY', line: 'U2', line_color: '#FF3300', headsign: 'Ruhleben' })
|
expect(payload.metadata.transit.legs[1]).toMatchObject({ mode: 'SUBWAY', line: 'U2', line_color: '#FF3300', headsign: 'Ruhleben' })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('FE-PLANNER-TRANSIT-003b: routes Google answered name Google Maps and are saved as Google’s (#2850)', async () => {
|
||||||
|
const user = userEvent.setup()
|
||||||
|
const onAdd = vi.fn().mockResolvedValue({})
|
||||||
|
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [ITINERARY], provider: 'google' })
|
||||||
|
render(<TransitSearchPanel {...makeProps({ onAdd })} />)
|
||||||
|
await pickFromAndTo(user)
|
||||||
|
await user.click(screen.getByRole('button', { name: /^Search$/ }))
|
||||||
|
await user.click(await screen.findByText(/08:30 – 09:00/))
|
||||||
|
|
||||||
|
// Google's terms want the words as written, so the browser must not translate them.
|
||||||
|
expect(screen.getByText('Google Maps')).toHaveAttribute('translate', 'no')
|
||||||
|
expect(screen.queryByRole('link', { name: 'Transitous' })).not.toBeInTheDocument()
|
||||||
|
|
||||||
|
await user.click(await screen.findByRole('button', { name: 'Add to day' }))
|
||||||
|
await waitFor(() => expect(onAdd).toHaveBeenCalled())
|
||||||
|
expect(onAdd.mock.calls[0][0].metadata.transit.provider).toBe('google')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('FE-PLANNER-TRANSIT-003c: routes Transitous answered credit Transitous with its sources link', async () => {
|
||||||
|
const user = userEvent.setup()
|
||||||
|
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [ITINERARY], provider: 'transitous' })
|
||||||
|
render(<TransitSearchPanel {...makeProps()} />)
|
||||||
|
await pickFromAndTo(user)
|
||||||
|
await user.click(screen.getByRole('button', { name: /^Search$/ }))
|
||||||
|
expect(await screen.findByRole('link', { name: 'Transitous' })).toHaveAttribute('href', 'https://transitous.org/sources/')
|
||||||
|
expect(screen.queryByText('Google Maps')).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
it('FE-PLANNER-TRANSIT-004: search failure shows the empty state, not a crash', async () => {
|
it('FE-PLANNER-TRANSIT-004: search failure shows the empty state, not a crash', async () => {
|
||||||
const user = userEvent.setup()
|
const user = userEvent.setup()
|
||||||
transitApiMock.plan.mockRejectedValueOnce(new Error('boom'))
|
transitApiMock.plan.mockRejectedValueOnce(new Error('boom'))
|
||||||
|
|||||||
@@ -604,7 +604,7 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
|
|||||||
notes: null,
|
notes: null,
|
||||||
metadata: {
|
metadata: {
|
||||||
transit: {
|
transit: {
|
||||||
provider: 'transitous',
|
provider: provider ?? 'transitous',
|
||||||
duration: it.duration,
|
duration: it.duration,
|
||||||
transfers: it.transfers,
|
transfers: it.transfers,
|
||||||
walk_seconds: it.walkSeconds,
|
walk_seconds: it.walkSeconds,
|
||||||
@@ -760,7 +760,10 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
|
|||||||
))}
|
))}
|
||||||
<div className="text-content-faint" style={{ fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))', textAlign: 'center', marginTop: 2 }}>
|
<div className="text-content-faint" style={{ fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))', textAlign: 'center', marginTop: 2 }}>
|
||||||
{t('transit.attribution')}{' '}
|
{t('transit.attribution')}{' '}
|
||||||
<a href="https://transitous.org/sources/" target="_blank" rel="noopener noreferrer" style={{ color: 'inherit', textDecoration: 'underline' }}>Transitous</a>
|
{/* Named after the backend that answered; Google's terms want "Google Maps" as written, never translated. */}
|
||||||
|
{provider === 'google'
|
||||||
|
? <span translate="no">Google Maps</span>
|
||||||
|
: <a href="https://transitous.org/sources/" target="_blank" rel="noopener noreferrer" style={{ color: 'inherit', textDecoration: 'underline' }}>Transitous</a>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -287,6 +287,8 @@ export interface ReservationSaveOptions {
|
|||||||
isEdit: boolean;
|
isEdit: boolean;
|
||||||
/** The desktop also saves the end of the check-in window. */
|
/** The desktop also saves the end of the check-in window. */
|
||||||
withCheckInEnd: boolean;
|
withCheckInEnd: boolean;
|
||||||
|
/** Where the review found an imported stay on the map, so the save creates its place right there. */
|
||||||
|
venuePin?: { lat: number; lng: number } | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ReservationSaveData = Record<string, unknown> & { title: string };
|
export type ReservationSaveData = Record<string, unknown> & { title: string };
|
||||||
@@ -344,7 +346,11 @@ export function reservationSaveData(
|
|||||||
// import): the save handler geocodes it and creates the place.
|
// import): the save handler geocodes it and creates the place.
|
||||||
venue:
|
venue:
|
||||||
!form.hotel_place_id && (form.hotel_address || form.title)
|
!form.hotel_place_id && (form.hotel_address || form.title)
|
||||||
? { name: form.title, address: form.hotel_address || null }
|
? {
|
||||||
|
name: form.title,
|
||||||
|
address: form.hotel_address || null,
|
||||||
|
...(opts.venuePin ? { lat: opts.venuePin.lat, lng: opts.venuePin.lng } : {}),
|
||||||
|
}
|
||||||
: null,
|
: null,
|
||||||
// The typed address, so the save handler can write it through to a linked
|
// The typed address, so the save handler can write it through to a linked
|
||||||
// place; an edited address used to be silently dropped (#1496).
|
// place; an edited address used to be silently dropped (#1496).
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import {
|
|||||||
withStartDate,
|
withStartDate,
|
||||||
withStartTime,
|
withStartTime,
|
||||||
} from './reservationFormModel';
|
} from './reservationFormModel';
|
||||||
|
import { useStayPin } from './useStayPin';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The booking form behind the desktop ReservationModal and the phone's booking
|
* The booking form behind the desktop ReservationModal and the phone's booking
|
||||||
@@ -39,6 +40,8 @@ export function useReservationForm<F extends ReservationFields & CheckInEndField
|
|||||||
|
|
||||||
const set = (field: keyof F, value: string | number) => setForm((prev) => ({ ...prev, [field]: value }));
|
const set = (field: keyof F, value: string | number) => setForm((prev) => ({ ...prev, [field]: value }));
|
||||||
const toggleTraveler = (id: number) => setTravelerIds((prev) => toggledTraveler(prev, id));
|
const toggleTraveler = (id: number) => setTravelerIds((prev) => toggledTraveler(prev, id));
|
||||||
|
// Where an imported stay will land on the map, looked up while it is reviewed.
|
||||||
|
const stayPin = useStayPin();
|
||||||
|
|
||||||
// Restrict non-hotel booking dates to the trip's span (#1662). Hotels already
|
// Restrict non-hotel booking dates to the trip's span (#1662). Hotels already
|
||||||
// constrain to trip days via their day dropdowns.
|
// constrain to trip days via their day dropdowns.
|
||||||
@@ -71,6 +74,7 @@ export function useReservationForm<F extends ReservationFields & CheckInEndField
|
|||||||
pickHotelPlace: (value: string | number) => setForm((prev) => withHotelPlace(prev, value, places)),
|
pickHotelPlace: (value: string | number) => setForm((prev) => withHotelPlace(prev, value, places)),
|
||||||
pickHotelStart: (value: string | number) => setForm((prev) => withHotelStart(prev, value, days)),
|
pickHotelStart: (value: string | number) => setForm((prev) => withHotelStart(prev, value, days)),
|
||||||
pickHotelEnd: (value: string | number) => setForm((prev) => withHotelEnd(prev, value, days)),
|
pickHotelEnd: (value: string | number) => setForm((prev) => withHotelEnd(prev, value, days)),
|
||||||
saveData: (opts: ReservationSaveOptions) => reservationSaveData(form, opts),
|
stayPin,
|
||||||
|
saveData: (opts: ReservationSaveOptions) => reservationSaveData(form, { ...opts, venuePin: stayPin.match }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { findOnMap } from '../../repo/mapMatchRepo';
|
||||||
|
import { isEffectivelyOffline } from '../../sync/networkMode';
|
||||||
|
import { useStayPin } from './useStayPin';
|
||||||
|
|
||||||
|
vi.mock('../../hooks/usePlaceLanguage', () => ({ usePlaceLanguage: () => 'en' }));
|
||||||
|
vi.mock('../../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) }));
|
||||||
|
vi.mock('../../repo/mapMatchRepo', async (importOriginal) => ({
|
||||||
|
...(await importOriginal<typeof import('../../repo/mapMatchRepo')>()),
|
||||||
|
findOnMap: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const SPOT = { lat: 35.69, lng: 139.7, label: 'Hotel Gracery Shinjuku' };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useStayPin', () => {
|
||||||
|
it('FE-STAY-PIN-001: looks the stay up by name and address and says where it found it', async () => {
|
||||||
|
vi.mocked(findOnMap).mockResolvedValueOnce(SPOT);
|
||||||
|
const { result } = renderHook(() => useStayPin());
|
||||||
|
expect(result.current.pin).toEqual({ status: 'idle' });
|
||||||
|
|
||||||
|
act(() => result.current.lookUp('Hotel Gracery', '1-19-1 Kabukicho'));
|
||||||
|
expect(result.current.pin).toEqual({ status: 'searching' });
|
||||||
|
await waitFor(() => expect(result.current.pin).toEqual({ status: 'found', match: SPOT }));
|
||||||
|
expect(result.current.match).toEqual(SPOT);
|
||||||
|
expect(findOnMap).toHaveBeenCalledWith(
|
||||||
|
['Hotel Gracery 1-19-1 Kabukicho', 'Hotel Gracery', '1-19-1 Kabukicho'],
|
||||||
|
'en'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STAY-PIN-002: nothing found, a failed search and an empty name all read as not on the map', async () => {
|
||||||
|
const { result } = renderHook(() => useStayPin());
|
||||||
|
vi.mocked(findOnMap).mockResolvedValueOnce(null);
|
||||||
|
act(() => result.current.lookUp('Ryokan', null));
|
||||||
|
await waitFor(() => expect(result.current.pin).toEqual({ status: 'missing' }));
|
||||||
|
expect(result.current.match).toBeNull();
|
||||||
|
|
||||||
|
vi.mocked(findOnMap).mockRejectedValueOnce(new Error('down'));
|
||||||
|
act(() => result.current.lookUp('Ryokan', null));
|
||||||
|
await waitFor(() => expect(result.current.pin).toEqual({ status: 'missing' }));
|
||||||
|
|
||||||
|
act(() => result.current.lookUp('', ''));
|
||||||
|
expect(result.current.pin).toEqual({ status: 'missing' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STAY-PIN-003: a later lookup or a hand-picked spot wins over an answer still on its way', async () => {
|
||||||
|
let answer: (m: typeof SPOT | null) => void = () => undefined;
|
||||||
|
vi.mocked(findOnMap).mockImplementationOnce(() => new Promise((resolve) => (answer = resolve)));
|
||||||
|
const { result } = renderHook(() => useStayPin());
|
||||||
|
act(() => result.current.lookUp('Hotel', 'Somewhere'));
|
||||||
|
const picked = { lat: 1, lng: 2, label: 'Picked' };
|
||||||
|
act(() => result.current.pick(picked));
|
||||||
|
await act(async () => answer(SPOT));
|
||||||
|
expect(result.current.pin).toEqual({ status: 'found', match: picked });
|
||||||
|
|
||||||
|
act(() => result.current.reset());
|
||||||
|
expect(result.current.pin).toEqual({ status: 'idle' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-STAY-PIN-004: offline there is nothing to ask, so the review shows nothing', () => {
|
||||||
|
vi.mocked(isEffectivelyOffline).mockReturnValue(true);
|
||||||
|
const { result } = renderHook(() => useStayPin());
|
||||||
|
act(() => result.current.lookUp('Hotel', 'Somewhere'));
|
||||||
|
expect(result.current.pin).toEqual({ status: 'idle' });
|
||||||
|
expect(findOnMap).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
|
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage';
|
||||||
|
import { findOnMap, type MapMatch, stayQueries } from '../../repo/mapMatchRepo';
|
||||||
|
import { isEffectivelyOffline } from '../../sync/networkMode';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where an imported stay will sit on the map, as the review shows it: not asked
|
||||||
|
* yet (or offline, where there is nothing to ask), being looked up, found, or
|
||||||
|
* not found at all.
|
||||||
|
*/
|
||||||
|
export type StayPin =
|
||||||
|
{ status: 'idle' } | { status: 'searching' } | { status: 'found'; match: MapMatch } | { status: 'missing' };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The map spot of a stay reviewed from an import, looked up before it is saved
|
||||||
|
* so the review can say whether it will show on the map. A stay the search did
|
||||||
|
* not find used to be saved without coordinates and simply never appeared.
|
||||||
|
* A later lookup always wins over an earlier one still on its way.
|
||||||
|
*/
|
||||||
|
export function useStayPin() {
|
||||||
|
const lang = usePlaceLanguage();
|
||||||
|
const [pin, setPin] = useState<StayPin>({ status: 'idle' });
|
||||||
|
const ticket = useRef(0);
|
||||||
|
useEffect(
|
||||||
|
() => () => {
|
||||||
|
ticket.current++;
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
const lookUp = (name: string | null | undefined, address: string | null | undefined) => {
|
||||||
|
const mine = ++ticket.current;
|
||||||
|
const queries = stayQueries(name ?? '', address);
|
||||||
|
if (isEffectivelyOffline()) {
|
||||||
|
setPin({ status: 'idle' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (queries.length === 0) {
|
||||||
|
setPin({ status: 'missing' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setPin({ status: 'searching' });
|
||||||
|
findOnMap(queries, lang).then(
|
||||||
|
(match) => {
|
||||||
|
if (mine === ticket.current) setPin(match ? { status: 'found', match } : { status: 'missing' });
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
if (mine === ticket.current) setPin({ status: 'missing' });
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
pin,
|
||||||
|
/** The spot to save the stay at, once one is known. */
|
||||||
|
match: pin.status === 'found' ? pin.match : null,
|
||||||
|
lookUp,
|
||||||
|
/** A spot the reader picked by hand, which beats any lookup. */
|
||||||
|
pick: (match: MapMatch) => {
|
||||||
|
ticket.current++;
|
||||||
|
setPin({ status: 'found', match });
|
||||||
|
},
|
||||||
|
reset: () => {
|
||||||
|
ticket.current++;
|
||||||
|
setPin({ status: 'idle' });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -803,6 +803,34 @@ describe('useRoadtripRoutes', () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('FE-ROADTRIP-ROUTES-052: a join this device routed before is not paced like a request (#2794)', async () => {
|
||||||
|
// A join kept its request slot whatever answered it, so a month of connected days
|
||||||
|
// waited half a minute on every open with every road already on the device. The
|
||||||
|
// clock is held still, so every answer reads as one from the cache; a join that
|
||||||
|
// still waited its turn would wait 1.1 s of real time, past what waitFor gives it.
|
||||||
|
const clock = vi.spyOn(performance, 'now').mockImplementation(() => 10_000)
|
||||||
|
try {
|
||||||
|
const MUNICH: [number, number] = [48.1374, 11.5755]
|
||||||
|
const INNSBRUCK: [number, number] = [47.2692, 11.4041]
|
||||||
|
const BOZEN: [number, number] = [46.4983, 11.3548]
|
||||||
|
setting({ roadtrip_connect_days: true })
|
||||||
|
const daysList = [day(1, 1), day(2, 2), day(3, 3)]
|
||||||
|
const assignments = {
|
||||||
|
...map(1, [{ id: 1, at: HAMBURG, time: '09:00' }, { id: 2, at: LUENEBURG }]),
|
||||||
|
...map(2, [{ id: 3, at: BERLIN, time: '09:00' }, { id: 4, at: MUNICH }]),
|
||||||
|
...map(3, [{ id: 5, at: INNSBRUCK, time: '09:00' }, { id: 6, at: BOZEN }]),
|
||||||
|
} as AssignmentsMap
|
||||||
|
renderHook(() => useRoadtripRoutes(7, daysList, assignments))
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(askedFor(LUENEBURG, BERLIN)).toHaveLength(1)
|
||||||
|
expect(askedFor(MUNICH, INNSBRUCK)).toHaveLength(1)
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
clock.mockRestore()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
it('FE-ROADTRIP-ROUTES-051: a join OSRM answered in the engine’s place is drawn, flagged, and asked for again on request', async () => {
|
it('FE-ROADTRIP-ROUTES-051: a join OSRM answered in the engine’s place is drawn, flagged, and asked for again on request', async () => {
|
||||||
// Filed like any answer, it stood in for the weighed road until the page was loaded
|
// Filed like any answer, it stood in for the weighed road until the page was loaded
|
||||||
// again, and a picker on it read the stand-in line as the road already taken.
|
// again, and a picker on it read the stand-in line as the road already taken.
|
||||||
|
|||||||
@@ -692,11 +692,19 @@ export function useRoadtripRoutes(
|
|||||||
* for both, so a choice being checked cannot fire into the gap a seam is keeping.
|
* for both, so a choice being checked cannot fire into the gap a seam is keeping.
|
||||||
*/
|
*/
|
||||||
const lastSpacedRequestAt = useRef(0)
|
const lastSpacedRequestAt = useRef(0)
|
||||||
/** Waits until the gap since the last such request is kept, then claims the next slot. */
|
/**
|
||||||
const spacedRequest = useCallback(async (signal: AbortSignal): Promise<void> => {
|
* Waits until the gap since the last such request is kept, then claims the next slot.
|
||||||
|
* Hands back what gives the slot up again, for a request the cache answered.
|
||||||
|
*/
|
||||||
|
const spacedRequest = useCallback(async (signal: AbortSignal): Promise<() => void> => {
|
||||||
const since = performance.now() - lastSpacedRequestAt.current
|
const since = performance.now() - lastSpacedRequestAt.current
|
||||||
if (since < REQUEST_SPACING_MS) await sleep(REQUEST_SPACING_MS - since, signal)
|
if (since < REQUEST_SPACING_MS) await sleep(REQUEST_SPACING_MS - since, signal)
|
||||||
if (!signal.aborted) lastSpacedRequestAt.current = performance.now()
|
const before = lastSpacedRequestAt.current
|
||||||
|
const claimed = performance.now()
|
||||||
|
if (!signal.aborted) lastSpacedRequestAt.current = claimed
|
||||||
|
return () => {
|
||||||
|
if (lastSpacedRequestAt.current === claimed) lastSpacedRequestAt.current = before
|
||||||
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -727,7 +735,7 @@ export function useRoadtripRoutes(
|
|||||||
// shared routing hosts answered the tail with 429, and a refused seam
|
// shared routing hosts answered the tail with 429, and a refused seam
|
||||||
// writes no state, so nothing changed to make the effect try again: the
|
// writes no state, so nothing changed to make the effect try again: the
|
||||||
// map drew the trip in pieces and the totals came back short.
|
// map drew the trip in pieces and the totals came back short.
|
||||||
await spacedRequest(controller.signal)
|
const release = await spacedRequest(controller.signal)
|
||||||
if (controller.signal.aborted) return
|
if (controller.signal.aborted) return
|
||||||
try {
|
try {
|
||||||
// The via points on this seam, threaded in the same way the day runs thread
|
// The via points on this seam, threaded in the same way the day runs thread
|
||||||
@@ -735,6 +743,7 @@ export function useRoadtripRoutes(
|
|||||||
// shape: it is asked for on its own, so the points the traveller dropped on it
|
// shape: it is asked for on its own, so the points the traveller dropped on it
|
||||||
// never reached the router and dragging one did visibly nothing.
|
// never reached the router and dragging one did visibly nothing.
|
||||||
const shaping = viasOnLeg(seam.from, seam.to, viasByDay[seam.from.ownerDayId] ?? [])
|
const shaping = viasOnLeg(seam.from, seam.to, viasByDay[seam.from.ownerDayId] ?? [])
|
||||||
|
const startedAt = performance.now()
|
||||||
const r = await calculateRouteWithLegs(
|
const r = await calculateRouteWithLegs(
|
||||||
[
|
[
|
||||||
{ lat: seam.from.lat, lng: seam.from.lng },
|
{ lat: seam.from.lat, lng: seam.from.lng },
|
||||||
@@ -743,6 +752,10 @@ export function useRoadtripRoutes(
|
|||||||
],
|
],
|
||||||
{ signal: controller.signal, profile: mode, tripId: tripId ?? null, dayId: seam.dayId, avoid },
|
{ signal: controller.signal, profile: mode, tripId: tripId ?? null, dayId: seam.dayId, avoid },
|
||||||
)
|
)
|
||||||
|
// A seam this device routed before came back from its cache and went nowhere, so
|
||||||
|
// its slot goes back before the store below re-runs this effect. Holding it made a
|
||||||
|
// trip of connected days wait a second per join on every open (#2794).
|
||||||
|
if (performance.now() - startedAt <= CACHE_HIT_MS) release()
|
||||||
if (controller.signal.aborted) return
|
if (controller.signal.aborted) return
|
||||||
// One leg per waypoint PAIR, so a shaped seam comes back in pieces and the rail
|
// One leg per waypoint PAIR, so a shaped seam comes back in pieces and the rail
|
||||||
// wants the whole drive: merged here, exactly as a day run folds its via legs
|
// wants the whole drive: merged here, exactly as a day run folds its via legs
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|||||||
import { buildUser } from '../../../../tests/helpers/factories';
|
import { buildUser } from '../../../../tests/helpers/factories';
|
||||||
import { render, screen } from '../../../../tests/helpers/render';
|
import { render, screen } from '../../../../tests/helpers/render';
|
||||||
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||||
|
import { useAddonStore } from '../../../store/addonStore';
|
||||||
import { useAssistantStore } from '../../../store/assistantStore';
|
import { useAssistantStore } from '../../../store/assistantStore';
|
||||||
import { useAuthStore } from '../../../store/authStore';
|
import { useAuthStore } from '../../../store/authStore';
|
||||||
import { useSettingsStore } from '../../../store/settingsStore';
|
import { useSettingsStore } from '../../../store/settingsStore';
|
||||||
@@ -33,6 +34,8 @@ beforeEach(() => {
|
|||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
useAssistantStore.setState({ status: null });
|
useAssistantStore.setState({ status: null });
|
||||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||||
|
// The card shows while the assistant is on, and only then is its status asked for.
|
||||||
|
seedStore(useAddonStore, { loaded: true, addons: [{ id: 'ai_assistant', enabled: true }] });
|
||||||
repo.models.mockResolvedValue([]);
|
repo.models.mockResolvedValue([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|||||||
import { buildAdmin, buildUser } from '../../../../tests/helpers/factories';
|
import { buildAdmin, buildUser } from '../../../../tests/helpers/factories';
|
||||||
import { render, screen, waitFor } from '../../../../tests/helpers/render';
|
import { render, screen, waitFor } from '../../../../tests/helpers/render';
|
||||||
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||||
|
import { useAddonStore } from '../../../store/addonStore';
|
||||||
import { useAssistantStore } from '../../../store/assistantStore';
|
import { useAssistantStore } from '../../../store/assistantStore';
|
||||||
import { useAuthStore } from '../../../store/authStore';
|
import { useAuthStore } from '../../../store/authStore';
|
||||||
|
|
||||||
@@ -51,6 +52,8 @@ beforeEach(() => {
|
|||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
useAssistantStore.setState({ status: null });
|
useAssistantStore.setState({ status: null });
|
||||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||||
|
// The card shows while the assistant is on, and only then is its status asked for.
|
||||||
|
seedStore(useAddonStore, { loaded: true, addons: [{ id: 'ai_assistant', enabled: true }] });
|
||||||
repo.models.mockResolvedValue([{ id: 'claude-sonnet', label: 'Claude Sonnet', supportsTools: true }]);
|
repo.models.mockResolvedValue([{ id: 'claude-sonnet', label: 'Claude Sonnet', supportsTools: true }]);
|
||||||
repo.disconnect.mockResolvedValue(undefined);
|
repo.disconnect.mockResolvedValue(undefined);
|
||||||
repo.chatgptStart.mockResolvedValue({
|
repo.chatgptStart.mockResolvedValue({
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// FE-AI-CONNECT-MODEL-001 to FE-AI-CONNECT-MODEL-007: the pure rules behind connecting an AI provider.
|
// FE-AI-CONNECT-MODEL-001 to FE-AI-CONNECT-MODEL-008: the pure rules behind connecting an AI provider.
|
||||||
import type { AiConnectionView } from '@trek/shared';
|
import type { AiConnectionView } from '@trek/shared';
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { OnlineOnlyError } from '../../../repo/onlineOnly';
|
import { OnlineOnlyError } from '../../../repo/onlineOnly';
|
||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
connectErrorKey,
|
connectErrorKey,
|
||||||
httpHostOf,
|
httpHostOf,
|
||||||
isPublicHttpsUrl,
|
isPublicHttpsUrl,
|
||||||
|
openrouterReturnCode,
|
||||||
refusalCode,
|
refusalCode,
|
||||||
rememberOpenrouterFlow,
|
rememberOpenrouterFlow,
|
||||||
repairModeOf,
|
repairModeOf,
|
||||||
@@ -46,6 +47,14 @@ describe('aiConnectModel', () => {
|
|||||||
expect(connectErrorKey(new Error('boom'))).toBe('assistant.error.generic');
|
expect(connectErrorKey(new Error('boom'))).toBe('assistant.error.generic');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-AI-CONNECT-MODEL-002b: tells an own server that answered without a model list from one that is down (#2808)', () => {
|
||||||
|
const noList = { response: { data: { code: 'provider_unavailable', reason: 'no_model_list' } } };
|
||||||
|
expect(connectErrorKey(noList)).toBe('assistant.connect.noModelList');
|
||||||
|
expect(connectErrorKey({ response: { data: { code: 'provider_unavailable', reason: 'other' } } })).toBe(
|
||||||
|
'assistant.error.providerDown'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('FE-AI-CONNECT-MODEL-003: offers the way back into a broken connection, none for a working one', () => {
|
it('FE-AI-CONNECT-MODEL-003: offers the way back into a broken connection, none for a working one', () => {
|
||||||
expect(repairModeOf(VIEW)).toBeNull();
|
expect(repairModeOf(VIEW)).toBeNull();
|
||||||
expect(repairModeOf({ ...VIEW, status: 'error' })).toBe('key');
|
expect(repairModeOf({ ...VIEW, status: 'error' })).toBe('key');
|
||||||
@@ -93,4 +102,14 @@ describe('aiConnectModel', () => {
|
|||||||
expect(src).not.toContain('<');
|
expect(src).not.toContain('<');
|
||||||
expect(decodeURIComponent(src.split(',')[1])).toBe('<svg><path d="M0 0"/></svg>');
|
expect(decodeURIComponent(src.split(',')[1])).toBe('<svg><path d="M0 0"/></svg>');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-AI-CONNECT-MODEL-008: reads the OpenRouter return with the code after an & or after a second ?', () => {
|
||||||
|
const read = (query: string) => openrouterReturnCode(new URLSearchParams(query));
|
||||||
|
expect(read('tab=integrations&ai=openrouter&code=abc')).toBe('abc');
|
||||||
|
expect(read('tab=integrations&ai=openrouter?code=abc')).toBe('abc');
|
||||||
|
expect(read('tab=addons&ai=openrouter?code=abc&state=x')).toBe('abc');
|
||||||
|
expect(read('ai=openrouter')).toBeNull();
|
||||||
|
expect(read('tab=integrations')).toBeUndefined();
|
||||||
|
expect(read('ai=chatgpt&code=abc')).toBeUndefined();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -33,9 +33,20 @@ const CONNECT_ERRORS: Record<string, { messageKey: string }> = {
|
|||||||
offline: { messageKey: 'assistant.error.offline' },
|
offline: { messageKey: 'assistant.error.offline' },
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The line a failed connect shows. Takes `{provider}` where the line names one. */
|
/** What a refused connect says for the `reason` it carries next to its code, ahead of the code's line. */
|
||||||
|
const CONNECT_REASONS: Record<string, { messageKey: string }> = {
|
||||||
|
no_model_list: { messageKey: 'assistant.connect.noModelList' },
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The line a failed connect shows. Takes `{provider}` where the line names one.
|
||||||
|
* An own server that answered without a model list is up, so it gets its own
|
||||||
|
* line about the address instead of "not responding" (#2808).
|
||||||
|
*/
|
||||||
export function connectErrorKey(err: unknown): string {
|
export function connectErrorKey(err: unknown): string {
|
||||||
return CONNECT_ERRORS[refusalCode(err) ?? '']?.messageKey ?? 'assistant.error.generic';
|
const reason = (err as { response?: { data?: { reason?: unknown } } } | null)?.response?.data?.reason;
|
||||||
|
const byReason = typeof reason === 'string' ? CONNECT_REASONS[reason] : undefined;
|
||||||
|
return byReason?.messageKey ?? CONNECT_ERRORS[refusalCode(err) ?? '']?.messageKey ?? 'assistant.error.generic';
|
||||||
}
|
}
|
||||||
|
|
||||||
/** How each connection state reads on its pill. */
|
/** How each connection state reads on its pill. */
|
||||||
@@ -56,6 +67,26 @@ export function repairModeOf(view: AiConnectionView): AiConnectMode | null {
|
|||||||
return view.kind === 'custom' ? 'custom' : 'key';
|
return view.kind === 'custom' ? 'custom' : 'key';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a pasted ChatGPT callback ended this sign-in rather than an earlier
|
||||||
|
* one: its `state` is the one the sign-in address carried. The server takes a
|
||||||
|
* sign-in only once, so an address from an earlier attempt still on the
|
||||||
|
* clipboard would use up the one in progress. Without a state on either side
|
||||||
|
* the server decides.
|
||||||
|
*/
|
||||||
|
export function callbackMatchesFlow(callback: string, authorizeUrl: string): boolean {
|
||||||
|
const stateOf = (address: string) => {
|
||||||
|
try {
|
||||||
|
return new URL(address.trim()).searchParams.get('state');
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const expected = stateOf(authorizeUrl);
|
||||||
|
const pasted = stateOf(callback);
|
||||||
|
return !expected || !pasted || pasted === expected;
|
||||||
|
}
|
||||||
|
|
||||||
// The OpenRouter sign-in leaves the page and comes back with a code only; the
|
// The OpenRouter sign-in leaves the page and comes back with a code only; the
|
||||||
// flow it belongs to waits here for that one return. Tab-scoped on purpose.
|
// flow it belongs to waits here for that one return. Tab-scoped on purpose.
|
||||||
const OPENROUTER_FLOW_KEY = 'trek.ai.openrouterFlow';
|
const OPENROUTER_FLOW_KEY = 'trek.ai.openrouterFlow';
|
||||||
@@ -79,6 +110,21 @@ export function takeOpenrouterFlow(): string | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The code an OpenRouter sign-in came back with, or `undefined` when the page
|
||||||
|
* was not opened by one. The return address already carries a query
|
||||||
|
* (`?tab=…&ai=openrouter`), and OpenRouter may add its code with a second `?`
|
||||||
|
* rather than an `&`, which leaves it inside the `ai` value
|
||||||
|
* (`ai=openrouter?code=…`); both shapes count.
|
||||||
|
*/
|
||||||
|
export function openrouterReturnCode(params: URLSearchParams): string | null | undefined {
|
||||||
|
const ai = params.get('ai');
|
||||||
|
if (ai === null) return undefined;
|
||||||
|
const [marker, rest] = ai.split('?', 2);
|
||||||
|
if (marker !== 'openrouter') return undefined;
|
||||||
|
return params.get('code') ?? new URLSearchParams(rest ?? '').get('code');
|
||||||
|
}
|
||||||
|
|
||||||
const PRIVATE_V4 = [/^10\./, /^127\./, /^169\.254\./, /^192\.168\./, /^172\.(1[6-9]|2\d|3[01])\./, /^0\./];
|
const PRIVATE_V4 = [/^10\./, /^127\./, /^169\.254\./, /^192\.168\./, /^172\.(1[6-9]|2\d|3[01])\./, /^0\./];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-013: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
|
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-015: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
|
||||||
import { act, fireEvent, renderHook, waitFor } from '@testing-library/react';
|
import { act, fireEvent, renderHook, waitFor } from '@testing-library/react';
|
||||||
import { createElement, type ReactNode } from 'react';
|
import { createElement, type ReactNode } from 'react';
|
||||||
import { MemoryRouter, useLocation } from 'react-router';
|
import { MemoryRouter, useLocation } from 'react-router';
|
||||||
@@ -249,6 +249,52 @@ describe('useChatgptConnect', () => {
|
|||||||
expect(readText).toHaveBeenCalledTimes(1);
|
expect(readText).toHaveBeenCalledTimes(1);
|
||||||
input.remove();
|
input.remove();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-HOOK-AI-CONNECT-014: the same address handed in twice at once is sent once, so the sign-in is not used up', async () => {
|
||||||
|
let answer: (value: unknown) => void = () => undefined;
|
||||||
|
repo.chatgptFinish.mockImplementationOnce(() => new Promise((resolve) => (answer = resolve)));
|
||||||
|
const onConnected = vi.fn();
|
||||||
|
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
|
||||||
|
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||||
|
act(() => {
|
||||||
|
result.current.paste(CALLBACK);
|
||||||
|
result.current.paste(CALLBACK);
|
||||||
|
});
|
||||||
|
await act(async () => answer({}));
|
||||||
|
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||||
|
expect(repo.chatgptFinish).toHaveBeenCalledTimes(1);
|
||||||
|
expect(result.current.error).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('FE-HOOK-AI-CONNECT-015: an address from an earlier sign-in is not sent, and the one in progress stays usable', async () => {
|
||||||
|
repo.chatgptStart.mockResolvedValue({ ...FLOW, authorizeUrl: 'https://auth.openai.com/oauth/authorize?state=s2' });
|
||||||
|
const readText = vi.fn(async () => CALLBACK);
|
||||||
|
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { readText } });
|
||||||
|
Object.defineProperty(window, 'isSecureContext', { configurable: true, value: true });
|
||||||
|
const onConnected = vi.fn();
|
||||||
|
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
|
||||||
|
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||||
|
|
||||||
|
// Back from the sign-in window with the old address still on the clipboard: nothing is sent.
|
||||||
|
act(() => result.current.markOpened());
|
||||||
|
fireEvent.focus(window);
|
||||||
|
await waitFor(() => expect(readText).toHaveBeenCalled());
|
||||||
|
expect(repo.chatgptFinish).not.toHaveBeenCalled();
|
||||||
|
expect(result.current.error).toBeNull();
|
||||||
|
|
||||||
|
// Pasted by hand it is refused here, and the address this sign-in ended on still goes through.
|
||||||
|
act(() => {
|
||||||
|
result.current.paste(CALLBACK);
|
||||||
|
});
|
||||||
|
expect(result.current.error).toEqual({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
|
||||||
|
const current = CALLBACK.replace('state=s1', 'state=s2');
|
||||||
|
act(() => {
|
||||||
|
result.current.paste(current);
|
||||||
|
});
|
||||||
|
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||||
|
expect(repo.chatgptFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, pastedUrl: current });
|
||||||
|
expect(repo.chatgptStart).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('OpenRouter', () => {
|
describe('OpenRouter', () => {
|
||||||
@@ -280,4 +326,19 @@ describe('OpenRouter', () => {
|
|||||||
await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
|
await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
|
||||||
expect(repo.openrouterFinish).not.toHaveBeenCalled();
|
expect(repo.openrouterFinish).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-HOOK-AI-CONNECT-012b: a code OpenRouter added with a second question mark still finishes the sign-in', async () => {
|
||||||
|
rememberOpenrouterFlow(FLOW.flowId);
|
||||||
|
const onConnected = vi.fn();
|
||||||
|
const { result } = renderHook(
|
||||||
|
() => {
|
||||||
|
useOpenrouterReturn(onConnected);
|
||||||
|
return useLocation();
|
||||||
|
},
|
||||||
|
{ wrapper: wrapperAt('/settings?tab=integrations&ai=openrouter?code=or-code') }
|
||||||
|
);
|
||||||
|
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||||
|
expect(repo.openrouterFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, code: 'or-code' });
|
||||||
|
expect(result.current.search).toBe('?tab=integrations');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,7 +5,15 @@ import { useTranslation } from '../../../i18n';
|
|||||||
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
|
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
|
||||||
import { detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
|
import { detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
|
||||||
import { useToast } from '../../shared/Toast';
|
import { useToast } from '../../shared/Toast';
|
||||||
import { connectErrorKey, httpHostOf, refusalCode, rememberOpenrouterFlow, takeOpenrouterFlow } from './aiConnectModel';
|
import {
|
||||||
|
callbackMatchesFlow,
|
||||||
|
connectErrorKey,
|
||||||
|
httpHostOf,
|
||||||
|
openrouterReturnCode,
|
||||||
|
refusalCode,
|
||||||
|
rememberOpenrouterFlow,
|
||||||
|
takeOpenrouterFlow,
|
||||||
|
} from './aiConnectModel';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The ways to connect a provider, one hook each, behind `AiConnectPanel`: a
|
* The ways to connect a provider, one hook each, behind `AiConnectPanel`: a
|
||||||
@@ -205,6 +213,10 @@ export function useChatgptConnect({
|
|||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState<ConnectError | null>(null);
|
const [error, setError] = useState<ConnectError | null>(null);
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
// Set at once, unlike `busy`: the clipboard read on return and the user's own
|
||||||
|
// paste can hand in the same address within one render, and the server takes
|
||||||
|
// a sign-in only once, so the second would come back as expired.
|
||||||
|
const finishing = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!active) return;
|
if (!active) return;
|
||||||
@@ -232,8 +244,8 @@ export function useChatgptConnect({
|
|||||||
|
|
||||||
const finish = async (raw: string) => {
|
const finish = async (raw: string) => {
|
||||||
const url = raw.trim();
|
const url = raw.trim();
|
||||||
if (!flow || busy) return;
|
if (!flow || finishing.current) return;
|
||||||
if (!isChatgptCallback(url)) {
|
if (!isChatgptCallback(url) || !callbackMatchesFlow(url, flow.authorizeUrl)) {
|
||||||
setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
|
setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -242,6 +254,7 @@ export function useChatgptConnect({
|
|||||||
restart();
|
restart();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
finishing.current = true;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
@@ -253,6 +266,7 @@ export function useChatgptConnect({
|
|||||||
setError({ messageKey: connectErrorKey(err), code });
|
setError({ messageKey: connectErrorKey(err), code });
|
||||||
if (code === 'expired') restart();
|
if (code === 'expired') restart();
|
||||||
} finally {
|
} finally {
|
||||||
|
finishing.current = false;
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -280,10 +294,12 @@ export function useChatgptConnect({
|
|||||||
|
|
||||||
// Back from the sign-in window: the address the user just copied is taken
|
// Back from the sign-in window: the address the user just copied is taken
|
||||||
// off the clipboard where the browser allows it, else the field has the cursor.
|
// off the clipboard where the browser allows it, else the field has the cursor.
|
||||||
|
// An address left over from an earlier sign-in is not sent: it would use up this one.
|
||||||
useOnReturnToTab(opened, () => {
|
useOnReturnToTab(opened, () => {
|
||||||
if (pasted.trim() || busy) return;
|
if (pasted.trim() || busy) return;
|
||||||
readClipboard((text) => {
|
readClipboard((text) => {
|
||||||
if (!paste(text)) focusField();
|
if (flow && !callbackMatchesFlow(text, flow.authorizeUrl)) focusField();
|
||||||
|
else if (!paste(text)) focusField();
|
||||||
}, focusField);
|
}, focusField);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -351,9 +367,9 @@ export function useOpenrouterReturn(onConnected: () => void) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (handled.current || params.get('ai') !== 'openrouter') return;
|
const code = openrouterReturnCode(params);
|
||||||
|
if (handled.current || code === undefined) return;
|
||||||
handled.current = true;
|
handled.current = true;
|
||||||
const code = params.get('code');
|
|
||||||
setParams(
|
setParams(
|
||||||
(prev) => {
|
(prev) => {
|
||||||
const next = new URLSearchParams(prev);
|
const next = new URLSearchParams(prev);
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import type { AiConnectionView, AiStatusResponse } from '@trek/shared';
|
|||||||
import { createElement, type ReactNode } from 'react';
|
import { createElement, type ReactNode } from 'react';
|
||||||
import { MemoryRouter, useLocation } from 'react-router';
|
import { MemoryRouter, useLocation } from 'react-router';
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { seedStore } from '../../../../tests/helpers/store';
|
||||||
import { TranslationProvider } from '../../../i18n/TranslationContext';
|
import { TranslationProvider } from '../../../i18n/TranslationContext';
|
||||||
|
import { useAddonStore } from '../../../store/addonStore';
|
||||||
import { useAssistantStore } from '../../../store/assistantStore';
|
import { useAssistantStore } from '../../../store/assistantStore';
|
||||||
|
|
||||||
const repo = vi.hoisted(() => ({
|
const repo = vi.hoisted(() => ({
|
||||||
@@ -61,6 +63,8 @@ function renderConnections(phone = false) {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
useAssistantStore.setState({ status: null, window: { open: false, minimized: false } });
|
useAssistantStore.setState({ status: null, window: { open: false, minimized: false } });
|
||||||
|
// The card shows while the assistant is on, and only then is its status asked for.
|
||||||
|
seedStore(useAddonStore, { loaded: true, addons: [{ id: 'ai_assistant', enabled: true }] });
|
||||||
repo.status.mockResolvedValue(status());
|
repo.status.mockResolvedValue(status());
|
||||||
repo.models.mockResolvedValue([
|
repo.models.mockResolvedValue([
|
||||||
{ id: 'claude-sonnet', label: 'Claude Sonnet', supportsTools: true },
|
{ id: 'claude-sonnet', label: 'Claude Sonnet', supportsTools: true },
|
||||||
|
|||||||
@@ -24,9 +24,9 @@ function releaseNotice(overrides: Partial<SystemNoticeDTO> = {}): SystemNoticeDT
|
|||||||
introKey: 'rel.intro',
|
introKey: 'rel.intro',
|
||||||
featuresLabelKey: 'rel.features.label',
|
featuresLabelKey: 'rel.features.label',
|
||||||
features: [
|
features: [
|
||||||
{ iconName: 'Database', visual: 'places-api', titleKey: 'rel.f1.title', bodyKey: 'rel.f1.body' },
|
{ iconName: 'Mountain', visual: 'tours', titleKey: 'rel.f1.title', bodyKey: 'rel.f1.body' },
|
||||||
{ iconName: 'Route', visual: 'roadtrip', titleKey: 'rel.f2.title', bodyKey: 'rel.f2.body' },
|
{ iconName: 'BookOpen', visual: 'studio', titleKey: 'rel.f2.title', bodyKey: 'rel.f2.body' },
|
||||||
{ iconName: 'MapPin', visual: 'dawarich', titleKey: 'rel.f3.title', bodyKey: 'rel.f3.body' },
|
{ iconName: 'Sparkles', visual: 'assistant', titleKey: 'rel.f3.title', bodyKey: 'rel.f3.body' },
|
||||||
],
|
],
|
||||||
note: {
|
note: {
|
||||||
eyebrowKey: 'rel.note.eyebrow',
|
eyebrowKey: 'rel.note.eyebrow',
|
||||||
@@ -78,9 +78,9 @@ describe('ReleaseNoticeModal', () => {
|
|||||||
renderModal()
|
renderModal()
|
||||||
expect(screen.getByText('rel.f1.title')).toBeInTheDocument()
|
expect(screen.getByText('rel.f1.title')).toBeInTheDocument()
|
||||||
expect(document.querySelectorAll('.rn-feature')).toHaveLength(3)
|
expect(document.querySelectorAll('.rn-feature')).toHaveLength(3)
|
||||||
expect(document.querySelector('.rn-vis-places')).not.toBeNull()
|
expect(document.querySelector('.rn-vis-tours')).not.toBeNull()
|
||||||
expect(document.querySelector('.rn-vis-road')).not.toBeNull()
|
expect(document.querySelector('.rn-vis-studio')).not.toBeNull()
|
||||||
expect(document.querySelector('.rn-vis-trail')).not.toBeNull()
|
expect(document.querySelector('.rn-vis-assist')).not.toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('FE-RN-004: splits the note body on the blank line into separate paragraphs', () => {
|
it('FE-RN-004: splits the note body on the blank line into separate paragraphs', () => {
|
||||||
@@ -194,20 +194,20 @@ describe('ReleaseNoticeModal', () => {
|
|||||||
const n = releaseNotice()
|
const n = releaseNotice()
|
||||||
n.release!.features = [
|
n.release!.features = [
|
||||||
...n.release!.features,
|
...n.release!.features,
|
||||||
{ iconName: 'FolderSync', visual: 'docsync', layout: 'wide', titleKey: 'rel.f4.title', bodyKey: 'rel.f4.body' },
|
{ iconName: 'LifeBuoy', visual: 'help', layout: 'wide', titleKey: 'rel.f4.title', bodyKey: 'rel.f4.body' },
|
||||||
]
|
]
|
||||||
renderModal(n)
|
renderModal(n)
|
||||||
const cards = document.querySelectorAll('.rn-feature')
|
const cards = document.querySelectorAll('.rn-feature')
|
||||||
expect(cards).toHaveLength(4)
|
expect(cards).toHaveLength(4)
|
||||||
expect(cards[3].classList.contains('rn-feature-wide')).toBe(true)
|
expect(cards[3].classList.contains('rn-feature-wide')).toBe(true)
|
||||||
expect([...cards].slice(0, 3).some(c => c.classList.contains('rn-feature-wide'))).toBe(false)
|
expect([...cards].slice(0, 3).some(c => c.classList.contains('rn-feature-wide'))).toBe(false)
|
||||||
// The document sync drawing: the wordmark without its API pill, and the five stores.
|
// The help drawing: the help button and two rows of greetings, each written twice to loop.
|
||||||
const wide = cards[3]
|
const wide = cards[3]
|
||||||
expect(wide.querySelector('.rn-vis-docs')).not.toBeNull()
|
expect(wide.querySelector('.rn-vis-help-q')).not.toBeNull()
|
||||||
expect(wide.querySelectorAll('.rn-vis-docs-store')).toHaveLength(5)
|
expect(wide.querySelectorAll('.rn-vis-hello-row')).toHaveLength(2)
|
||||||
expect(wide.querySelector('.trek-mark .pill-bg')).toBeNull()
|
expect(wide.querySelectorAll('.rn-vis-hello').length % 2).toBe(0)
|
||||||
// The places card keeps the pill: that one is about the index.
|
// The tours card lists the kinds of tour along its foot.
|
||||||
expect(cards[0].querySelector('.trek-mark .pill-bg')).not.toBeNull()
|
expect(cards[0].querySelectorAll('.rn-vis-tours-kind')).toHaveLength(5)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('FE-RN-016: the close button belongs to the panel, not the note', () => {
|
it('FE-RN-016: the close button belongs to the panel, not the note', () => {
|
||||||
|
|||||||
@@ -1,94 +1,166 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import * as LucideIcons from 'lucide-react';
|
import * as LucideIcons from 'lucide-react';
|
||||||
import { ArrowLeftRight, Car, Landmark, Search, Sparkles } from 'lucide-react';
|
import { Bike, Check, Footprints, Landmark, Plane, Sailboat, Snowflake, Sparkles, Star, TrendingUp } from 'lucide-react';
|
||||||
import DawarichIcon from '../shared/DawarichIcon';
|
import './releaseNoticeVisuals.css';
|
||||||
import { NextcloudIcon, OpenCloudIcon, PaperlessIcon, PapraIcon, SynologyDriveIcon } from '../shared/DocumentProviderIcons';
|
|
||||||
import TrekMark from '../shared/TrekMark';
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* The small pictures on the release cards: pieces of TREK itself, drawn at card
|
* The small pictures on the release cards: pieces of TREK itself, drawn at card
|
||||||
* size rather than screenshotted, because a screenshot this small is a blur. They
|
* size rather than screenshotted, because a screenshot this small is a blur. They
|
||||||
* carry no words, only place names and figures that read the same in every
|
* carry no words, only place names, greetings and figures that read the same in
|
||||||
* language, so nothing here needs translating.
|
* every language, so nothing here needs translating. Every colour lives in
|
||||||
|
* releaseNoticeVisuals.css, and every motion stops under reduced motion.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function PlacesApiVisual() {
|
// ── Tours: a trail climbing to the summit at dusk, and the kinds of tour under it ──
|
||||||
return (
|
|
||||||
<div className="rn-vis rn-vis-places">
|
|
||||||
<span className="rn-vis-trekbadge"><TrekMark className="rn-vis-trekmark" /></span>
|
|
||||||
<div className="rn-vis-search">
|
|
||||||
<Search size={11} strokeWidth={2.4} />
|
|
||||||
<span className="rn-vis-typed">Fushimi Inari</span>
|
|
||||||
<span className="rn-vis-caret" />
|
|
||||||
</div>
|
|
||||||
<div className="rn-vis-result">
|
|
||||||
<span className="rn-vis-cat" style={{ background: '#ef4444' }}><Landmark size={10} strokeWidth={2.2} /></span>
|
|
||||||
<span className="rn-vis-place">
|
|
||||||
<span>Fushimi Inari Taisha</span>
|
|
||||||
<small>Kyoto</small>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The route and its stops, in the planner's own route blue and marker style.
|
const FAR_RIDGE = 'M0 66 L20 50 L38 60 L60 38 L84 56 L104 44 L128 58 L152 40 L176 54 L200 46 V112 H0 Z';
|
||||||
const ROUTE = 'M26 84 C 58 82, 60 44, 96 46 S 136 74, 160 52 S 176 30, 182 28';
|
const MOUNTAIN = 'M0 112 V86 L44 62 L84 28 L98 38 L112 32 L152 68 L200 80 V112 Z';
|
||||||
|
const SNOW = 'M84 28 L73 38 L79 37 L84 42 L89 37.5 L95 37 Z';
|
||||||
|
const MEADOW = 'M0 112 V96 C 30 88, 60 90, 92 94 S 160 82, 200 90 V112 Z';
|
||||||
|
// From the valley up the mountain's flank to the summit, in switchbacks.
|
||||||
|
const TRAIL = 'M24 100 C 40 96, 50 90, 54 84 S 66 78, 70 72 S 64 62, 72 56 S 82 48, 78 42 S 82 34, 84 29';
|
||||||
|
const KINDS = [Footprints, Bike, Sailboat, Snowflake, Landmark];
|
||||||
|
|
||||||
function RoadtripVisual() {
|
function ToursVisual() {
|
||||||
return (
|
return (
|
||||||
<div className="rn-vis rn-vis-road">
|
<div className="rn-vis rn-vis-tours">
|
||||||
<svg viewBox="0 0 200 112" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
|
<svg className="rn-vis-tours-scene" viewBox="0 0 200 112" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
|
||||||
<path className="rn-vis-road-casing" d={ROUTE} />
|
<circle className="rn-vis-tours-sun" cx="160" cy="24" r="9" />
|
||||||
<path className="rn-vis-road-line" d={ROUTE} />
|
<path className="rn-vis-tours-far" d={FAR_RIDGE} />
|
||||||
|
<path className="rn-vis-tours-mountain" d={MOUNTAIN} />
|
||||||
|
<path className="rn-vis-tours-snow" d={SNOW} />
|
||||||
|
<path className="rn-vis-tours-meadow" d={MEADOW} />
|
||||||
|
<path className="rn-vis-tours-trail" d={TRAIL} pathLength={1} />
|
||||||
|
<circle className="rn-vis-tours-walker" r="2.6">
|
||||||
|
<animateMotion dur="5s" begin="1.6s" repeatCount="indefinite" path={TRAIL} />
|
||||||
|
</circle>
|
||||||
|
<g className="rn-vis-tours-flag">
|
||||||
|
<line x1="84" y1="29" x2="84" y2="17" />
|
||||||
|
<path d="M84 17 L93 20 L84 23 Z" />
|
||||||
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
<span className="rn-vis-marker" style={{ left: '13%', top: '75%', background: '#6366f1' }}>1</span>
|
<span className="rn-vis-tours-climb">
|
||||||
<span className="rn-vis-marker" style={{ left: '48%', top: '41%', background: '#f59e0b' }}>2</span>
|
<TrendingUp size={9} strokeWidth={2.6} />
|
||||||
<span className="rn-vis-marker" style={{ left: '91%', top: '25%', background: '#ec4899' }}>3</span>
|
860 m
|
||||||
<span className="rn-vis-distance"><Car size={10} strokeWidth={2.2} />386 km</span>
|
</span>
|
||||||
</div>
|
<div className="rn-vis-tours-kinds">
|
||||||
);
|
{KINDS.map((Kind, i) => (
|
||||||
}
|
<span key={i} className="rn-vis-tours-kind" style={{ animationDelay: `${1.2 + i * 0.08}s` }}>
|
||||||
|
<Kind size={10} strokeWidth={2.2} />
|
||||||
// A recorded day, with the two places the traveller stayed.
|
</span>
|
||||||
const TRAIL = '84,94 96,88 106,80 118,76 130,74 142,66 152,58 162,62 172,66 180,56 186,46';
|
|
||||||
const STAYS: Array<[number, number]> = [[130, 74], [186, 46]];
|
|
||||||
|
|
||||||
function DawarichVisual() {
|
|
||||||
return (
|
|
||||||
<div className="rn-vis rn-vis-trail">
|
|
||||||
<svg viewBox="0 0 200 112" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
|
|
||||||
<polyline className="rn-vis-trail-line" points={TRAIL} />
|
|
||||||
{STAYS.map(([x, y]) => <circle key={x} className="rn-vis-trail-stay" cx={x} cy={y} r="3.4" />)}
|
|
||||||
</svg>
|
|
||||||
<span className="rn-vis-brand"><DawarichIcon size={58} /></span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// A trip's documents travelling both ways between TREK and the five stores. The
|
|
||||||
// wordmark without the API pill: this is TREK itself, not its index.
|
|
||||||
const STORES = [PaperlessIcon, PapraIcon, NextcloudIcon, OpenCloudIcon, SynologyDriveIcon];
|
|
||||||
|
|
||||||
function DocSyncVisual() {
|
|
||||||
return (
|
|
||||||
<div className="rn-vis rn-vis-docs">
|
|
||||||
<span className="rn-vis-trekbadge"><TrekMark pill={false} className="rn-vis-trekmark" /></span>
|
|
||||||
<span className="rn-vis-docs-flow"><ArrowLeftRight size={14} strokeWidth={2.4} /></span>
|
|
||||||
<div className="rn-vis-docs-stores">
|
|
||||||
{STORES.map((Store, i) => (
|
|
||||||
<span key={i} className="rn-vis-docs-store"><Store size={22} /></span>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── TREK Studio: an open photo book with a polaroid, a stamp and a sticker ──
|
||||||
|
|
||||||
|
function StudioVisual() {
|
||||||
|
return (
|
||||||
|
<div className="rn-vis rn-vis-studio">
|
||||||
|
<div className="rn-vis-book">
|
||||||
|
<div className="rn-vis-page rn-vis-page-start">
|
||||||
|
<div className="rn-vis-polaroid">
|
||||||
|
<svg viewBox="0 0 60 44" aria-hidden="true">
|
||||||
|
<rect className="rn-vis-sky" width="60" height="44" />
|
||||||
|
<circle className="rn-vis-sun" cx="42" cy="15" r="6" />
|
||||||
|
<path className="rn-vis-peak-far" d="M0 32 L12 20 L20 26 L32 12 L44 24 L52 18 L60 26 V44 H0 Z" />
|
||||||
|
<path className="rn-vis-peak-near" d="M0 38 L14 28 L26 34 L38 26 L60 36 V44 H0 Z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<span className="rn-vis-tape" />
|
||||||
|
</div>
|
||||||
|
<div className="rn-vis-page rn-vis-page-end">
|
||||||
|
<span className="rn-vis-book-title">Dolomiti</span>
|
||||||
|
<span className="rn-vis-book-line" />
|
||||||
|
<span className="rn-vis-book-line rn-vis-book-line-short" />
|
||||||
|
<span className="rn-vis-stamp">
|
||||||
|
<Plane size={10} strokeWidth={2.2} />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span className="rn-vis-gutter" />
|
||||||
|
</div>
|
||||||
|
<span className="rn-vis-sticker">
|
||||||
|
<Star size={15} strokeWidth={1.8} />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── The assistant: a day in Porto proposed stop by stop, ready to apply ──
|
||||||
|
|
||||||
|
const PORTO: Array<{ time: string; name: string; tone: string }> = [
|
||||||
|
{ time: '09:30', name: 'Ribeira', tone: 'sight' },
|
||||||
|
{ time: '12:30', name: 'Livraria Lello', tone: 'culture' },
|
||||||
|
{ time: '16:00', name: 'Torre dos Clérigos', tone: 'view' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function AssistantVisual() {
|
||||||
|
return (
|
||||||
|
<div className="rn-vis rn-vis-assist">
|
||||||
|
<div className="rn-vis-assist-head">
|
||||||
|
<span className="rn-vis-assist-avatar">
|
||||||
|
<Sparkles size={10} strokeWidth={2.4} />
|
||||||
|
</span>
|
||||||
|
<span className="rn-vis-assist-typing">
|
||||||
|
<i />
|
||||||
|
<i />
|
||||||
|
<i />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="rn-vis-assist-card">
|
||||||
|
{PORTO.map((stop, i) => (
|
||||||
|
<div key={stop.name} className="rn-vis-assist-row" style={{ animationDelay: `${0.5 + i * 0.35}s` }}>
|
||||||
|
<span className="rn-vis-assist-time">{stop.time}</span>
|
||||||
|
<span className={`rn-vis-assist-dot rn-vis-assist-dot-${stop.tone}`} />
|
||||||
|
<span className="rn-vis-assist-name">{stop.name}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<span className="rn-vis-assist-apply">
|
||||||
|
<Check size={11} strokeWidth={3} />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Help on every screen, in 27 languages: hello in each of them, drifting by ──
|
||||||
|
|
||||||
|
const HELLO_A = ['Hallo', 'Bonjour', 'Hola', 'Ciao', 'Olá', 'Hej', 'Ahoj', 'Cześć', 'Szia', 'Tere', 'Salam', 'Bon dia', 'Halo'];
|
||||||
|
const HELLO_B = ['Привіт', 'Привет', 'Γεια σου', 'مرحبا', 'こんにちは', '안녕하세요', '你好', '哈囉', 'สวัสดี', 'Xin chào', 'Merhaba', 'Dobrý deň'];
|
||||||
|
|
||||||
|
function HelloRow({ words, reverse }: { words: string[]; reverse?: boolean }) {
|
||||||
|
// Written twice, so the row can slide by half its width and start over without a seam.
|
||||||
|
return (
|
||||||
|
<div className={reverse ? 'rn-vis-hello-row rn-vis-hello-row-reverse' : 'rn-vis-hello-row'}>
|
||||||
|
{[...words, ...words].map((word, i) => (
|
||||||
|
<span key={i} className="rn-vis-hello" lang="und">
|
||||||
|
{word}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function HelpVisual() {
|
||||||
|
return (
|
||||||
|
<div className="rn-vis rn-vis-help">
|
||||||
|
<span className="rn-vis-help-q">?</span>
|
||||||
|
<div className="rn-vis-help-langs">
|
||||||
|
<HelloRow words={HELLO_A} />
|
||||||
|
<HelloRow words={HELLO_B} reverse />
|
||||||
|
</div>
|
||||||
|
<span className="rn-vis-help-count">27</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const VISUALS: Record<string, () => React.ReactElement> = {
|
const VISUALS: Record<string, () => React.ReactElement> = {
|
||||||
'places-api': PlacesApiVisual,
|
tours: ToursVisual,
|
||||||
roadtrip: RoadtripVisual,
|
studio: StudioVisual,
|
||||||
dawarich: DawarichVisual,
|
assistant: AssistantVisual,
|
||||||
docsync: DocSyncVisual,
|
help: HelpVisual,
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The card's picture, or its icon when the release names no drawing this client knows. */
|
/** The card's picture, or its icon when the release names no drawing this client knows. */
|
||||||
|
|||||||
@@ -380,223 +380,6 @@
|
|||||||
flex: none;
|
flex: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── The card pictures ─────────────────────────────────────────────────── */
|
|
||||||
|
|
||||||
.rn-vis {
|
|
||||||
position: absolute;
|
|
||||||
inset: 0;
|
|
||||||
color: #f5f5f7;
|
|
||||||
font-family: var(--font-system);
|
|
||||||
}
|
|
||||||
|
|
||||||
.rn-vis-road > svg,
|
|
||||||
.rn-vis-trail > svg { position: absolute; inset: 0; width: 100%; height: 100%; }
|
|
||||||
|
|
||||||
.rn-vis-icon {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
color: oklch(1 0 0 / 0.55);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Places API: the index answering a search while it is typed. */
|
|
||||||
.rn-vis-places {
|
|
||||||
padding: 9px 12px;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 6px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* The same wordmark the API keys card leads with, centred; its pill text inverts against the tile. */
|
|
||||||
.rn-vis-trekbadge { align-self: center; display: flex; align-items: center; height: 24px; }
|
|
||||||
|
|
||||||
.rn-vis-trekmark { display: block; height: 20px; width: auto; color: #f5f5f7; }
|
|
||||||
|
|
||||||
.rn-vis-places .trek-mark .pill-fg { fill: #101013; }
|
|
||||||
|
|
||||||
.rn-vis-search {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
height: 22px;
|
|
||||||
padding: 0 9px;
|
|
||||||
border-radius: 8px;
|
|
||||||
background: oklch(1 0 0 / 0.08);
|
|
||||||
border: 1px solid oklch(1 0 0 / 0.16);
|
|
||||||
font-size: 10px;
|
|
||||||
font-weight: 500;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rn-vis-search svg { width: 11px; height: 11px; flex: none; color: oklch(1 0 0 / 0.55); }
|
|
||||||
|
|
||||||
/* The query types itself out once, then the answer arrives under it. */
|
|
||||||
.rn-vis-typed {
|
|
||||||
display: inline-block;
|
|
||||||
max-width: 90px;
|
|
||||||
overflow: hidden;
|
|
||||||
white-space: nowrap;
|
|
||||||
animation: rn-type 1.3s steps(13, end) 0.7s both;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes rn-type { from { max-width: 0; } to { max-width: 90px; } }
|
|
||||||
|
|
||||||
.rn-vis-caret {
|
|
||||||
width: 1px;
|
|
||||||
height: 12px;
|
|
||||||
margin-inline-start: -4px;
|
|
||||||
background: #f5f5f7;
|
|
||||||
animation: rn-caret 1s steps(1) infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes rn-caret { 50% { opacity: 0; } }
|
|
||||||
|
|
||||||
.rn-vis-result {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 7px;
|
|
||||||
padding: 5px 8px;
|
|
||||||
border-radius: 8px;
|
|
||||||
background: oklch(1 0 0 / 0.07);
|
|
||||||
animation: rn-answer 0.3s ease 2.1s both;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes rn-answer { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: none; } }
|
|
||||||
|
|
||||||
.rn-vis-cat {
|
|
||||||
width: 18px;
|
|
||||||
height: 18px;
|
|
||||||
border-radius: 50%;
|
|
||||||
border: 1.5px solid #ffffff;
|
|
||||||
color: #ffffff;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
flex: none;
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rn-vis-place { display: flex; flex-direction: column; min-width: 0; line-height: 1.2; }
|
|
||||||
|
|
||||||
.rn-vis-place span {
|
|
||||||
font-size: 10px;
|
|
||||||
font-weight: 600;
|
|
||||||
white-space: nowrap;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rn-vis-place small { font-size: 8.5px; color: oklch(1 0 0 / 0.5); }
|
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
|
||||||
.rn-vis-typed, .rn-vis-caret, .rn-vis-result { animation: none; }
|
|
||||||
}
|
|
||||||
|
|
||||||
[data-reduce-motion='true'] .rn-vis-typed,
|
|
||||||
[data-reduce-motion='true'] .rn-vis-caret,
|
|
||||||
[data-reduce-motion='true'] .rn-vis-result { animation: none; }
|
|
||||||
|
|
||||||
/* Road trip: the drive on the map, in the planner's route blue and marker style. */
|
|
||||||
.rn-vis-road-casing { fill: none; stroke: #0a5cc2; stroke-width: 5; stroke-linecap: round; stroke-linejoin: round; }
|
|
||||||
|
|
||||||
.rn-vis-road-line { fill: none; stroke: #0a84ff; stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
|
|
||||||
|
|
||||||
.rn-vis-marker {
|
|
||||||
position: absolute;
|
|
||||||
width: 18px;
|
|
||||||
height: 18px;
|
|
||||||
margin: -9px 0 0 -9px;
|
|
||||||
border-radius: 50%;
|
|
||||||
border: 2px solid #ffffff;
|
|
||||||
box-sizing: border-box;
|
|
||||||
box-shadow: 0 1px 4px oklch(0 0 0 / 0.35);
|
|
||||||
color: #ffffff;
|
|
||||||
font-size: 8.5px;
|
|
||||||
font-weight: 700;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
font-variant-numeric: tabular-nums;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rn-vis-distance {
|
|
||||||
position: absolute;
|
|
||||||
right: 9px;
|
|
||||||
bottom: 8px;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 4px;
|
|
||||||
padding: 2px 7px;
|
|
||||||
border-radius: 99px;
|
|
||||||
background: #f5f5f7;
|
|
||||||
color: #101013;
|
|
||||||
font-size: 9px;
|
|
||||||
font-weight: 600;
|
|
||||||
white-space: nowrap;
|
|
||||||
font-variant-numeric: tabular-nums;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Dawarich: a recorded day, in the trail colour the map draws it with. */
|
|
||||||
.rn-vis-trail-line { fill: none; stroke: #2563eb; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; }
|
|
||||||
|
|
||||||
.rn-vis-trail-stay { fill: #ffffff; stroke: #2563eb; stroke-width: 2; }
|
|
||||||
|
|
||||||
/* Document sync: the wordmark, the two-way arrow under it, and the five stores in a row. */
|
|
||||||
.rn-vis-docs {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
gap: 4px;
|
|
||||||
padding: 8px 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rn-vis-docs .rn-vis-trekbadge { height: 22px; }
|
|
||||||
.rn-vis-docs .rn-vis-trekmark { height: 19px; }
|
|
||||||
|
|
||||||
.rn-vis-docs-flow { display: flex; color: oklch(1 0 0 / 0.55); transform: rotate(90deg); }
|
|
||||||
|
|
||||||
.rn-vis-docs-stores {
|
|
||||||
display: flex;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rn-vis-docs-store {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
width: 34px;
|
|
||||||
height: 34px;
|
|
||||||
border-radius: 10px;
|
|
||||||
background: oklch(1 0 0 / 0.1);
|
|
||||||
box-shadow: inset 0 1px 0 oklch(1 0 0 / 0.18), inset 0 0 0 1px oklch(1 0 0 / 0.1);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* The mark itself, unframed, with its corners rounded like an app icon. */
|
|
||||||
.rn-vis-brand {
|
|
||||||
position: absolute;
|
|
||||||
top: 12px;
|
|
||||||
left: 12px;
|
|
||||||
width: 58px;
|
|
||||||
height: 58px;
|
|
||||||
border-radius: 15px;
|
|
||||||
overflow: hidden;
|
|
||||||
box-shadow: 0 4px 14px oklch(0 0 0 / 0.45), 0 0 0 1px oklch(1 0 0 / 0.14);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* A glass sheen over the mark: a soft light from the top and a bright inner edge. */
|
|
||||||
.rn-vis-brand::after {
|
|
||||||
content: '';
|
|
||||||
position: absolute;
|
|
||||||
inset: 0;
|
|
||||||
border-radius: inherit;
|
|
||||||
background: linear-gradient(160deg, oklch(1 0 0 / 0.42) 0%, oklch(1 0 0 / 0.08) 38%, transparent 55%, oklch(0 0 0 / 0.12) 100%);
|
|
||||||
box-shadow: inset 0 1px 0 oklch(1 0 0 / 0.55), inset 0 0 0 1px oklch(1 0 0 / 0.22);
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rn-vis-brand img { display: block; width: 100%; height: 100%; }
|
|
||||||
|
|
||||||
/* ── Right: the note ───────────────────────────────────────────────────── */
|
/* ── Right: the note ───────────────────────────────────────────────────── */
|
||||||
|
|
||||||
.rn-note {
|
.rn-note {
|
||||||
|
|||||||
@@ -0,0 +1,582 @@
|
|||||||
|
/*
|
||||||
|
* The pictures on the release cards (ReleaseNoticeVisuals.tsx). They sit on the
|
||||||
|
* release half, which is dark in both themes, so they draw in their own colours
|
||||||
|
* rather than the surface tokens, like the panel around them.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* ── The card pictures ─────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
.rn-vis {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
color: #f5f5f7;
|
||||||
|
font-family: var(--font-system);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-icon {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
color: oklch(1 0 0 / 0.55);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes rn-draw {
|
||||||
|
to {
|
||||||
|
stroke-dashoffset: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes rn-pop {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: scale(0.2);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes rn-rise {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(4px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes rn-typing {
|
||||||
|
0%,
|
||||||
|
60%,
|
||||||
|
100% {
|
||||||
|
opacity: 0.35;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
30% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(-2px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes rn-ring {
|
||||||
|
0% {
|
||||||
|
box-shadow: 0 0 0 0 oklch(0.72 0.19 150 / 0.55);
|
||||||
|
}
|
||||||
|
70%,
|
||||||
|
100% {
|
||||||
|
box-shadow: 0 0 0 9px oklch(0.72 0.19 150 / 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes rn-marquee {
|
||||||
|
from {
|
||||||
|
transform: translateX(0);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
transform: translateX(-50%);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes rn-sticker {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: scale(0.2) rotate(-50deg);
|
||||||
|
}
|
||||||
|
70% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: scale(1.12) rotate(12deg);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: rotate(8deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tours: a trail climbing to the summit at dusk, and the kinds of tour along the foot. */
|
||||||
|
.rn-vis-tours {
|
||||||
|
background: linear-gradient(180deg, #24304f 0%, #3c4a6b 46%, #c9876a 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-scene {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-sun {
|
||||||
|
fill: #fde68a;
|
||||||
|
filter: drop-shadow(0 0 6px oklch(0.92 0.12 90 / 0.7));
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-far {
|
||||||
|
fill: #56668a;
|
||||||
|
opacity: 0.75;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-mountain {
|
||||||
|
fill: #23344a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-snow {
|
||||||
|
fill: #e8f0f8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-meadow {
|
||||||
|
fill: #14202d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-trail {
|
||||||
|
fill: none;
|
||||||
|
stroke: #fbbf24;
|
||||||
|
stroke-width: 2;
|
||||||
|
stroke-linecap: round;
|
||||||
|
stroke-linejoin: round;
|
||||||
|
stroke-dasharray: 1;
|
||||||
|
stroke-dashoffset: 1;
|
||||||
|
filter: drop-shadow(0 0 2px oklch(0.85 0.16 80 / 0.6));
|
||||||
|
animation: rn-draw 1.3s ease-in-out 0.3s both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-walker {
|
||||||
|
fill: #ffffff;
|
||||||
|
filter: drop-shadow(0 0 3px #ffffff);
|
||||||
|
opacity: 0;
|
||||||
|
animation: rn-show 0.2s linear 1.6s both;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes rn-show {
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-flag {
|
||||||
|
transform-box: fill-box;
|
||||||
|
transform-origin: 0% 100%;
|
||||||
|
animation: rn-pop 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) 1.5s both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-flag line {
|
||||||
|
stroke: #f5f5f7;
|
||||||
|
stroke-width: 1.2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-flag path {
|
||||||
|
fill: #ef4444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-climb {
|
||||||
|
position: absolute;
|
||||||
|
top: 8px;
|
||||||
|
inset-inline-start: 9px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 3px;
|
||||||
|
padding: 2px 7px;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: oklch(1 0 0 / 0.14);
|
||||||
|
border: 1px solid oklch(1 0 0 / 0.18);
|
||||||
|
backdrop-filter: blur(6px);
|
||||||
|
font-size: 9px;
|
||||||
|
font-weight: 700;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-kinds {
|
||||||
|
position: absolute;
|
||||||
|
inset-inline: 0;
|
||||||
|
bottom: 7px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tours-kind {
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: oklch(1 0 0 / 0.12);
|
||||||
|
border: 1px solid oklch(1 0 0 / 0.2);
|
||||||
|
backdrop-filter: blur(6px);
|
||||||
|
animation: rn-rise 0.3s ease both;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* TREK Studio: an open book, a polaroid taped in, a title, a stamp and a sticker. */
|
||||||
|
.rn-vis-studio {
|
||||||
|
background:
|
||||||
|
radial-gradient(120% 90% at 50% 115%, oklch(0.62 0.14 45 / 0.38) 0%, transparent 60%),
|
||||||
|
linear-gradient(165deg, #23201c 0%, #171513 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-book {
|
||||||
|
position: absolute;
|
||||||
|
inset: 13px 20px 13px;
|
||||||
|
display: flex;
|
||||||
|
border-radius: 3px;
|
||||||
|
overflow: hidden;
|
||||||
|
transform: perspective(520px) rotateX(16deg);
|
||||||
|
box-shadow:
|
||||||
|
0 16px 22px -10px oklch(0 0 0 / 0.75),
|
||||||
|
0 0 0 1px oklch(1 0 0 / 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-page {
|
||||||
|
position: relative;
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.rn-vis-page-start {
|
||||||
|
background: #ede2c9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-page-end {
|
||||||
|
background: #f6eedc;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 11px 9px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-gutter {
|
||||||
|
position: absolute;
|
||||||
|
inset-block: 0;
|
||||||
|
inset-inline-start: 50%;
|
||||||
|
width: 16px;
|
||||||
|
margin-inline-start: -8px;
|
||||||
|
background: linear-gradient(90deg, transparent, oklch(0 0 0 / 0.2), transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-polaroid {
|
||||||
|
position: absolute;
|
||||||
|
top: 11px;
|
||||||
|
inset-inline-start: 10px;
|
||||||
|
width: 58%;
|
||||||
|
padding: 3px 3px 9px;
|
||||||
|
background: #ffffff;
|
||||||
|
transform: rotate(-6deg);
|
||||||
|
box-shadow: 0 3px 6px oklch(0 0 0 / 0.25);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-polaroid svg {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
.rn-vis-sky {
|
||||||
|
fill: #fcd5b0;
|
||||||
|
}
|
||||||
|
.rn-vis-sun {
|
||||||
|
fill: #fb923c;
|
||||||
|
}
|
||||||
|
.rn-vis-peak-far {
|
||||||
|
fill: #7c8aa0;
|
||||||
|
}
|
||||||
|
.rn-vis-peak-near {
|
||||||
|
fill: #334155;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-tape {
|
||||||
|
position: absolute;
|
||||||
|
top: 7px;
|
||||||
|
inset-inline-start: 30%;
|
||||||
|
width: 24px;
|
||||||
|
height: 7px;
|
||||||
|
transform: rotate(-24deg);
|
||||||
|
background: repeating-linear-gradient(45deg, #f43f5e 0 3px, #fecdd3 3px 6px);
|
||||||
|
opacity: 0.88;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-book-title {
|
||||||
|
font-family: Georgia, 'Times New Roman', serif;
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1;
|
||||||
|
color: #1f3d2b;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-book-line {
|
||||||
|
height: 3px;
|
||||||
|
width: 88%;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: oklch(0.4 0.03 60 / 0.3);
|
||||||
|
}
|
||||||
|
.rn-vis-book-line-short {
|
||||||
|
width: 58%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-stamp {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 9px;
|
||||||
|
inset-inline-end: 9px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 1.5px dashed #b45309;
|
||||||
|
color: #b45309;
|
||||||
|
transform: rotate(-14deg);
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-sticker {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 7px;
|
||||||
|
inset-inline-start: 14px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 26px;
|
||||||
|
height: 26px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #facc15;
|
||||||
|
color: #fff8db;
|
||||||
|
box-shadow:
|
||||||
|
0 0 0 2px #ffffff,
|
||||||
|
0 4px 10px oklch(0 0 0 / 0.4);
|
||||||
|
animation: rn-sticker 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) 1s both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-sticker svg {
|
||||||
|
fill: currentColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The assistant: a day in Porto proposed stop by stop, and the button that applies it. */
|
||||||
|
.rn-vis-assist {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 9px 10px;
|
||||||
|
background:
|
||||||
|
radial-gradient(110% 80% at 0% 0%, oklch(0.55 0.2 290 / 0.36) 0%, transparent 62%),
|
||||||
|
linear-gradient(165deg, #1d1b29 0%, #141320 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-assist-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-assist-avatar {
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 19px;
|
||||||
|
height: 19px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: linear-gradient(135deg, #a78bfa 0%, #3b82f6 100%);
|
||||||
|
color: #ffffff;
|
||||||
|
box-shadow: 0 2px 8px oklch(0.55 0.2 290 / 0.6);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-assist-typing {
|
||||||
|
display: flex;
|
||||||
|
gap: 3px;
|
||||||
|
padding: 5px 7px;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: oklch(1 0 0 / 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-assist-typing i {
|
||||||
|
width: 4px;
|
||||||
|
height: 4px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #f5f5f7;
|
||||||
|
animation: rn-typing 1.2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-assist-typing i:nth-child(2) {
|
||||||
|
animation-delay: 0.15s;
|
||||||
|
}
|
||||||
|
.rn-vis-assist-typing i:nth-child(3) {
|
||||||
|
animation-delay: 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-assist-card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
padding: 5px 8px;
|
||||||
|
border-radius: 9px;
|
||||||
|
background: oklch(1 0 0 / 0.08);
|
||||||
|
border: 1px solid oklch(1 0 0 / 0.14);
|
||||||
|
box-shadow: inset 0 1px 0 oklch(1 0 0 / 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-assist-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
font-size: 9.5px;
|
||||||
|
line-height: 1.35;
|
||||||
|
animation: rn-rise 0.34s ease both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-assist-time {
|
||||||
|
flex: none;
|
||||||
|
width: 27px;
|
||||||
|
color: oklch(1 0 0 / 0.5);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.rn-vis-assist-dot {
|
||||||
|
flex: none;
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
.rn-vis-assist-dot-sight {
|
||||||
|
background: #f59e0b;
|
||||||
|
}
|
||||||
|
.rn-vis-assist-dot-culture {
|
||||||
|
background: #a78bfa;
|
||||||
|
}
|
||||||
|
.rn-vis-assist-dot-view {
|
||||||
|
background: #34d399;
|
||||||
|
}
|
||||||
|
.rn-vis-assist-name {
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-assist-apply {
|
||||||
|
position: absolute;
|
||||||
|
top: 8px;
|
||||||
|
inset-inline-end: 9px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #22c55e;
|
||||||
|
color: #ffffff;
|
||||||
|
animation:
|
||||||
|
rn-pop 0.3s cubic-bezier(0.34, 1.56, 0.64, 1) 1.7s both,
|
||||||
|
rn-ring 2.2s ease-out 2s infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Help on every screen: the help button, and hello in TREK's languages drifting past it. */
|
||||||
|
.rn-vis-help {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 0 12px;
|
||||||
|
background:
|
||||||
|
radial-gradient(70% 120% at 10% 50%, oklch(0.6 0.16 250 / 0.34) 0%, transparent 70%),
|
||||||
|
linear-gradient(165deg, #1a1f2b 0%, #12151d 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-help-q {
|
||||||
|
position: relative;
|
||||||
|
flex: none;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 42px;
|
||||||
|
height: 42px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #f5f5f7;
|
||||||
|
color: #101013;
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 800;
|
||||||
|
box-shadow:
|
||||||
|
0 0 0 5px oklch(1 0 0 / 0.08),
|
||||||
|
0 6px 16px oklch(0 0 0 / 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-help-count {
|
||||||
|
position: absolute;
|
||||||
|
top: 12px;
|
||||||
|
inset-inline-start: 42px;
|
||||||
|
padding: 1px 6px;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: #3b82f6;
|
||||||
|
color: #ffffff;
|
||||||
|
font-size: 9.5px;
|
||||||
|
font-weight: 800;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
box-shadow: 0 0 0 2px #12151d;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The rows slide the same way in every language: they are a picture, not text. */
|
||||||
|
.rn-vis-help-langs {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
overflow: hidden;
|
||||||
|
direction: ltr;
|
||||||
|
-webkit-mask-image: linear-gradient(90deg, transparent 0%, #000 14%, #000 86%, transparent 100%);
|
||||||
|
mask-image: linear-gradient(90deg, transparent 0%, #000 14%, #000 86%, transparent 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-hello-row {
|
||||||
|
display: flex;
|
||||||
|
width: max-content;
|
||||||
|
animation: rn-marquee 34s linear infinite;
|
||||||
|
}
|
||||||
|
.rn-vis-hello-row-reverse {
|
||||||
|
animation-direction: reverse;
|
||||||
|
animation-duration: 40s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rn-vis-hello {
|
||||||
|
flex: none;
|
||||||
|
margin-inline-end: 5px;
|
||||||
|
padding: 3px 8px;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: oklch(1 0 0 / 0.09);
|
||||||
|
border: 1px solid oklch(1 0 0 / 0.13);
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.rn-vis-tours-trail,
|
||||||
|
.rn-vis-tours-flag,
|
||||||
|
.rn-vis-tours-kind,
|
||||||
|
.rn-vis-sticker,
|
||||||
|
.rn-vis-assist-typing i,
|
||||||
|
.rn-vis-assist-row,
|
||||||
|
.rn-vis-assist-apply,
|
||||||
|
.rn-vis-hello-row {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
.rn-vis-tours-trail {
|
||||||
|
stroke-dashoffset: 0;
|
||||||
|
}
|
||||||
|
.rn-vis-tours-walker {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.rn-vis-sticker {
|
||||||
|
transform: rotate(8deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-reduce-motion='true'] .rn-vis-tours-trail,
|
||||||
|
[data-reduce-motion='true'] .rn-vis-tours-flag,
|
||||||
|
[data-reduce-motion='true'] .rn-vis-tours-kind,
|
||||||
|
[data-reduce-motion='true'] .rn-vis-sticker,
|
||||||
|
[data-reduce-motion='true'] .rn-vis-assist-typing i,
|
||||||
|
[data-reduce-motion='true'] .rn-vis-assist-row,
|
||||||
|
[data-reduce-motion='true'] .rn-vis-assist-apply,
|
||||||
|
[data-reduce-motion='true'] .rn-vis-hello-row {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-reduce-motion='true'] .rn-vis-tours-trail {
|
||||||
|
stroke-dashoffset: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-reduce-motion='true'] .rn-vis-tours-walker {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-reduce-motion='true'] .rn-vis-sticker {
|
||||||
|
transform: rotate(8deg);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// FE-GPX-PREVIEW-001 to FE-GPX-PREVIEW-003
|
// FE-GPX-PREVIEW-001 to FE-GPX-PREVIEW-004
|
||||||
// The GPX preview as ACT-01 uses it: preset to the tour's type, a city walk
|
// The GPX preview as ACT-01 uses it: preset to the tour's type, a city walk
|
||||||
// imported as one, and when a track was recorded shown where it carried times.
|
// imported as one, and when a track was recorded shown where it carried times.
|
||||||
import { fireEvent, render, screen } from '@testing-library/react';
|
import { fireEvent, render, screen } from '@testing-library/react';
|
||||||
@@ -47,6 +47,13 @@ describe('TourGpxPreviewDialog (ACT-01)', () => {
|
|||||||
expect(recorded[0]).toHaveTextContent('50 min');
|
expect(recorded[0]).toHaveTextContent('50 min');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('FE-GPX-PREVIEW-004: a track taken over from before Tours reads as one, not as a duplicate (#2810)', () => {
|
||||||
|
render(<TourGpxPreviewDialog gpxImport={gpxImport([track({ adopts_track: true })])} />);
|
||||||
|
expect(screen.getByTestId('gpx-preview-track')).not.toHaveAttribute('data-duplicate');
|
||||||
|
expect(screen.getByText(/tours\.import\.previewAdopts|becomes a tour/)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText(/tours\.import\.previewDuplicate|Already in the trip/)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it('FE-GPX-PREVIEW-002: imports as the preset type, a paddle tour with its boat and water', () => {
|
it('FE-GPX-PREVIEW-002: imports as the preset type, a paddle tour with its boat and water', () => {
|
||||||
const current = gpxImport([track()]);
|
const current = gpxImport([track()]);
|
||||||
render(
|
render(
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ function PreviewTrackRow({
|
|||||||
{track.name || name}
|
{track.name || name}
|
||||||
</span>
|
</span>
|
||||||
{track.duplicate && <SoftPill tone="warning">{t('tours.import.previewDuplicate')}</SoftPill>}
|
{track.duplicate && <SoftPill tone="warning">{t('tours.import.previewDuplicate')}</SoftPill>}
|
||||||
|
{track.adopts_track && <SoftPill>{t('tours.import.previewAdopts')}</SoftPill>}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap items-center gap-1.5 ps-8" style={fs(11)}>
|
<div className="flex flex-wrap items-center gap-1.5 ps-8" style={fs(11)}>
|
||||||
<span className={BADGE}>{formatDistance(track.distance_km, unit)}</span>
|
<span className={BADGE}>{formatDistance(track.distance_km, unit)}</span>
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
import { describe, it, expect } from 'vitest'
|
import { describe, it, expect } from 'vitest'
|
||||||
import { DOCUMENT_PROVIDER_IDS } from '@trek/shared'
|
import { DOCUMENT_PROVIDER_IDS } from '@trek/shared'
|
||||||
import { render } from '../../../tests/helpers/render'
|
import { render } from '../../../tests/helpers/render'
|
||||||
import { DOCUMENT_PROVIDER_ICONS } from './DocumentProviderIcons'
|
import { DOCUMENT_PROVIDER_ICONS } from './documentProviderIconMap'
|
||||||
import TrekIcon from './TrekIcon'
|
import TrekIcon from './TrekIcon'
|
||||||
|
|
||||||
const marks = Object.entries(DOCUMENT_PROVIDER_ICONS)
|
const marks = Object.entries(DOCUMENT_PROVIDER_ICONS)
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import React from 'react'
|
|||||||
* for legibility in a monochrome row.
|
* for legibility in a monochrome row.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
interface GlyphProps {
|
export interface GlyphProps {
|
||||||
size?: number
|
size?: number
|
||||||
className?: string
|
className?: string
|
||||||
}
|
}
|
||||||
@@ -126,12 +126,3 @@ export function SynologyDriveIcon({ size = 20, className }: GlyphProps): React.R
|
|||||||
</svg>
|
</svg>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Keyed by the provider ids in `document_providers`. */
|
|
||||||
export const DOCUMENT_PROVIDER_ICONS: Record<string, React.ComponentType<GlyphProps>> = {
|
|
||||||
paperless: PaperlessIcon,
|
|
||||||
papra: PapraIcon,
|
|
||||||
nextcloud: NextcloudIcon,
|
|
||||||
opencloud: OpenCloudIcon,
|
|
||||||
synologydrive: SynologyDriveIcon,
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import type React from 'react';
|
||||||
|
import {
|
||||||
|
type GlyphProps,
|
||||||
|
NextcloudIcon,
|
||||||
|
OpenCloudIcon,
|
||||||
|
PaperlessIcon,
|
||||||
|
PapraIcon,
|
||||||
|
SynologyDriveIcon,
|
||||||
|
} from './DocumentProviderIcons';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The document providers' marks keyed by the provider ids in `document_providers`.
|
||||||
|
* Kept apart from the drawings so that module exports components only.
|
||||||
|
*/
|
||||||
|
export const DOCUMENT_PROVIDER_ICONS: Record<string, React.ComponentType<GlyphProps>> = {
|
||||||
|
paperless: PaperlessIcon,
|
||||||
|
papra: PapraIcon,
|
||||||
|
nextcloud: NextcloudIcon,
|
||||||
|
opencloud: OpenCloudIcon,
|
||||||
|
synologydrive: SynologyDriveIcon,
|
||||||
|
};
|
||||||
@@ -70,6 +70,19 @@ interface CachedTourDraft {
|
|||||||
draft: TourDraft;
|
draft: TourDraft;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A road route as the router answered it, kept on the device so a trip opens
|
||||||
|
* with its roads drawn instead of asking the router for every leg again (#2794).
|
||||||
|
* `key` is RouteCalculator's cache key (profile, unit, waypoints, avoided
|
||||||
|
* roads), `route` its answer as it came, `savedAt` when it came: an old answer
|
||||||
|
* is asked again, and the oldest give way first.
|
||||||
|
*/
|
||||||
|
interface CachedRoute {
|
||||||
|
key: string;
|
||||||
|
route: unknown;
|
||||||
|
savedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
// ── Queue + sync types ────────────────────────────────────────────────────────
|
// ── Queue + sync types ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
// 'conflict' is terminal-until-resolved: the server rejected the replay because
|
// 'conflict' is terminal-until-resolved: the server rejected the replay because
|
||||||
@@ -279,6 +292,7 @@ export class TrekOfflineDb extends Dexie {
|
|||||||
ferrataTiles!: Table<CachedFerrataTile, [number, string]>;
|
ferrataTiles!: Table<CachedFerrataTile, [number, string]>;
|
||||||
tourStationVisits!: Table<CachedTourStationVisit, [number, string]>;
|
tourStationVisits!: Table<CachedTourStationVisit, [number, string]>;
|
||||||
tourDrafts!: Table<CachedTourDraft, number>;
|
tourDrafts!: Table<CachedTourDraft, number>;
|
||||||
|
routeCache!: Table<CachedRoute, string>;
|
||||||
|
|
||||||
constructor(name: string = ANON_DB_NAME) {
|
constructor(name: string = ANON_DB_NAME) {
|
||||||
super(name);
|
super(name);
|
||||||
@@ -366,6 +380,11 @@ export class TrekOfflineDb extends Dexie {
|
|||||||
// v13: the Tours planner's unsaved draft as the account last said it, one
|
// v13: the Tours planner's unsaved draft as the account last said it, one
|
||||||
// per trip (the database is the signed-in user's own), so it opens offline.
|
// per trip (the database is the signed-in user's own), so it opens offline.
|
||||||
this.version(13).stores({ tourDrafts: 'tripId' });
|
this.version(13).stores({ tourDrafts: 'tripId' });
|
||||||
|
|
||||||
|
// v14: road routes the router answered, by their cache key, so a trip with its
|
||||||
|
// whole route shown opens drawn instead of re-routing every leg (#2794). Not per
|
||||||
|
// trip: the same waypoints are the same road in any trip; `savedAt` to prune.
|
||||||
|
this.version(14).stores({ routeCache: 'key, savedAt' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import DawarichIcon from '../../../components/shared/DawarichIcon'
|
import DawarichIcon from '../../../components/shared/DawarichIcon'
|
||||||
import AirTrailIcon from '../../../components/shared/AirTrailIcon'
|
import AirTrailIcon from '../../../components/shared/AirTrailIcon'
|
||||||
import { DOCUMENT_PROVIDER_ICONS } from '../../../components/shared/DocumentProviderIcons'
|
import { DOCUMENT_PROVIDER_ICONS } from '../../../components/shared/documentProviderIconMap'
|
||||||
import MToggle from '../../components/MToggle'
|
import MToggle from '../../components/MToggle'
|
||||||
import {
|
import {
|
||||||
type Addon,
|
type Addon,
|
||||||
|
|||||||
@@ -294,7 +294,7 @@ export default function MAdminPluginsPanel() {
|
|||||||
{bypass.copy && (
|
{bypass.copy && (
|
||||||
<MConfirmSheet open onClose={bypass.dismiss} onConfirm={bypass.copy.confirm ? bypass.confirm : undefined}
|
<MConfirmSheet open onClose={bypass.dismiss} onConfirm={bypass.copy.confirm ? bypass.confirm : undefined}
|
||||||
title={bypass.copy.title} message={bypass.copy.body}
|
title={bypass.copy.title} message={bypass.copy.body}
|
||||||
confirmLabel={t('admin.plugins.installAnyway')} cancelLabel={bypass.copy.confirm ? t('common.cancel') : t('common.ok')} danger />
|
confirmLabel={bypass.copy.confirmLabel} cancelLabel={bypass.copy.confirm ? t('common.cancel') : t('common.ok')} danger />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Row ⋯ action sheet */}
|
{/* Row ⋯ action sheet */}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { useCallback, useEffect, useMemo } from 'react';
|
import { useCallback, useMemo } from 'react';
|
||||||
import { useMatch, useNavigate } from 'react-router';
|
import { useMatch, useNavigate } from 'react-router';
|
||||||
|
|
||||||
import type { AssistantChatTrip } from '../../../components/Assistant/assistantViewContext';
|
import type { AssistantChatTrip } from '../../../components/Assistant/assistantViewContext';
|
||||||
import type { EntityTarget } from '../../../components/Assistant/cards/cardTypes';
|
import type { EntityTarget } from '../../../components/Assistant/cards/cardTypes';
|
||||||
import { chatPagePath, useAssistantHome, useRouteJournalChat } from '../../../components/Assistant/useAssistantHome';
|
import { chatPagePath, useAssistantHome, useRouteJournalChat } from '../../../components/Assistant/useAssistantHome';
|
||||||
|
import { useAssistantStatus } from '../../../components/Assistant/useAssistantStatus';
|
||||||
import { useAssistantStore } from '../../../store/assistantStore';
|
import { useAssistantStore } from '../../../store/assistantStore';
|
||||||
import { AssistantScreen, type MapHops } from '../trip/assistant/MAssistantScreen';
|
import { AssistantScreen, type MapHops } from '../trip/assistant/MAssistantScreen';
|
||||||
|
|
||||||
@@ -26,7 +27,6 @@ export default function MAssistantHomeScreen() {
|
|||||||
const available = useAssistantStore((s) => s.status?.available === true);
|
const available = useAssistantStore((s) => s.status?.available === true);
|
||||||
const open = useAssistantStore((s) => s.window.open);
|
const open = useAssistantStore((s) => s.window.open);
|
||||||
const minimized = useAssistantStore((s) => s.window.minimized);
|
const minimized = useAssistantStore((s) => s.window.minimized);
|
||||||
const loadStatus = useAssistantStore((s) => s.loadStatus);
|
|
||||||
const close = useAssistantStore((s) => s.close);
|
const close = useAssistantStore((s) => s.close);
|
||||||
|
|
||||||
// The trip's screen (or the journal's) takes over with the window still open, so its chat comes up there.
|
// The trip's screen (or the journal's) takes over with the window still open, so its chat comes up there.
|
||||||
@@ -46,19 +46,21 @@ export default function MAssistantHomeScreen() {
|
|||||||
[close, navigate]
|
[close, navigate]
|
||||||
);
|
);
|
||||||
|
|
||||||
// The desktop window loads this itself; on the phone the pages outside a trip ask once.
|
// The desktop window loads this itself; on the phone the pages outside a trip ask here.
|
||||||
useEffect(() => {
|
useAssistantStatus();
|
||||||
void loadStatus();
|
|
||||||
}, [loadStatus]);
|
|
||||||
|
|
||||||
if (inTrip || !available || !open || minimized) return null;
|
if (inTrip || !available || !open || minimized) return null;
|
||||||
|
// Mounted beside MobileShell, not inside it, so the --m-* tokens the screen paints
|
||||||
|
// with only resolve under an m-root of its own; without it the chat is see-through.
|
||||||
return (
|
return (
|
||||||
<AssistantScreen
|
<div className="m-root">
|
||||||
tripId={chat.id}
|
<AssistantScreen
|
||||||
tripTitle={chat.title}
|
tripId={chat.id}
|
||||||
hidden={false}
|
tripTitle={chat.title}
|
||||||
hops={hops}
|
hidden={false}
|
||||||
onOpenTripChat={journal ? undefined : home.openTripChat}
|
hops={hops}
|
||||||
/>
|
onOpenTripChat={journal ? undefined : home.openTripChat}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|||||||
import { buildUser } from '../../../../tests/helpers/factories';
|
import { buildUser } from '../../../../tests/helpers/factories';
|
||||||
import { render, screen, waitFor } from '../../../../tests/helpers/render';
|
import { render, screen, waitFor } from '../../../../tests/helpers/render';
|
||||||
import { seedStore } from '../../../../tests/helpers/store';
|
import { seedStore } from '../../../../tests/helpers/store';
|
||||||
|
import { useAddonStore } from '../../../store/addonStore';
|
||||||
import { useAssistantStore } from '../../../store/assistantStore';
|
import { useAssistantStore } from '../../../store/assistantStore';
|
||||||
import { useAuthStore } from '../../../store/authStore';
|
import { useAuthStore } from '../../../store/authStore';
|
||||||
|
|
||||||
@@ -47,6 +48,8 @@ function status(over: Partial<AiStatusResponse> = {}): AiStatusResponse {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
useAssistantStore.setState({ status: null });
|
useAssistantStore.setState({ status: null });
|
||||||
|
// The card shows while the assistant is on, and only then is its status asked for.
|
||||||
|
seedStore(useAddonStore, { loaded: true, addons: [{ id: 'ai_assistant', enabled: true }] });
|
||||||
repo.models.mockResolvedValue([
|
repo.models.mockResolvedValue([
|
||||||
{ id: 'gemini-flash', label: 'Gemini Flash', supportsTools: true, free: true },
|
{ id: 'gemini-flash', label: 'Gemini Flash', supportsTools: true, free: true },
|
||||||
{ id: 'gemini-pro', label: 'Gemini Pro', supportsTools: true },
|
{ id: 'gemini-pro', label: 'Gemini Pro', supportsTools: true },
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user