From 1727732841253010382b7d63830b216f03c1af11 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 25 Sep 2026 00:49:15 +0000 Subject: [PATCH] feat(plugins): plugins can add POI categories to the map and answer them A new manifest capability poiCategories (up to 4, icon from an allow-list, strict #rrggbb color) and the hook poiCategoryProvider.getPois behind the hook:poi-category-provider permission. GET /api/plugin-pois in the plugin contributions module answers them in the /api/maps/pois shape, with search_plugin_pois as the MCP twin. plugin: ids no longer count as Google place ids. SDK 1.8.0 carries the types, validation and docs. On the map, one hook merges the built-in categories with the ones active plugins declare, and the pill shows the plugin chips after a divider on desktop and phone, scrolling sideways instead of shrinking a chip below its touch target. A plugin chip searches through a repo that refuses offline and parses the answer strictly. Its pins, on Leaflet and GL, use the category's own icon and color, both checked again before they reach any markup, and the hover card lists the plugin's details as escaped text. A plugin POI can be added as a place like any other. The admin panels on desktop and phone show a chip for the new permission and the categories a plugin would add, from one shared module. Addresses discussion #1781. --- client/src/api/pluginPois.test.ts | 53 ++++ client/src/api/pluginPois.ts | 36 +++ .../Admin/AdminPluginsPanel.test.tsx | 67 +++++ .../components/Admin/AdminPluginsPanel.tsx | 61 +--- .../Admin/PluginPoiCategoryList.test.tsx | 69 +++++ .../Admin/PluginPoiCategoryList.tsx | 45 +++ .../src/components/Admin/pluginCaps.test.ts | 140 +++++++++ client/src/components/Admin/pluginCaps.ts | 142 +++++++++ client/src/components/Map/MapView.test.tsx | 80 +++++ client/src/components/Map/MapView.tsx | 46 ++- client/src/components/Map/MapViewGL.test.tsx | 54 ++++ client/src/components/Map/MapViewGL.tsx | 13 +- .../components/Map/PoiCategoryPill.test.tsx | 143 ++++++++- client/src/components/Map/PoiCategoryPill.tsx | 177 +++++++---- client/src/components/Map/placePopup.test.ts | 87 +++++- client/src/components/Map/placePopup.ts | 39 ++- .../src/components/Map/pluginPoiIcons.test.ts | 34 +++ client/src/components/Map/pluginPoiIcons.ts | 56 ++++ .../src/components/Map/poiCategories.test.ts | 34 +++ client/src/components/Map/poiCategories.ts | 41 ++- client/src/components/Map/poiMarker.test.ts | 68 +++++ client/src/components/Map/poiMarker.ts | 59 ++++ .../components/Map/useMergedMapPois.test.ts | 13 +- .../components/Map/usePoiCategories.test.tsx | 119 ++++++++ client/src/components/Map/usePoiCategories.ts | 67 +++++ .../src/components/Map/usePoiExplore.test.tsx | 192 +++++++++++- client/src/components/Map/usePoiExplore.ts | 74 ++++- .../Planner/PlaceFormModal.test.tsx | 33 ++- .../screens/admin/MAdminPluginsPanel.tsx | 61 +--- .../src/mobile/screens/trip/map/MMapArea.tsx | 1 + client/src/pages/TripPlannerPage.tsx | 7 +- .../src/pages/TripPlannerPage.wiring.test.tsx | 32 +- .../pages/tripPlanner/useTripPlanner.test.tsx | 40 ++- .../src/pages/tripPlanner/useTripPlanner.ts | 8 +- client/src/repo/pluginPoiRepo.test.ts | 68 +++++ client/src/repo/pluginPoiRepo.ts | 27 ++ client/src/store/pluginStore.test.ts | 64 +++- client/src/store/pluginStore.ts | 37 ++- .../mobile/admin/MAdminPluginsPanel.test.tsx | 67 +++++ .../tests/unit/mobile/trip/MMapArea.test.tsx | 36 ++- .../unit/mobile/trip/MPlaceEditSheet.test.tsx | 27 +- plugin-sdk/README.md | 50 ++++ plugin-sdk/package-lock.json | 4 +- plugin-sdk/package.json | 2 +- plugin-sdk/src/cli/ui.ts | 1 + plugin-sdk/src/generated/host-facts.ts | 33 +++ plugin-sdk/src/index.ts | 48 +++ plugin-sdk/src/manifest.ts | 72 ++++- plugin-sdk/test/sdk.test.ts | 32 ++ server/scripts/gen-plugin-facts.ts | 18 ++ server/src/nest/maps/maps.helpers.ts | 53 +++- server/src/nest/maps/maps.mcp.ts | 9 +- server/src/nest/maps/maps.service.ts | 23 +- .../plugin-contributions.module.ts | 16 +- .../contributions/plugin-pois.controller.ts | 74 +++++ .../contributions/plugin-pois.helpers.ts | 131 +++++++++ .../plugins/contributions/plugin-pois.mcp.ts | 67 +++++ .../contributions/plugin-pois.service.ts | 124 ++++++++ .../contributions/plugin-search.helpers.ts | 74 +++-- server/src/nest/plugins/install/manifest.ts | 33 +++ .../src/nest/plugins/plugin-hooks.service.ts | 35 ++- .../nest/plugins/plugins-feed.controller.ts | 6 + .../nest/plugins/plugins-runtime.module.ts | 2 +- server/src/nest/plugins/plugins.module.ts | 2 +- server/src/nest/plugins/poi-categories.ts | 116 ++++++++ server/src/nest/plugins/protocol/envelope.ts | 6 + .../nest/plugins/registry/registry.service.ts | 12 + server/src/nest/plugins/runtime/plugin-sdk.ts | 10 + server/tests/e2e/plugin-pois.e2e.test.ts | 153 ++++++++++ server/tests/helpers/mcp-test-controllers.ts | 3 + .../tests/unit/mcp/tools-plugin-pois.test.ts | 162 ++++++++++ server/tests/unit/nest/maps.service.test.ts | 30 ++ server/tests/unit/plugins/manifest.test.ts | 53 ++++ .../tests/unit/plugins/plugin-hooks.test.ts | 13 +- server/tests/unit/plugins/plugin-pois.test.ts | 276 ++++++++++++++++++ .../plugins/plugin-search.controller.test.ts | 13 + .../plugins/plugins-feed.controller.test.ts | 40 +++ .../tests/unit/plugins/poi-categories.test.ts | 56 ++++ .../unit/plugins/provider-hook-grant.test.ts | 8 + .../unit/plugins/registry-preview.test.ts | 16 + shared/src/i18n/ar/admin.ts | 4 + shared/src/i18n/ar/map.ts | 1 + shared/src/i18n/az/admin.ts | 4 + shared/src/i18n/az/map.ts | 1 + shared/src/i18n/br/admin.ts | 4 + shared/src/i18n/br/map.ts | 1 + shared/src/i18n/ca/admin.ts | 4 + shared/src/i18n/ca/map.ts | 1 + shared/src/i18n/cs/admin.ts | 4 + shared/src/i18n/cs/map.ts | 1 + shared/src/i18n/de/admin.ts | 4 + shared/src/i18n/de/map.ts | 1 + shared/src/i18n/en/admin.ts | 4 + shared/src/i18n/en/map.ts | 1 + shared/src/i18n/es/admin.ts | 4 + shared/src/i18n/es/map.ts | 1 + shared/src/i18n/et/admin.ts | 4 + shared/src/i18n/et/map.ts | 1 + shared/src/i18n/fr/admin.ts | 4 + shared/src/i18n/fr/map.ts | 1 + shared/src/i18n/gr/admin.ts | 4 + shared/src/i18n/gr/map.ts | 1 + shared/src/i18n/hu/admin.ts | 4 + shared/src/i18n/hu/map.ts | 1 + .../src/i18n/i18n-permission-wording.spec.ts | 10 + shared/src/i18n/id/admin.ts | 4 + shared/src/i18n/id/map.ts | 1 + shared/src/i18n/it/admin.ts | 4 + shared/src/i18n/it/map.ts | 1 + shared/src/i18n/ja/admin.ts | 4 + shared/src/i18n/ja/map.ts | 1 + shared/src/i18n/ko/admin.ts | 4 + shared/src/i18n/ko/map.ts | 1 + shared/src/i18n/nl/admin.ts | 4 + shared/src/i18n/nl/map.ts | 1 + shared/src/i18n/pl/admin.ts | 4 + shared/src/i18n/pl/map.ts | 1 + shared/src/i18n/ru/admin.ts | 4 + shared/src/i18n/ru/map.ts | 1 + shared/src/i18n/sk/admin.ts | 4 + shared/src/i18n/sk/map.ts | 1 + shared/src/i18n/sv/admin.ts | 4 + shared/src/i18n/sv/map.ts | 1 + shared/src/i18n/th/admin.ts | 4 + shared/src/i18n/th/map.ts | 1 + shared/src/i18n/tr/admin.ts | 4 + shared/src/i18n/tr/map.ts | 1 + shared/src/i18n/uk/admin.ts | 4 + shared/src/i18n/uk/map.ts | 1 + shared/src/i18n/vi/admin.ts | 4 + shared/src/i18n/vi/map.ts | 1 + shared/src/i18n/zh-TW/admin.ts | 4 + shared/src/i18n/zh-TW/map.ts | 1 + shared/src/i18n/zh/admin.ts | 4 + shared/src/i18n/zh/map.ts | 1 + shared/src/index.ts | 3 + shared/src/plugin-permissions.ts | 3 + shared/src/plugins/plugin-poi-facts.ts | 49 ++++ shared/src/plugins/plugin-poi.schema.spec.ts | 166 +++++++++++ shared/src/plugins/plugin-poi.schema.ts | 188 ++++++++++++ wiki/Admin-Plugins.md | 1 + wiki/Display-Settings.md | 2 +- wiki/MCP-Tools-and-Resources.md | 2 + wiki/Places-and-Search.md | 22 ++ wiki/Plugin-Cookbook.md | 66 +++++ wiki/Plugin-Development.md | 3 + wiki/Plugin-Permissions.md | 1 + wiki/Plugins.md | 7 + 148 files changed, 4761 insertions(+), 290 deletions(-) create mode 100644 client/src/api/pluginPois.test.ts create mode 100644 client/src/api/pluginPois.ts create mode 100644 client/src/components/Admin/PluginPoiCategoryList.test.tsx create mode 100644 client/src/components/Admin/PluginPoiCategoryList.tsx create mode 100644 client/src/components/Admin/pluginCaps.test.ts create mode 100644 client/src/components/Admin/pluginCaps.ts create mode 100644 client/src/components/Map/pluginPoiIcons.test.ts create mode 100644 client/src/components/Map/pluginPoiIcons.ts create mode 100644 client/src/components/Map/poiCategories.test.ts create mode 100644 client/src/components/Map/poiMarker.test.ts create mode 100644 client/src/components/Map/poiMarker.ts create mode 100644 client/src/components/Map/usePoiCategories.test.tsx create mode 100644 client/src/components/Map/usePoiCategories.ts create mode 100644 client/src/repo/pluginPoiRepo.test.ts create mode 100644 client/src/repo/pluginPoiRepo.ts create mode 100644 server/src/nest/plugins/contributions/plugin-pois.controller.ts create mode 100644 server/src/nest/plugins/contributions/plugin-pois.helpers.ts create mode 100644 server/src/nest/plugins/contributions/plugin-pois.mcp.ts create mode 100644 server/src/nest/plugins/contributions/plugin-pois.service.ts create mode 100644 server/src/nest/plugins/poi-categories.ts create mode 100644 server/tests/e2e/plugin-pois.e2e.test.ts create mode 100644 server/tests/unit/mcp/tools-plugin-pois.test.ts create mode 100644 server/tests/unit/plugins/plugin-pois.test.ts create mode 100644 server/tests/unit/plugins/poi-categories.test.ts create mode 100644 shared/src/plugins/plugin-poi-facts.ts create mode 100644 shared/src/plugins/plugin-poi.schema.spec.ts create mode 100644 shared/src/plugins/plugin-poi.schema.ts diff --git a/client/src/api/pluginPois.test.ts b/client/src/api/pluginPois.test.ts new file mode 100644 index 000000000..691c68c8d --- /dev/null +++ b/client/src/api/pluginPois.test.ts @@ -0,0 +1,53 @@ +// FE-API-PLUGINPOIS-001 to FE-API-PLUGINPOIS-003 +import { describe, it, expect, vi, afterEach } from 'vitest' +import { http, HttpResponse } from 'msw' +import { server } from '../../tests/helpers/msw/server' +import { pluginPoisApi } from './pluginPois' + +const BBOX = { south: 47.1, west: 11.2, north: 47.3, east: 11.5 } +const reply = { + pois: [{ + osm_id: 'plugin:trail-finder:th-1', name: 'Hochalm trailhead', lat: 47.2, lng: 11.3, + category: 'plugin:trail-finder/trailheads', poi_type: 'plugin:trail-finder/trailheads', + address: null, website: null, phone: null, + opening_hours: null, cuisine: null, brand: null, brand_wikidata: null, charging: null, + source: 'plugin:trail-finder', pluginId: 'trail-finder', rating: null, + details: [], icon: 'Signpost', color: '#2f855a', + }], + source: 'plugin:trail-finder', + truncated: false, + clamped: false, +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('pluginPoisApi.search', () => { + it('FE-API-PLUGINPOIS-001: asks GET /api/plugin-pois with the plugin, category, box and language', async () => { + let url = '' + server.use(http.get('/api/plugin-pois', ({ request }) => { + url = request.url + return HttpResponse.json(reply) + })) + expect(await pluginPoisApi.search('trail-finder', 'trailheads', BBOX, 'de')).toEqual(reply) + const params = new URL(url).searchParams + expect(Object.fromEntries(params)).toEqual({ + pluginId: 'trail-finder', category: 'trailheads', + south: '47.1', west: '11.2', north: '47.3', east: '11.5', lang: 'de', + }) + }) + + it('FE-API-PLUGINPOIS-002: a drifting answer still passes through, with a warning in development', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const drifted = { ...reply, pois: [{ ...reply.pois[0], color: 'red' }] } + server.use(http.get('/api/plugin-pois', () => HttpResponse.json(drifted))) + expect(await pluginPoisApi.search('trail-finder', 'trailheads', BBOX, undefined)).toEqual(drifted) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('pluginPois.search'), expect.anything()) + }) + + it('FE-API-PLUGINPOIS-003: rejects with the server error', async () => { + server.use(http.get('/api/plugin-pois', () => HttpResponse.json({ error: 'Unknown POI category' }, { status: 404 }))) + await expect(pluginPoisApi.search('trail-finder', 'gone', BBOX, 'en')).rejects.toMatchObject({ response: { status: 404 } }) + }) +}) diff --git a/client/src/api/pluginPois.ts b/client/src/api/pluginPois.ts new file mode 100644 index 000000000..659e2b135 --- /dev/null +++ b/client/src/api/pluginPois.ts @@ -0,0 +1,36 @@ +import { pluginPoiResponseSchema, type PluginPoiResponse } from '@trek/shared' +import { apiClient, parseInDev } from './client' + +/** The map area a plugin POI search covers, as the explore pill reports it. */ +export interface PluginPoiArea { + south: number + west: number + north: number + east: number +} + +/** + * The same ceiling as the core categories' GET /api/maps/pois. The server gives the + * plugin 8 seconds and answers 502 after that, so this only ever cuts off a request + * that got lost on the way. + */ +export const PLUGIN_POI_TIMEOUT_MS = 20_000 + +/** + * GET /api/plugin-pois (#1781): the places of one plugin POI category inside a map + * area. In a file of its own rather than in the `client.ts` god module, typed from the + * shared contract. The explore pill reaches it through repo/pluginPoiRepo.ts, which + * adds the offline guard and the strict check. + */ +export const pluginPoisApi = { + search: ( + pluginId: string, + category: string, + bbox: PluginPoiArea, + lang: string | undefined, + signal?: AbortSignal, + ): Promise => + apiClient + .get('/plugin-pois', { params: { pluginId, category, ...bbox, lang }, signal, timeout: PLUGIN_POI_TIMEOUT_MS }) + .then(r => parseInDev(pluginPoiResponseSchema, r.data, 'pluginPois.search')), +} diff --git a/client/src/components/Admin/AdminPluginsPanel.test.tsx b/client/src/components/Admin/AdminPluginsPanel.test.tsx index 3f8b4137c..57f843e32 100644 --- a/client/src/components/Admin/AdminPluginsPanel.test.tsx +++ b/client/src/components/Admin/AdminPluginsPanel.test.tsx @@ -381,6 +381,23 @@ describe('AdminPluginsPanel — update consent', () => { // Falls back to the installed row's `signed: false` rather than going quiet. expect(await screen.findByText(/nothing ties this version to its author/i)).toBeInTheDocument() }) + + it('FE-COMP-PLUGINS-PANEL-054: an update asking for the POI category grant spells out what it sends (#1781)', async () => { + mockPanel(plugin({ source_repo: 'acme/gotify', signed: true }), registryEntry()) + server.use( + http.post('*/api/admin/plugins/trek-gotify/update', () => + HttpResponse.json({ version: '2.0.0', activated: false, newPermissions: ['hook:poi-category-provider'], newEgress: [] }), + ), + ) + render() + await screen.findByText('Gotify') + fireEvent.click(await screen.findByRole('button', { name: /update to|2\.0\.0/i })) + + expect(await screen.findByText( + 'Add its own place categories to Explore places on the map; picking one sends the plugin the map area you are viewing', + )).toBeInTheDocument() + expect(screen.queryByText('hook:poi-category-provider')).not.toBeInTheDocument() + }) }) /** @@ -1425,6 +1442,20 @@ describe('AdminPluginsPanel — capability and dependency chips', () => { expect(await screen.findByText('Does not say which TREK versions it supports')).toBeInTheDocument() }) + + it('FE-COMP-PLUGINS-PANEL-051: a plugin adding explore-pill categories says so on its row (#1781)', async () => { + panelWith([plugin({ + operatorEgress: false, + permissions: JSON.stringify(['hook:poi-category-provider']), + capabilities: JSON.stringify({ + poiCategories: [{ id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' }], + }), + })]) + render() + await screen.findByText('Gotify') + + expect(screen.getByText('Adds map categories')).toBeInTheDocument() + }) }) describe('AdminPluginsPanel — Discover cards and the detail modal', () => { @@ -1588,6 +1619,42 @@ describe('AdminPluginsPanel — Discover cards and the detail modal', () => { expect(await screen.findByText('No plugins available in the registry yet.')).toBeInTheDocument() }) + + it('FE-COMP-PLUGINS-PANEL-052: the detail lists the map categories a plugin adds, before the install (#1781)', async () => { + discoverWith({}, manifestDetail({}, { + permissions: ['hook:poi-category-provider'], + capabilities: { + poiCategories: [ + { id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' }, + { id: 'swimming', label: 'Swimming spots', icon: 'Waves', color: '#0369a1' }, + ], + }, + })) + render() + await clickDiscover() + fireEvent.click(await screen.findByText('Gotify')) + + const title = await screen.findByRole('heading', { name: 'Map categories it adds' }) + const section = title.parentElement as HTMLElement + expect(within(section).getAllByRole('listitem').map(li => li.textContent)).toEqual(['Trailheads', 'Swimming spots']) + expect(within(section).getAllByTestId('poi-category-swatch')[0].style.backgroundColor).toBe('rgb(47, 133, 90)') + // The grant itself is listed with the rest of what the plugin can do. + expect(screen.getByText('Adds map categories')).toBeInTheDocument() + }) + + it('FE-COMP-PLUGINS-PANEL-053: declared categories without the grant are not shown, the feed would never serve them', async () => { + discoverWith({}, manifestDetail({}, { + permissions: ['hook:search-provider'], + capabilities: { poiCategories: [{ id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' }] }, + })) + render() + await clickDiscover() + fireEvent.click(await screen.findByText('Gotify')) + + expect(await screen.findByText('Answers searches')).toBeInTheDocument() + expect(screen.queryByText('Map categories it adds')).not.toBeInTheDocument() + expect(screen.queryByText('Trailheads')).not.toBeInTheDocument() + }) }) describe('AdminPluginsPanel — security footer', () => { diff --git a/client/src/components/Admin/AdminPluginsPanel.tsx b/client/src/components/Admin/AdminPluginsPanel.tsx index a0abde00f..21dc05b7a 100644 --- a/client/src/components/Admin/AdminPluginsPanel.tsx +++ b/client/src/components/Admin/AdminPluginsPanel.tsx @@ -4,15 +4,15 @@ import { createPortal } from 'react-dom' import { Blocks, AlertTriangle, PackageOpen, RefreshCw, Trash2, Download, Bug, X, ShieldCheck, UploadCloud, ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search, Link2, KeyRound, ShieldAlert, - SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, ArrowRight, Database, Users, LayoutDashboard, - Radio, Luggage, Globe, Image, CalendarDays, Bell, Info, History, PauseCircle, - Wallet, Puzzle, MapPin, ListChecks, Pencil, Tag, FileText, Route, Navigation, Clock, LocateFixed, Palette, Bot, - Loader2, + SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, Database, + Globe, Info, History, PauseCircle, Puzzle, Bot, Loader2, } from 'lucide-react' import PluginIcon from '../shared/PluginIcon' import { adminApi } from '../../api/client' import { useInstanceSettings } from './useInstanceSettings' import { bypassChip, bypassOffer, useRangeBypass, type RangeWarning, type TrekRangeBypass } from './useRangeBypass' +import { deriveCaps } from './pluginCaps' +import PluginPoiCategoryList from './PluginPoiCategoryList' import { usePluginStore } from '../../store/pluginStore' import { useTranslation } from '../../i18n' import { useToast } from '../shared/Toast' @@ -139,6 +139,8 @@ interface RegistryDetail extends RegistryItem { tripPage?: { replaces?: string[] } /** Tools the plugin will publish on the MCP server once mcp:tools is granted. */ mcpTools?: Array<{ name: string; title?: string; description: string }> + /** Explore-pill categories it adds (#1781), checked again before anything draws them. */ + poiCategories?: unknown } } | null } @@ -230,53 +232,6 @@ function parseJson(raw: string | null | undefined, fallback: T): T { try { const v = JSON.parse(raw || '') as T; return v ?? fallback } catch { return fallback } } -interface Cap { icon: React.ComponentType<{ size?: number; className?: string }>; label: string; net?: boolean } - -// Turn a plugin's declared permissions + capabilities into the at-a-glance chips -// that make its real reach legible without opening the detail dialog. -function deriveCaps(perms: string[], caps: { widget?: { slot?: string }; tripPage?: { replaces?: string[] } }, t: T): Cap[] { - const out: Cap[] = [] - if (perms.includes('db:read:trips')) out.push({ icon: Database, label: t('admin.plugins.cap.readsTrips') }) - if (perms.includes('db:read:users')) out.push({ icon: Users, label: t('admin.plugins.cap.readsUsers') }) - if (perms.includes('db:write:costs')) out.push({ icon: Wallet, label: t('admin.plugins.cap.writesCosts') }) - else if (perms.includes('db:read:costs')) out.push({ icon: Wallet, label: t('admin.plugins.cap.readsCosts') }) - if (perms.includes('db:read:packing')) out.push({ icon: Luggage, label: t('admin.plugins.cap.readsPacking') }) - if (perms.includes('db:read:files')) out.push({ icon: FileText, label: t('admin.plugins.cap.readsFiles') }) - if (perms.includes('db:write:places')) out.push({ icon: MapPin, label: t('admin.plugins.cap.writesPlaces') }) - if (perms.includes('db:write:days')) out.push({ icon: CalendarDays, label: t('admin.plugins.cap.writesDays') }) - if (perms.includes('db:write:itinerary')) out.push({ icon: ListChecks, label: t('admin.plugins.cap.writesItinerary') }) - if (perms.includes('db:write:trips')) out.push({ icon: Pencil, label: t('admin.plugins.cap.writesTrips') }) - if (perms.includes('db:meta')) out.push({ icon: Tag, label: t('admin.plugins.cap.metadata') }) - if (caps.widget) { - const slotKey = caps.widget.slot === 'hero' ? 'admin.plugins.cap.heroWidget' - : caps.widget.slot === 'place-detail' ? 'admin.plugins.cap.placeSlot' - : caps.widget.slot === 'day-detail' ? 'admin.plugins.cap.daySlot' - : caps.widget.slot === 'reservation-detail' ? 'admin.plugins.cap.reservationSlot' - : 'admin.plugins.cap.widget' - out.push({ icon: LayoutDashboard, label: t(slotKey as never) }) - } - // Replacing planner tabs is the one capability that HIDES core UI — always chip it. - if (caps.tripPage?.replaces?.length) out.push({ icon: LayoutDashboard, label: t('admin.plugins.cap.replacesTabs') }) - if (perms.includes('mcp:tools')) out.push({ icon: Bot, label: t('admin.plugins.cap.mcpTools') }) - if (perms.some(p => p.startsWith('ws:broadcast'))) out.push({ icon: Radio, label: t('admin.plugins.cap.realtime') }) - if (perms.includes('hook:photo-provider')) out.push({ icon: Image, label: t('admin.plugins.cap.photos') }) - if (perms.includes('hook:calendar-source')) out.push({ icon: CalendarDays, label: t('admin.plugins.cap.calendar') }) - if (perms.includes('hook:place-detail-provider')) out.push({ icon: MapPin, label: t('admin.plugins.cap.placeDetails') }) - if (perms.includes('hook:search-provider')) out.push({ icon: Search, label: t('admin.plugins.cap.search') }) - if (perms.includes('hook:trip-warning-provider')) out.push({ icon: AlertTriangle, label: t('admin.plugins.cap.warnings') }) - if (perms.includes('hook:map-layer-provider')) out.push({ icon: Route, label: t('admin.plugins.cap.mapLayers') }) - if (perms.includes('hook:route-provider')) out.push({ icon: Navigation, label: t('admin.plugins.cap.routing') }) - if (perms.includes('hook:day-schedule-provider')) out.push({ icon: Clock, label: t('admin.plugins.cap.daySchedule') }) - if (perms.includes('hook:day-tint-provider')) out.push({ icon: Palette, label: t('admin.plugins.cap.dayTint') }) - if (perms.includes('geolocation:read')) out.push({ icon: LocateFixed, label: t('admin.plugins.cap.geolocation') }) - if (perms.includes('hook:notification-channel')) out.push({ icon: Bell, label: t('admin.plugins.cap.notificationChannel') }) - if (perms.includes('events:subscribe')) out.push({ icon: Radio, label: t('admin.plugins.cap.events') }) - for (const h of perms.filter(p => p.startsWith('http:outbound:')).map(p => p.slice('http:outbound:'.length)).filter(Boolean)) { - out.push({ icon: ArrowRight, label: h, net: true }) - } - return out -} - interface DepChip { icon: React.ComponentType<{ size?: number; className?: string }>; label: string; blocked: boolean; warn?: boolean } // A plugin's declared dependencies as chips — a required addon (amber when that @@ -1808,6 +1763,10 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local )} + + {manifest && (egress.length > 0 || manifest.operatorEgress) && (

{t('admin.plugins.connectsTitle')}

diff --git a/client/src/components/Admin/PluginPoiCategoryList.test.tsx b/client/src/components/Admin/PluginPoiCategoryList.test.tsx new file mode 100644 index 000000000..8157c6073 --- /dev/null +++ b/client/src/components/Admin/PluginPoiCategoryList.test.tsx @@ -0,0 +1,69 @@ +// FE-COMP-PLUGINPOICATLIST-001 to FE-COMP-PLUGINPOICATLIST-005 +import { describe, it, expect, beforeEach } from 'vitest' +import { render, screen } from '../../../tests/helpers/render' +import { useSettingsStore } from '../../store/settingsStore' +import PluginPoiCategoryList from './PluginPoiCategoryList' +import { POI_CATEGORY_PERMISSION } from './pluginCaps' + +const TRAILHEADS = { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a' } +const SWIMMING = { id: 'swimming', label: 'Swimming spots', icon: 'Waves', color: '#0369a1' } + +const initialSettings = useSettingsStore.getState() +beforeEach(() => useSettingsStore.setState(initialSettings, true)) + +function renderList(categories: unknown, permissions: string[] = [POI_CATEGORY_PERMISSION]) { + return render( + , + ) +} + +describe('PluginPoiCategoryList', () => { + it('FE-COMP-PLUGINPOICATLIST-001: a titled list with one row per category, placed by the shell', () => { + const { container } = renderList([TRAILHEADS, SWIMMING]) + + const title = screen.getByRole('heading', { name: 'Map categories it adds' }) + expect(title).toHaveClass('shell-title') + expect(container.firstElementChild).toHaveClass('shell-place') + const rows = screen.getAllByRole('listitem') + expect(rows.map(r => r.textContent)).toEqual(['Trailheads', 'Swimming spots']) + expect(rows[0]).toHaveClass('shell-row') + }) + + it('FE-COMP-PLUGINPOICATLIST-002: each swatch carries the category colour and its icon, hidden from readers', () => { + renderList([TRAILHEADS, SWIMMING]) + + const swatches = screen.getAllByTestId('poi-category-swatch') + expect(swatches.map(s => s.style.backgroundColor)).toEqual(['rgb(47, 133, 90)', 'rgb(3, 105, 161)']) + expect(swatches[0]).toHaveAttribute('aria-hidden', 'true') + expect(swatches[0].querySelector('svg')).toHaveClass('lucide-signpost') + expect(swatches[1].querySelector('svg')).toHaveClass('lucide-waves') + }) + + it('FE-COMP-PLUGINPOICATLIST-003: a label is text, never markup', () => { + const { container } = renderList([{ ...TRAILHEADS, label: '' }]) + + expect(screen.getByText('')).toBeInTheDocument() + expect(container.querySelector('img')).toBeNull() + }) + + it('FE-COMP-PLUGINPOICATLIST-004: the admin language picks the plugin label for it', async () => { + useSettingsStore.setState(s => ({ settings: { ...s.settings, language: 'de' } })) + renderList([TRAILHEADS, SWIMMING]) + + expect(await screen.findByRole('heading', { name: 'Kartenkategorien, die es hinzufügt' })).toBeInTheDocument() + expect(screen.getAllByRole('listitem').map(r => r.textContent)).toEqual(['Wanderparkplätze', 'Swimming spots']) + }) + + it('FE-COMP-PLUGINPOICATLIST-005: renders nothing without the grant or without a valid category', () => { + const withoutGrant = renderList([TRAILHEADS], ['hook:search-provider']) + expect(withoutGrant.container).toBeEmptyDOMElement() + withoutGrant.unmount() + + const nothingValid = renderList([{ ...TRAILHEADS, color: 'red' }]) + expect(nothingValid.container).toBeEmptyDOMElement() + nothingValid.unmount() + + expect(renderList(undefined).container).toBeEmptyDOMElement() + }) +}) diff --git a/client/src/components/Admin/PluginPoiCategoryList.tsx b/client/src/components/Admin/PluginPoiCategoryList.tsx new file mode 100644 index 000000000..fab42f08f --- /dev/null +++ b/client/src/components/Admin/PluginPoiCategoryList.tsx @@ -0,0 +1,45 @@ +import { useTranslation } from '../../i18n' +import { declaredPoiCategories } from './pluginCaps' + +interface Props { + pluginId: string + /** The plugin's declared permissions: the list only shows with the grant that serves it. */ + permissions: readonly string[] + /** `capabilities.poiCategories` as the registry sent it; checked again before drawing. */ + categories: unknown + /** Where the section sits and how its heading and rows read are the shell's business. */ + className?: string + titleClassName: string + itemClassName: string +} + +/** + * The "Map categories it adds" section of a plugin's detail view (#1781), shared by + * the desktop dialog and the phone sheet. Each row is drawn the way the chip looks + * when it is switched on in the explore pill: the icon on the category colour, then + * the label in the admin's language. The label only ever goes in as React text and + * the colour only as a background value, so a plugin cannot put markup or styling of + * its own into the panel. + */ +export default function PluginPoiCategoryList({ pluginId, permissions, categories, className, titleClassName, itemClassName }: Readonly) { + const { t, language } = useTranslation() + const declared = declaredPoiCategories(pluginId, permissions, categories, language) + if (declared.length === 0) return null + return ( +
+

{t('admin.plugins.poiCategoriesTitle')}

+
    + {declared.map(({ id, label, Icon, color }) => ( +
  • + + {label} +
  • + ))} +
+
+ ) +} diff --git a/client/src/components/Admin/pluginCaps.test.ts b/client/src/components/Admin/pluginCaps.test.ts new file mode 100644 index 000000000..b2e070871 --- /dev/null +++ b/client/src/components/Admin/pluginCaps.test.ts @@ -0,0 +1,140 @@ +// FE-COMP-PLUGINCAPS-001 to FE-COMP-PLUGINCAPS-013 +import { describe, it, expect } from 'vitest' +import { ArrowRight, Database, LayoutDashboard, MapPinned, Signpost, Wallet, Waves } from 'lucide-react' +import { POI_CATEGORY_PERMISSION, declaredPoiCategories, deriveCaps } from './pluginCaps' + +const t = (key: string) => `t:${key}` +const labels = (perms: string[], caps = {}) => deriveCaps(perms, caps, t).map(c => c.label) + +/** + * The ONE place both admin shells turn a plugin's manifest into chips. The desktop + * panel and the phone panel only draw what this returns. + */ +describe('deriveCaps', () => { + it('FE-COMP-PLUGINCAPS-001: data grants, then the widget, then hooks, then hosts, in that order', () => { + const caps = deriveCaps( + ['http:outbound:api.acme.io', 'hook:search-provider', 'db:read:trips', 'mcp:tools'], + { widget: { slot: 'hero' } }, + t, + ) + expect(caps.map(c => c.label)).toEqual([ + 't:admin.plugins.cap.readsTrips', + 't:admin.plugins.cap.heroWidget', + 't:admin.plugins.cap.mcpTools', + 't:admin.plugins.cap.search', + 'api.acme.io', + ]) + expect(caps[0].icon).toBe(Database) + expect(caps[1].icon).toBe(LayoutDashboard) + expect(caps[4]).toEqual({ icon: ArrowRight, label: 'api.acme.io', net: true }) + expect(caps.slice(0, 4).every(c => !c.net)).toBe(true) + }) + + it('FE-COMP-PLUGINCAPS-002: every known grant has its own chip', () => { + expect(labels([ + 'db:read:trips', 'db:read:users', 'db:write:costs', 'db:read:packing', 'db:read:files', 'db:write:places', + 'db:write:days', 'db:write:itinerary', 'db:write:trips', 'db:meta', 'mcp:tools', 'ws:broadcast:trip', + 'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider', 'hook:search-provider', + 'hook:poi-category-provider', 'hook:trip-warning-provider', 'hook:map-layer-provider', 'hook:route-provider', + 'hook:day-schedule-provider', 'hook:day-tint-provider', 'geolocation:read', 'hook:notification-channel', + 'events:subscribe', + ])).toEqual([ + 'readsTrips', 'readsUsers', 'writesCosts', 'readsPacking', 'readsFiles', 'writesPlaces', 'writesDays', + 'writesItinerary', 'writesTrips', 'metadata', 'mcpTools', 'realtime', 'photos', 'calendar', 'placeDetails', + 'search', 'poiCategories', 'warnings', 'mapLayers', 'routing', 'daySchedule', 'dayTint', 'geolocation', + 'notificationChannel', 'events', + ].map(k => `t:admin.plugins.cap.${k}`)) + }) + + it('FE-COMP-PLUGINCAPS-003: the POI category grant gets the map-categories chip (#1781)', () => { + const [chip] = deriveCaps([POI_CATEGORY_PERMISSION], {}, t) + expect(chip).toEqual({ icon: MapPinned, label: 't:admin.plugins.cap.poiCategories' }) + expect(labels(['hook:search-provider'])).not.toContain('t:admin.plugins.cap.poiCategories') + }) + + it('FE-COMP-PLUGINCAPS-004: writing costs hides the read-only costs chip', () => { + expect(labels(['db:read:costs'])).toEqual(['t:admin.plugins.cap.readsCosts']) + expect(labels(['db:read:costs', 'db:write:costs'])).toEqual(['t:admin.plugins.cap.writesCosts']) + expect(deriveCaps(['db:read:costs'], {}, t)[0].icon).toBe(Wallet) + }) + + it('FE-COMP-PLUGINCAPS-005: each widget slot has its own wording, and anything else is a plain widget', () => { + const slot = (s?: string) => labels([], { widget: s === undefined ? {} : { slot: s } }) + expect(slot('hero')).toEqual(['t:admin.plugins.cap.heroWidget']) + expect(slot('place-detail')).toEqual(['t:admin.plugins.cap.placeSlot']) + expect(slot('day-detail')).toEqual(['t:admin.plugins.cap.daySlot']) + expect(slot('reservation-detail')).toEqual(['t:admin.plugins.cap.reservationSlot']) + expect(slot()).toEqual(['t:admin.plugins.cap.widget']) + // Names of Object.prototype members are unknown slots, not lookups into the prototype. + expect(slot('constructor')).toEqual(['t:admin.plugins.cap.widget']) + expect(slot('toString')).toEqual(['t:admin.plugins.cap.widget']) + }) + + it('FE-COMP-PLUGINCAPS-006: replacing planner tabs is chipped, an empty list is not', () => { + expect(labels([], { tripPage: { replaces: ['collab'] } })).toEqual(['t:admin.plugins.cap.replacesTabs']) + expect(labels([], { tripPage: { replaces: [] } })).toEqual([]) + expect(labels([], { tripPage: {} })).toEqual([]) + }) + + it('FE-COMP-PLUGINCAPS-007: every outbound host is its own network chip, a bare prefix is none', () => { + const caps = deriveCaps(['http:outbound:a.example', 'http:outbound:', 'http:outbound:b.example'], {}, t) + expect(caps).toEqual([ + { icon: ArrowRight, label: 'a.example', net: true }, + { icon: ArrowRight, label: 'b.example', net: true }, + ]) + }) + + it('FE-COMP-PLUGINCAPS-008: a plugin that asks for nothing gets no chips', () => { + expect(deriveCaps([], {}, t)).toEqual([]) + expect(labels(['db:own', 'x:unknown'])).toEqual([]) + }) +}) + +describe('declaredPoiCategories', () => { + const trailheads = { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a' } + const swimming = { id: 'swimming', label: 'Swimming spots', icon: 'Waves', color: '#0369a1' } + + it('FE-COMP-PLUGINCAPS-009: the declared categories in declaration order, with icon and colour resolved', () => { + expect(declaredPoiCategories('trail-finder', [POI_CATEGORY_PERMISSION], [trailheads, swimming], 'en')).toEqual([ + { id: 'trailheads', label: 'Trailheads', Icon: Signpost, color: '#2f855a' }, + { id: 'swimming', label: 'Swimming spots', Icon: Waves, color: '#0369a1' }, + ]) + }) + + it('FE-COMP-PLUGINCAPS-010: the label follows the admin language and falls back to the default', () => { + const [de] = declaredPoiCategories('trail-finder', [POI_CATEGORY_PERMISSION], [trailheads], 'de') + expect(de.label).toBe('Wanderparkplätze') + const [fr] = declaredPoiCategories('trail-finder', [POI_CATEGORY_PERMISSION], [trailheads], 'fr') + expect(fr.label).toBe('Trailheads') + // An inherited name is not a language the plugin wrote a label for. + const [inherited] = declaredPoiCategories('trail-finder', [POI_CATEGORY_PERMISSION], [trailheads], 'toString') + expect(inherited.label).toBe('Trailheads') + }) + + it('FE-COMP-PLUGINCAPS-011: nothing without the grant, because the feed would never serve them', () => { + expect(declaredPoiCategories('trail-finder', ['hook:search-provider'], [trailheads], 'en')).toEqual([]) + expect(declaredPoiCategories('trail-finder', [], [trailheads], 'en')).toEqual([]) + }) + + it('FE-COMP-PLUGINCAPS-012: entries the schema refuses are dropped, never drawn', () => { + const declared = declaredPoiCategories('trail-finder', [POI_CATEGORY_PERMISSION], [ + { ...swimming, id: 'css', color: '#2f855a;background:url(https://x)' }, + { ...swimming, id: 'skull', icon: 'Skull' }, + trailheads, + { ...trailheads, label: 'A repeated id' }, + ], 'en') + expect(declared).toEqual([{ id: 'trailheads', label: 'Trailheads', Icon: Signpost, color: '#2f855a' }]) + const odd = declaredPoiCategories('trail-finder', [POI_CATEGORY_PERMISSION], [{ ...swimming, id: 'Bad Id' }, 'not an object', swimming], 'en') + expect(odd.map(c => c.id)).toEqual(['swimming']) + expect(declaredPoiCategories('trail-finder', [POI_CATEGORY_PERMISSION], { trailheads }, 'en')).toEqual([]) + expect(declaredPoiCategories('trail-finder', [POI_CATEGORY_PERMISSION], undefined, 'en')).toEqual([]) + // A plugin id no pill key could carry takes all of its categories with it. + expect(declaredPoiCategories('Not A Plugin', [POI_CATEGORY_PERMISSION], [trailheads], 'en')).toEqual([]) + }) + + it('FE-COMP-PLUGINCAPS-013: no more than the cap, as the explore pill would show', () => { + const five = ['a1', 'b1', 'c1', 'd1', 'e1'].map(id => ({ ...swimming, id })) + const declared = declaredPoiCategories('trail-finder', [POI_CATEGORY_PERMISSION], five, 'en') + expect(declared.map(c => c.id)).toEqual(['a1', 'b1', 'c1', 'd1']) + }) +}) diff --git a/client/src/components/Admin/pluginCaps.ts b/client/src/components/Admin/pluginCaps.ts new file mode 100644 index 000000000..bc62e30e5 --- /dev/null +++ b/client/src/components/Admin/pluginCaps.ts @@ -0,0 +1,142 @@ +import type { ComponentType } from 'react' +import { + AlertTriangle, ArrowRight, Bell, Bot, CalendarDays, Clock, Database, FileText, Image, LayoutDashboard, ListChecks, + LocateFixed, Luggage, MapPin, MapPinned, Navigation, Palette, Pencil, Radio, Route, Search, Tag, Users, Wallet, + type LucideIcon, +} from 'lucide-react' +import { pluginPoiCategoryLabel } from '@trek/shared' +import { readPoiCategories } from '../../store/pluginStore' +import { pluginPoiColor, resolvePluginPoiIcon } from '../Map/pluginPoiIcons' + +/** + * A plugin's reach as the admin panel shows it: the capability chips on an installed + * row and the access list of the detail view. One module for the desktop panel and + * the phone panel, so the two can never tell an admin different things about the same + * plugin; each shell only decides where the chips sit and how they look. + */ + +type Translate = (key: string) => string + +export interface PluginCap { + icon: ComponentType<{ size?: number; className?: string }> + label: string + /** A host the plugin may call out to, drawn in the network tone. */ + net?: boolean +} + +/** The part of a plugin's declared capabilities the chips read. */ +export interface PluginCapsSlice { + widget?: { slot?: string } + tripPage?: { replaces?: string[] } +} + +/** The grant that puts a plugin's own categories into the map's explore pill (#1781). */ +export const POI_CATEGORY_PERMISSION = 'hook:poi-category-provider' + +interface ChipRule { + icon: LucideIcon + key: string + held: (perms: readonly string[]) => boolean +} + +const has = (perm: string) => (perms: readonly string[]) => perms.includes(perm) + +// What the plugin may read and write, listed before its widget. +const DATA_CHIPS: readonly ChipRule[] = [ + { icon: Database, key: 'admin.plugins.cap.readsTrips', held: has('db:read:trips') }, + { icon: Users, key: 'admin.plugins.cap.readsUsers', held: has('db:read:users') }, + { icon: Wallet, key: 'admin.plugins.cap.writesCosts', held: has('db:write:costs') }, + // Writing costs includes reading them, so only the wider grant gets a chip. + { + icon: Wallet, + key: 'admin.plugins.cap.readsCosts', + held: perms => perms.includes('db:read:costs') && !perms.includes('db:write:costs'), + }, + { icon: Luggage, key: 'admin.plugins.cap.readsPacking', held: has('db:read:packing') }, + { icon: FileText, key: 'admin.plugins.cap.readsFiles', held: has('db:read:files') }, + { icon: MapPin, key: 'admin.plugins.cap.writesPlaces', held: has('db:write:places') }, + { icon: CalendarDays, key: 'admin.plugins.cap.writesDays', held: has('db:write:days') }, + { icon: ListChecks, key: 'admin.plugins.cap.writesItinerary', held: has('db:write:itinerary') }, + { icon: Pencil, key: 'admin.plugins.cap.writesTrips', held: has('db:write:trips') }, + { icon: Tag, key: 'admin.plugins.cap.metadata', held: has('db:meta') }, +] + +// What it adds to TREK or answers for it, listed after its widget. +const HOOK_CHIPS: readonly ChipRule[] = [ + { icon: Bot, key: 'admin.plugins.cap.mcpTools', held: has('mcp:tools') }, + { icon: Radio, key: 'admin.plugins.cap.realtime', held: perms => perms.some(p => p.startsWith('ws:broadcast')) }, + { icon: Image, key: 'admin.plugins.cap.photos', held: has('hook:photo-provider') }, + { icon: CalendarDays, key: 'admin.plugins.cap.calendar', held: has('hook:calendar-source') }, + { icon: MapPin, key: 'admin.plugins.cap.placeDetails', held: has('hook:place-detail-provider') }, + { icon: Search, key: 'admin.plugins.cap.search', held: has('hook:search-provider') }, + { icon: MapPinned, key: 'admin.plugins.cap.poiCategories', held: has(POI_CATEGORY_PERMISSION) }, + { icon: AlertTriangle, key: 'admin.plugins.cap.warnings', held: has('hook:trip-warning-provider') }, + { icon: Route, key: 'admin.plugins.cap.mapLayers', held: has('hook:map-layer-provider') }, + { icon: Navigation, key: 'admin.plugins.cap.routing', held: has('hook:route-provider') }, + { icon: Clock, key: 'admin.plugins.cap.daySchedule', held: has('hook:day-schedule-provider') }, + { icon: Palette, key: 'admin.plugins.cap.dayTint', held: has('hook:day-tint-provider') }, + { icon: LocateFixed, key: 'admin.plugins.cap.geolocation', held: has('geolocation:read') }, + { icon: Bell, key: 'admin.plugins.cap.notificationChannel', held: has('hook:notification-channel') }, + { icon: Radio, key: 'admin.plugins.cap.events', held: has('events:subscribe') }, +] + +// A Map rather than an object literal, so a slot named after an Object.prototype +// member reads as an unknown slot instead of as that member. +const WIDGET_SLOT_KEYS: ReadonlyMap = new Map([ + ['hero', 'admin.plugins.cap.heroWidget'], + ['place-detail', 'admin.plugins.cap.placeSlot'], + ['day-detail', 'admin.plugins.cap.daySlot'], + ['reservation-detail', 'admin.plugins.cap.reservationSlot'], +]) + +const OUTBOUND = 'http:outbound:' + +/** + * A plugin's declared permissions and capabilities as the at-a-glance chips that + * make its real reach legible without opening the detail view. + */ +export function deriveCaps(perms: readonly string[], caps: PluginCapsSlice, t: Translate): PluginCap[] { + const chip = (rule: ChipRule): PluginCap => ({ icon: rule.icon, label: t(rule.key) }) + const out = DATA_CHIPS.filter(rule => rule.held(perms)).map(chip) + if (caps.widget) { + out.push({ icon: LayoutDashboard, label: t(WIDGET_SLOT_KEYS.get(caps.widget.slot ?? '') ?? 'admin.plugins.cap.widget') }) + } + // Replacing planner tabs is the one capability that hides core UI, so it always gets a chip. + if (caps.tripPage?.replaces?.length) out.push({ icon: LayoutDashboard, label: t('admin.plugins.cap.replacesTabs') }) + out.push(...HOOK_CHIPS.filter(rule => rule.held(perms)).map(chip)) + for (const perm of perms) { + const host = perm.startsWith(OUTBOUND) ? perm.slice(OUTBOUND.length) : '' + if (host) out.push({ icon: ArrowRight, label: host, net: true }) + } + return out +} + +/** One explore-pill category a plugin declares, ready for the admin panel to draw. */ +export interface DeclaredPoiCategory { + id: string + label: string + Icon: LucideIcon + color: string +} + +/** + * The explore-pill categories a plugin declares (#1781), the way its users would get + * them: checked again against the shared schema by the reader the plugin feed goes + * through, labelled in the admin's language, with the icon taken from the allow-list + * and the colour checked before it becomes a CSS value. Empty unless the plugin also + * asks for the grant, because without it the feed never serves the categories. + */ +export function declaredPoiCategories( + pluginId: string, + perms: readonly string[], + raw: unknown, + language: string, +): DeclaredPoiCategory[] { + if (!perms.includes(POI_CATEGORY_PERMISSION)) return [] + return readPoiCategories(pluginId, raw).map(category => ({ + id: category.id, + label: pluginPoiCategoryLabel(category, language), + Icon: resolvePluginPoiIcon(category.icon), + color: pluginPoiColor(category.color), + })) +} diff --git a/client/src/components/Map/MapView.test.tsx b/client/src/components/Map/MapView.test.tsx index 579c0e504..4bdfb8e5b 100644 --- a/client/src/components/Map/MapView.test.tsx +++ b/client/src/components/Map/MapView.test.tsx @@ -9,6 +9,8 @@ import { MAP_MAX_ZOOM } from '../../constants/mapDefaults' import { useAuthStore } from '../../store/authStore' import { CATEGORY_ICON_MAP } from '../shared/categoryIcons' import * as photoService from '../../services/photoService' +import { Coffee, MapPin, Mountain, Signpost, type LucideIcon } from 'lucide-react' +import { renderIconMarkup } from '../../utils/iconMarkup' const mapMock = vi.hoisted(() => ({ getContainer: vi.fn(() => document.createElement('div')), @@ -753,6 +755,84 @@ describe('MapView explore POIs', () => { expect(markersWithZ('500')).toHaveLength(2) expect(poiIcons).toHaveLength(1) }) + + const pinGlyph = (Icon: LucideIcon) => React.createElement(Icon, { size: 13, color: 'white', strokeWidth: 2.5 }) + const poiPinHtmls = async () => (await leafletMock()).divIcon.mock.calls + .filter(c => JSON.stringify((c[0] as { iconSize: number[] }).iconSize) === '[26,26]') + .map(c => (c[0] as { html: string }).html) + + it('FE-COMP-MAPVIEW-084: a core POI pin is the disc it always was', () => { + render() + expect(iconHtmlOf(markersWithZ('500')[0])).toBe( + '
' + + `${renderIconMarkup(pinGlyph(Coffee))}
`, + ) + }) + + it('FE-COMP-MAPVIEW-085: a plugin POI pin takes the colour and icon its POI carries, checked first', () => { + render(' }), + ]} />) + const [good, bad] = markersWithZ('500').map(iconHtmlOf) + expect(good).toContain('background:#2f855a;') + expect(good).toContain(renderIconMarkup(pinGlyph(Signpost))) + expect(bad).toContain('background:#6b7280;') + expect(bad).toContain(renderIconMarkup(pinGlyph(MapPin))) + expect(bad).not.toContain('evil.example') + expect(bad).not.toContain(' { + const trail = { category: 'plugin:trail-finder/trails-086', color: '#2f855a', icon: 'Signpost' } + const { rerender } = render() + expect(await poiPinHtmls()).toHaveLength(2) + const [first, second, well] = markersWithZ('500').map(iconHtmlOf) + expect(second).toBe(first) + expect(first).toContain('#2f855a') + expect(well).toContain('#3182ce') + expect(well).toContain(renderIconMarkup(pinGlyph(Mountain))) + // The plugin changed its colour in an update: the same category gets a new pin. + rerender() + expect(iconHtmlOf(markersWithZ('500')[0])).toContain('background:#c53030;') + }) + + it('FE-COMP-MAPVIEW-087: a plugin POI tooltip lists its detail rows as text, a core one stays the bare name', () => { + render(', + details: [{ label: 'Length', value: '12.4 km' }, { label: 'Fee', value: '">' }], + }), + ]} />) + const [core, plugin] = markersWithZ('500') + expect(core.querySelector('[data-testid="poi-details"]')).toBeNull() + const details = plugin.querySelector('[data-testid="poi-details"]')! + expect([...details.querySelectorAll('span')].map(el => el.textContent)).toEqual([ + 'Length', '12.4 km', 'Fee', '">', + ]) + expect(plugin.textContent).toContain('') + expect(plugin.querySelectorAll('img, b, svg')).toHaveLength(0) + // Sized by its content up to the cap, since the 0px tooltip pane gives it nothing to fill. + expect([...(details.parentElement as HTMLElement).classList]).toEqual(expect.arrayContaining(['w-max', 'max-w-56'])) + }) + + it('FE-COMP-MAPVIEW-088: a long tooltip label wraps inside a capped column and leaves its value the wider share', () => { + render() + const details = markersWithZ('500')[0].querySelector('[data-testid="poi-details"]')! + expect(details.classList).toContain('grid-cols-[fit-content(45%)_1fr]') + const [label, value] = [...details.querySelectorAll('span')] + expect(label.classList).toContain('[overflow-wrap:anywhere]') + expect(value.classList).toContain('[overflow-wrap:anywhere]') + }) }) describe('MapView plugin route vias', () => { diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx index 9d0276ebe..1dd20de72 100644 --- a/client/src/components/Map/MapView.tsx +++ b/client/src/components/Map/MapView.tsx @@ -54,7 +54,8 @@ import NightPauseTooltip from './NightPauseTooltip' import ClusteredPois from './ClusteredPois' import { NightPauseDrag } from './NightPauseDrag' import type { DayBoundaryControls } from './dayBoundaryDrag' -import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories' +import type { Poi } from './poiCategories' +import { poiDetailRowKey, poiDetailRows, poiPinCacheKey, poiPinParts } from './poiMarker' import { resolveTrackColor, hasManualTrackColor } from './trackColors' import DawarichTrailLayer from './DawarichTrailLayer' import { OFM_POSITRON, DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM, MAP_MAX_ZOOM, SATELLITE_TILE_URL, SATELLITE_TILE_MAXZOOM, AMAP_SATELLITE, attributionForTile } from '../../constants/mapDefaults' @@ -232,18 +233,18 @@ function createPlaceIcon(place, orderNumbers, isSelected) { // Small coloured pin for an OSM "explore" POI — distinct from the photo-circle // markers of planned places; the colour matches its pill category. const poiIconCache = new Map() -function createPoiIcon(category: string, brandWikidata?: string | null) { +function createPoiIcon(poi: Pick, brandWikidata?: string | null) { // One flat disc in the category's colour with its icon, and never the chain's logo. // The brands turned a corridor full of petrol stations into a row of advertisements, // they were unreadable at pin size, and a brand with no logo on file fell back to a // different picture entirely — so no two pins looked alike. `brandWikidata` is kept in // the signature because the callers still have it; it simply no longer changes anything. void brandWikidata - const cached = poiIconCache.get(category) + // A plugin category's key carries its colour and icon too, so two looks never share a pin. + const cacheKey = poiPinCacheKey(poi) + const cached = poiIconCache.get(cacheKey) if (cached) return cached - const cat = POI_CATEGORY_BY_KEY[category] - const color = cat?.color || '#6b7280' - const svg = cat ? renderIconMarkup(createElement(cat.Icon, { size: 13, color: 'white', strokeWidth: 2.5 })) : '' + const { color, svg } = poiPinParts(poi) const icon = L.divIcon({ className: '', html: `
${svg}
`, @@ -251,10 +252,37 @@ function createPoiIcon(category: string, brandWikidata?: string | null) { iconAnchor: [13, 13], tooltipAnchor: [0, -14], }) - poiIconCache.set(category, icon) + poiIconCache.set(cacheKey, icon) return icon } +/** + * The hover tooltip of an explore POI: its name, and for a plugin POI the rows the + * plugin knows about it (the GL hover card shows the same, see buildPoiPopupHtml). + * React text throughout, so nothing a plugin sends is ever read as markup. A POI + * without rows keeps the bare name it has always had. + */ +function PoiTooltipBody({ poi }: Readonly<{ poi: Poi }>) { + const rows = poiDetailRows(poi) + if (!rows.length) return poi.name + // w-max because Leaflet's tooltip pane is 0px wide: without an intrinsic width the + // tooltip shrinks to its narrowest layout and the values wrap a letter per line. The + // label column stops at 45% and wraps, so a long label leaves its value room too. + return ( +
+
{poi.name}
+
+ {rows.map(row => ( +
+ {row.label} + {row.value} +
+ ))} +
+
+ ) +} + // Clears the hover tooltip the moment the camera starts moving and suppresses // re-showing it until the move ends: after a click-recenter the marker slides // away under a stationary cursor, so the browser never fires mouseout — and @@ -749,7 +777,7 @@ export const MapView = memo(function MapView({ key={`poi-${poi.osm_id}`} alt={poi.name} position={[poi.lat, poi.lng]} - icon={createPoiIcon(poi.category, poi.brand_wikidata)} + icon={createPoiIcon(poi, poi.brand_wikidata)} zIndexOffset={500} eventHandlers={{ click: () => onPoiClick?.(poi), @@ -765,7 +793,7 @@ export const MapView = memo(function MapView({ }, }} > - {poi.name} + )), [pois, onPoiClick, onPoiDropOnRoute]) const visibleReservations = useMemo(() => ( diff --git a/client/src/components/Map/MapViewGL.test.tsx b/client/src/components/Map/MapViewGL.test.tsx index ceb7a585f..5acb542b3 100644 --- a/client/src/components/Map/MapViewGL.test.tsx +++ b/client/src/components/Map/MapViewGL.test.tsx @@ -14,6 +14,8 @@ import { MAP_LAYER_SWITCHER_INSET } from './MapLayerSwitcher' import type { GeoPosition, TrackingMode } from '../../hooks/useGeolocation' import type { PluginMapLayer, PluginMapLayerFeature, PluginMapMarker } from '../../api/client' import type { Poi } from './poiCategories' +import { Coffee, type LucideIcon } from 'lucide-react' +import { renderIconMarkup } from '../../utils/iconMarkup' import type { RouteVia } from '../../types' // Stable fake map so fitBounds call counts survive re-renders. The canvas @@ -1465,6 +1467,58 @@ describe('MapViewGL', () => { vi.mocked(glMap.getZoom).mockReturnValue(10) }) + const pinGlyph = (Icon: LucideIcon) => renderIconMarkup(React.createElement(Icon, { size: 13, color: 'white', strokeWidth: 2.5 })) + const explorePoi = (overrides: Partial): Poi => ({ + osm_id: 'n1', name: 'Café de Flore', lat: 48.854, lng: 2.332, category: 'cafe', + poi_type: 'cafe', address: null, website: null, phone: null, opening_hours: null, + cuisine: null, source: 'openstreetmap', ...overrides, + }) + + it('FE-COMP-MAPVIEWGL-104: a core POI pin is the disc it always was', async () => { + loadOnAttach() + render() + await act(async () => {}) + // Parsed the same way the element's own markup was, so only a real change shows up. + const expected = document.createElement('div') + expected.innerHTML = '
' + + `${pinGlyph(Coffee)}
` + expect(glMarkers.created[0].element.innerHTML).toBe(expected.innerHTML) + }) + + it('FE-COMP-MAPVIEWGL-105: a plugin POI pin and its hover card use its checked colour and icon, and its details stay text', async () => { + loadOnAttach() + const plugin = explorePoi({ + osm_id: 'plugin:trail-finder:1', name: '', category: 'plugin:trail-finder/trailheads', + source: 'plugin:trail-finder', pluginId: 'trail-finder', color: '#2f855a', icon: 'Signpost', + details: [{ label: 'Length', value: '12.4 km' }, { label: 'Fee', value: '">' }], + }) + const bad = explorePoi({ + osm_id: 'plugin:trail-finder:2', category: 'plugin:trail-finder/trailheads', + color: 'red;background:url(https://evil.example/x)', icon: '', + }) + render() + await act(async () => {}) + + const [good, fallback] = glMarkers.created.map(pin => pin.element) + expect(good.innerHTML).toContain('background:#2f855a;') + expect(good.querySelectorAll('svg')).toHaveLength(1) + expect(good.querySelector('svg.lucide-signpost')).not.toBeNull() + expect(fallback.innerHTML).toContain('background:#6b7280;') + expect(fallback.innerHTML).not.toContain('evil.example') + expect(fallback.querySelectorAll('img')).toHaveLength(0) + expect(fallback.querySelector('svg.lucide-map-pin')).not.toBeNull() + + act(() => { good.dispatchEvent(new MouseEvent('mouseenter')) }) + const card = document.createElement('div') + card.innerHTML = vi.mocked(glPopup.setHTML).mock.lastCall![0] + expect(card.querySelectorAll('img, b')).toHaveLength(0) + expect(card.querySelectorAll('svg')).toHaveLength(1) + expect(card.textContent).toContain('') + expect([...card.querySelectorAll('div[style*="grid-template-columns"] > span')].map(el => el.textContent)).toEqual([ + 'Length', '12.4 km', 'Fee', '">', + ]) + }) + it('FE-COMP-MAPVIEWGL-043: plugin markers render as tone dots with a text-only popup', async () => { loadOnAttach() const markers: PluginMapMarker[] = [ diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index b122575cf..bb0f53773 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -36,7 +36,8 @@ import { bindDayBoundaryDrag, type DayBoundaryControls } from './dayBoundaryDrag import NightPauseTooltip from './NightPauseTooltip' import PlaceHoverCard from './PlaceHoverCard' import { ratingBadgeHtml } from './ratingBadge' -import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories' +import type { Poi } from './poiCategories' +import { poiPinParts } from './poiMarker' import { resolveTrackColor, hasManualTrackColor } from './trackColors' import { buildPoiPopupHtml } from './placePopup' import { pluginsApi, type PluginMapMarker, type PluginMapLayer } from '../../api/client' @@ -646,10 +647,10 @@ function buildPluginMarkerPopup(mk: PluginMapMarker): HTMLDivElement { // A chain shows its logo instead of the category icon: on a corridor full of petrol // stations the brand is what the eye is looking for, and the server proxies it so the // browser never asks Wikimedia which ones are on screen. -function createPoiMarkerElement(category: string, brandWikidata?: string | null): HTMLDivElement { - const cat = POI_CATEGORY_BY_KEY[category] - const color = cat?.color || '#6b7280' - const svg = cat ? renderIconMarkup(createElement(cat.Icon, { size: 13, color: 'white', strokeWidth: 2.5 })) : '' +function createPoiMarkerElement(poi: Pick, brandWikidata?: string | null): HTMLDivElement { + // The same parts the Leaflet pin is built from: a plugin POI's own colour and icon, + // both checked before they get anywhere near innerHTML. + const { color, svg } = poiPinParts(poi) const el = document.createElement('div') el.style.cssText = 'width:26px;height:26px;cursor:pointer;will-change:transform;' el.innerHTML = `
${svg}${brandLogoMarkup(brandWikidata)}
` @@ -1994,7 +1995,7 @@ export function MapViewGL({ continue } const poi = group.pois[0] - const el = createPoiMarkerElement(poi.category, poi.brand_wikidata) + const el = createPoiMarkerElement(poi, poi.brand_wikidata) el.addEventListener('mouseenter', () => { popupRef.current?.setLngLat([poi.lng, poi.lat]).setHTML(buildPoiPopupHtml(poi)).addTo(map) }) diff --git a/client/src/components/Map/PoiCategoryPill.test.tsx b/client/src/components/Map/PoiCategoryPill.test.tsx index d1f79bdc4..669255198 100644 --- a/client/src/components/Map/PoiCategoryPill.test.tsx +++ b/client/src/components/Map/PoiCategoryPill.test.tsx @@ -1,17 +1,37 @@ -// FE-COMP-POIPILL-001 to FE-COMP-POIPILL-008 +// FE-COMP-POIPILL-001 to FE-COMP-POIPILL-018 import React from 'react' import { describe, it, expect, vi } from 'vitest' import { render, screen } from '../../../tests/helpers/render' import { fireEvent } from '@testing-library/react' import PoiCategoryPill from './PoiCategoryPill' import { POI_CATEGORIES } from './poiCategories' +import { corePoiCategories, pluginPoiCategories, type PoiCategoryGroups } from './usePoiCategories' const CAFE = POI_CATEGORIES.find(c => c.key === 'cafe')! const BAR = POI_CATEGORIES.find(c => c.key === 'bar')! +// The labels the English UI gives the core chips, as usePoiCategories hands them over. +const EN: Record = { + 'poi.cat.restaurants': 'Restaurants', 'poi.cat.cafes': 'Cafés', 'poi.cat.bars': 'Bars & nightlife', + 'poi.cat.hotels': 'Accommodation', 'poi.cat.sights': 'Sights', 'poi.cat.museums': 'Museums & culture', + 'poi.cat.nature': 'Nature & parks', 'poi.cat.activities': 'Activities', +} +const CORE_ONLY: PoiCategoryGroups = { core: corePoiCategories(key => EN[key] ?? key), plugin: [] } +const WITH_PLUGINS: PoiCategoryGroups = { + core: CORE_ONLY.core, + plugin: pluginPoiCategories([{ + id: 'trail-finder', name: 'Trail finder', type: 'integration', icon: null, + poiCategories: [ + { id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' }, + { id: 'water', label: 'Drinking water', icon: 'Droplet', color: '#0369a1' }, + ], + }], 'en'), +} +const TRAILHEADS = 'plugin:trail-finder/trailheads' + function pill(props: Partial> = {}) { return render( - , + , ) } @@ -21,6 +41,8 @@ const spinning = () => screen.getAllByRole('button') .filter(b => b.querySelector('.animate-spin')) .map(b => b.getAttribute('aria-label')) +const labels = () => screen.getAllByRole('button').map(b => b.getAttribute('aria-label')) + describe('PoiCategoryPill', () => { it('FE-COMP-POIPILL-001: renders one segment per category, none pressed', () => { pill() @@ -75,4 +97,121 @@ describe('PoiCategoryPill', () => { expect(button.style.width).toBe('34px') expect((button.parentElement as HTMLElement).style.display).toBe('inline-flex') }) + + it('FE-COMP-POIPILL-009: without plugin categories there is no divider and every segment sits in the bar', () => { + pill() + expect(screen.queryByRole('separator')).toBeNull() + const bar = screen.getAllByRole('button')[0].parentElement as HTMLElement + expect(bar.children).toHaveLength(POI_CATEGORIES.length) + }) + + it('FE-COMP-POIPILL-010: plugin categories follow the core ones after a labelled divider', () => { + pill({ categories: WITH_PLUGINS }) + expect(labels()).toEqual([...CORE_ONLY.core.map(c => c.label), 'Trailheads', 'Drinking water']) + const divider = screen.getByRole('separator', { name: 'Categories from plugins' }) + const bar = divider.parentElement as HTMLElement + // In the same bar, straight after the last core segment. + expect(Array.from(bar.children).indexOf(divider)).toBe(POI_CATEGORIES.length) + expect(divider.getAttribute('aria-orientation')).toBe('vertical') + }) + + it('FE-COMP-POIPILL-011: a plugin segment toggles its namespaced key and fills with its own colour', () => { + const onToggle = vi.fn() + const { rerender } = pill({ categories: WITH_PLUGINS, onToggle }) + fireEvent.click(screen.getByRole('button', { name: 'Trailheads' })) + expect(onToggle).toHaveBeenCalledWith(TRAILHEADS) + + rerender() + const segment = screen.getByRole('button', { name: 'Trailheads' }) + expect(segment.getAttribute('aria-pressed')).toBe('true') + expect(segment.style.background).toBe('rgb(47, 133, 90)') + // A failing plugin category offers the same retry a core one does. + expect(screen.getByText('Search this area')).toBeInTheDocument() + }) + + it('FE-COMP-POIPILL-012: the bar scrolls sideways once it runs out of room', () => { + pill({ categories: WITH_PLUGINS, fullWidth: true }) + const bar = screen.getAllByRole('button')[0].parentElement as HTMLElement + expect(bar.style.overflowX).toBe('auto') + expect(bar.style.maxWidth).toBe('100%') + // The column around it may shrink, or the bar would push past its container instead. + expect((bar.parentElement as HTMLElement).style.minWidth).toBe('0px') + }) + + it('FE-COMP-POIPILL-013: a phone segment never shrinks below the 34px touch target', () => { + pill({ categories: WITH_PLUGINS, fullWidth: true }) + for (const button of screen.getAllByRole('button')) { + expect(button.style.minWidth).toBe('34px') + expect(button.style.height).toBe('34px') + } + }) + + it('FE-COMP-POIPILL-014: a desktop segment keeps its 34px instead of shrinking in a narrow corridor', () => { + pill({ categories: WITH_PLUGINS }) + for (const button of screen.getAllByRole('button')) { + expect(button.style.flexShrink).toBe('0') + expect(button.style.minWidth).toBe('34px') + } + expect((screen.getByRole('separator').style.flexShrink)).toBe('0') + }) + + it('FE-COMP-POIPILL-015: hovering highlights an idle segment and leaves an active one its colour', () => { + pill({ categories: WITH_PLUGINS, active: new Set([TRAILHEADS]) }) + const idle = screen.getByRole('button', { name: 'Drinking water' }) + fireEvent.mouseEnter(idle) + expect(idle.style.background).toBe('var(--bg-hover)') + fireEvent.mouseLeave(idle) + expect(idle.style.background).toBe('transparent') + + const on = screen.getByRole('button', { name: 'Trailheads' }) + fireEvent.mouseEnter(on) + fireEvent.mouseLeave(on) + expect(on.style.background).toBe('rgb(47, 133, 90)') + }) + + // jsdom lays nothing out, so the bar is given the widths a narrow desktop corridor would. + const barOf = (clientWidth: number, scrollWidth: number) => { + const bar = screen.getByRole('separator').parentElement as HTMLElement + Object.defineProperty(bar, 'clientWidth', { configurable: true, value: clientWidth }) + Object.defineProperty(bar, 'scrollWidth', { configurable: true, value: scrollWidth }) + return bar + } + + it('FE-COMP-POIPILL-016: a mouse wheel scrolls an overflowing desktop bar sideways, in pixels, lines or pages', () => { + pill({ categories: WITH_PLUGINS }) + const bar = barOf(300, 450) + fireEvent.wheel(bar, { deltaY: 100 }) + expect(bar.scrollLeft).toBe(100) + fireEvent.wheel(bar, { deltaY: 1, deltaMode: WheelEvent.DOM_DELTA_LINE }) + expect(bar.scrollLeft).toBe(134) + fireEvent.wheel(bar, { deltaY: 0.5, deltaMode: WheelEvent.DOM_DELTA_PAGE }) + expect(bar.scrollLeft).toBe(284) + }) + + it('FE-COMP-POIPILL-017: the wheel is left alone when the bar fits or the turn is already sideways', () => { + pill({ categories: WITH_PLUGINS }) + const bar = barOf(450, 450) + fireEvent.wheel(bar, { deltaY: 100 }) + expect(bar.scrollLeft).toBe(0) + // A trackpad swipe or Shift+wheel scrolls the bar natively; adding to it would double it. + barOf(300, 450) + fireEvent.wheel(bar, { deltaX: 40, deltaY: 10 }) + expect(bar.scrollLeft).toBe(0) + }) + + it('FE-COMP-POIPILL-018: in a right-to-left language a wheel-down still moves toward the plugin chips', () => { + // The app sets the page direction from the language (TranslationContext) and the bar + // inherits it. The test provider renders in English, so a wrapper stands in for Arabic. + render( +
+ +
, + ) + const bar = barOf(300, 450) + // An RTL scroller counts scrollLeft from 0 at the start down to negative at the end. + fireEvent.wheel(bar, { deltaY: 100 }) + expect(bar.scrollLeft).toBe(-100) + fireEvent.wheel(bar, { deltaY: -40 }) + expect(bar.scrollLeft).toBe(-60) + }) }) diff --git a/client/src/components/Map/PoiCategoryPill.tsx b/client/src/components/Map/PoiCategoryPill.tsx index 7dd0ef59a..a9a623b3f 100644 --- a/client/src/components/Map/PoiCategoryPill.tsx +++ b/client/src/components/Map/PoiCategoryPill.tsx @@ -1,9 +1,11 @@ import { RotateCw, AlertTriangle } from 'lucide-react' import { useTranslation } from '../../i18n' import { Tooltip } from '../shared/Tooltip' -import { POI_CATEGORIES } from './poiCategories' +import type { ExplorePoiCategory, PoiCategoryGroups } from './usePoiCategories' interface Props { + /** The chips to offer, from usePoiCategories by way of usePoiExplore. */ + categories: PoiCategoryGroups active: Set onToggle: (key: string) => void loadingKeys?: Set @@ -18,10 +20,95 @@ interface Props { fullWidth?: boolean } +// The touch target every segment keeps, however many categories there are. +const SEGMENT = 34 + +// How far one wheel step moves the bar. Firefox counts a mouse wheel in lines and +// some drivers in pages; a line moves about one segment, a page one bar width. +function wheelPixels(e: React.WheelEvent, barWidth: number): number { + if (e.deltaMode === WheelEvent.DOM_DELTA_LINE) return e.deltaY * SEGMENT + if (e.deltaMode === WheelEvent.DOM_DELTA_PAGE) return e.deltaY * barWidth + return e.deltaY +} + +// The bar only ever overflows sideways and a plain mouse wheel only turns vertically, +// so on desktop the chips past the corridor edge (the plugin ones first) were out of +// reach without a trackpad. While the bar overflows, a mostly vertical turn scrolls it +// sideways. A sideways swipe or Shift+wheel already scrolls it natively and is left alone. +// In a right-to-left language the chips overflow to the left and scrollLeft runs from 0 +// down into negative numbers, so the same turn has to count the other way to reach them. +function wheelSideways(e: React.WheelEvent) { + const bar = e.currentTarget + if (bar.scrollWidth <= bar.clientWidth || Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return + const towardEnd = getComputedStyle(bar).direction === 'rtl' ? -1 : 1 + bar.scrollLeft += towardEnd * wheelPixels(e, bar.clientWidth) +} + +interface SegmentProps { + cat: ExplorePoiCategory + on: boolean + loading: boolean + failed: boolean + fullWidth?: boolean + onToggle: (key: string) => void +} + +function Segment({ cat, on, loading, failed, fullWidth, onToggle }: Readonly) { + return ( + + + + ) +} + // Frosted, icon-only segmented control that floats over the map. Active segments // fill with the category colour (matching their markers); the label shows in a -// custom tooltip on hover so the pill stays compact and never needs to scroll. -export default function PoiCategoryPill({ active, onToggle, loadingKeys, errorKeys, moved, onSearchArea, fullWidth }: Props) { +// custom tooltip on hover so the pill stays compact. The core categories come first +// and whatever plugins add follows a thin divider (#1781); once that is more than the +// width holds, the bar scrolls sideways (by swipe, trackpad or mouse wheel) rather than +// shrinking a segment below the touch target. +export default function PoiCategoryPill({ categories, active, onToggle, loadingKeys, errorKeys, moved, onSearchArea, fullWidth }: Readonly) { const { t } = useTranslation() const anyError = !!errorKeys && Array.from(active).some(k => errorKeys.has(k)) @@ -32,63 +119,41 @@ export default function PoiCategoryPill({ active, onToggle, loadingKeys, errorKe boxShadow: 'var(--sidebar-shadow, 0 4px 16px rgba(0,0,0,0.14))', } + const segment = (cat: ExplorePoiCategory) => { + const on = active.has(cat.key) + // Only an active category can be loading: a deselected one whose fetch + // is still winding down must not keep spinning. + const loading = on && !!loadingKeys?.has(cat.key) + return ( + + ) + } + return ( -
-
+
- {POI_CATEGORIES.map(cat => { - const on = active.has(cat.key) - // Only an active category can be loading — a deselected one whose fetch - // is still winding down must not keep spinning. - const loading = on && !!loadingKeys?.has(cat.key) - return ( - - - - ) - })} + {categories.core.map(segment)} + {categories.plugin.length > 0 && ( +
+ )} + {categories.plugin.map(segment)}
{(moved || anyError) && active.size > 0 && ( @@ -99,7 +164,7 @@ export default function PoiCategoryPill({ active, onToggle, loadingKeys, errorKe style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 13px', borderRadius: 999, border: 'none', cursor: 'pointer', - fontSize: 12, fontWeight: 600, fontFamily: 'inherit', pointerEvents: 'auto', + fontSize: 'calc(12px * var(--fs-scale-caption, 1))', fontWeight: 600, fontFamily: 'inherit', pointerEvents: 'auto', color: anyError ? '#ef4444' : undefined, ...frosted, }} diff --git a/client/src/components/Map/placePopup.test.ts b/client/src/components/Map/placePopup.test.ts index 9eea982b2..ca1028123 100644 --- a/client/src/components/Map/placePopup.test.ts +++ b/client/src/components/Map/placePopup.test.ts @@ -1,5 +1,8 @@ -// FE-COMP-PLACEPOPUP-001 to FE-COMP-PLACEPOPUP-014 +// FE-COMP-PLACEPOPUP-001 to FE-COMP-PLACEPOPUP-021 import { describe, it, expect } from 'vitest' +import { createElement } from 'react' +import { Coffee, MapPin, Signpost, type LucideIcon } from 'lucide-react' +import { renderIconMarkup } from '../../utils/iconMarkup' import { buildPlacePopupHtml, buildPoiPopupHtml } from './placePopup' import { buildPlace } from '../../../tests/helpers/factories' import type { Poi } from './poiCategories' @@ -47,6 +50,13 @@ describe('buildPlacePopupHtml', () => { expect(html).not.toContain(' { + const html = buildPlacePopupHtml(popupPlace({ name: undefined as never, address: null }), null) + // The name line is there and empty. + expect(html).toContain('white-space:nowrap;">
') + expect(html).not.toContain('undefined') + }) + it('FE-COMP-PLACEPOPUP-002: escapes HTML metacharacters in the name', () => { const html = buildPlacePopupHtml(popupPlace({ name: 'Bar & "Grill" x' }), null) expect(html).toContain('Bar & "Grill" <b>x</b>') @@ -130,3 +140,78 @@ describe('buildPoiPopupHtml', () => { expect(buildPoiPopupHtml(poi({ address: 'Herrengasse 14 & 16' }))).toContain('Herrengasse 14 & 16') }) }) + +describe('buildPoiPopupHtml looks and plugin details', () => { + const PLUGIN_KEY = 'plugin:trail-finder/trailheads' + const icon = (Icon: LucideIcon, color: string) => renderIconMarkup(createElement(Icon, { size: 12, color, strokeWidth: 2 })) + const parse = (html: string) => { + const box = document.createElement('div') + box.innerHTML = html + return box + } + + it('FE-COMP-PLACEPOPUP-015: a core POI card is the one it always was, with no details block', () => { + const html = buildPoiPopupHtml(poi({ name: 'Café Central', category: 'cafe', address: 'Herrengasse 14' })) + expect(html).toBe( + '
' + + `
${icon(Coffee, '#B45309')}` + + 'Café Central
' + + '
Herrengasse 14
', + ) + }) + + it('FE-COMP-PLACEPOPUP-016: shows the icon and colour the POI carries and its detail rows in order', () => { + const html = buildPoiPopupHtml(poi({ + category: PLUGIN_KEY, name: 'Trailhead', color: '#2f855a', icon: 'Signpost', + details: [{ label: 'Length', value: '12.4 km' }, { label: 'Step-free', value: 'Yes' }], + })) + expect(html).toContain(icon(Signpost, '#2f855a')) + const cells = [...parse(html).querySelectorAll('div[style*="grid-template-columns"] > span')].map(el => el.textContent) + expect(cells).toEqual(['Length', '12.4 km', 'Step-free', 'Yes']) + }) + + it('FE-COMP-PLACEPOPUP-017: markup in the name, the address and the details stays text', () => { + const html = buildPoiPopupHtml(poi({ + category: PLUGIN_KEY, + name: '', + address: '
', + color: '#2f855a', icon: 'Signpost', + details: [{ label: 'Fee', value: '">' }], + })) + const box = parse(html) + expect(box.querySelectorAll('img, script, b')).toHaveLength(0) + // The only svg is the category glyph, never one a value smuggled in. + expect(box.querySelectorAll('svg')).toHaveLength(1) + expect(box.textContent).toContain('') + expect(box.textContent).toContain('Fee') + expect(box.textContent).toContain('">') + }) + + it('FE-COMP-PLACEPOPUP-018: a colour or icon that fails the checks is drawn grey with a pin', () => { + const html = buildPoiPopupHtml(poi({ + category: PLUGIN_KEY, color: 'red;background:url(https://evil.example/x)', icon: '', + })) + expect(html).toContain(icon(MapPin, '#6b7280')) + expect(html).not.toContain('evil.example') + expect(parse(html).querySelectorAll('img')).toHaveLength(0) + }) + + it('FE-COMP-PLACEPOPUP-019: shows at most the six rows the contract allows', () => { + const details = Array.from({ length: 9 }, (_, i) => ({ label: `Row ${i}`, value: String(i) })) + const html = buildPoiPopupHtml(poi({ category: PLUGIN_KEY, color: '#2f855a', icon: 'Signpost', details })) + expect(parse(html).querySelectorAll('div[style*="grid-template-columns"] > span')).toHaveLength(12) + expect(html).not.toContain('Row 6') + }) + + it('FE-COMP-PLACEPOPUP-020: a long label wraps inside a capped column and leaves its value the wider share', () => { + const html = buildPoiPopupHtml(poi({ + category: PLUGIN_KEY, color: '#2f855a', icon: 'Signpost', + details: [{ label: 'Wheelchair accessible toilet, ground fl', value: 'Step-free via the side door on the left' }], + })) + const grid = parse(html).querySelector('div[style*="grid-template-columns"]')! + expect(grid.style.gridTemplateColumns).toBe('fit-content(45%) 1fr') + const [label, value] = [...grid.querySelectorAll(':scope > span')] + expect(label.style.overflowWrap).toBe('anywhere') + expect(value.style.overflowWrap).toBe('anywhere') + }) +}) diff --git a/client/src/components/Map/placePopup.ts b/client/src/components/Map/placePopup.ts index 930f8466d..60eba908d 100644 --- a/client/src/components/Map/placePopup.ts +++ b/client/src/components/Map/placePopup.ts @@ -1,7 +1,9 @@ import { createElement } from 'react' +import { escapeHtml } from '@trek/shared' import { renderIconMarkup } from '../../utils/iconMarkup' import { CATEGORY_ICON_MAP } from '../shared/categoryIcons' -import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories' +import { poiAppearance, type Poi } from './poiCategories' +import { poiDetailRows } from './poiMarker' import type { Place } from '../../types' // HTML builders for the Mapbox GL hover popup. The Leaflet map already shows a @@ -16,12 +18,7 @@ type PlaceWithCategory = Place & { } function esc(s: string | null | undefined): string { - if (!s) return '' - return String(s) - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') + return s ? escapeHtml(String(s)) : '' } // Render a lucide category icon to an inline SVG string in the given colour. @@ -43,6 +40,13 @@ function isDisplayablePhoto(url: string | null | undefined): url is string { const CARD_OPEN = '
' const NAME_STYLE = 'font-weight:600;font-size:12.5px;color:#111827;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' const ADDR_STYLE = 'font-size:11px;color:#9ca3af;margin-top:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' +// A plugin POI's detail rows: label and value side by side, the value free to wrap so a +// long one grows the card downwards instead of pushing it off the side of the map. The +// label column stops at 45% and wraps too, so a long label cannot squeeze its value +// into a strip a few letters wide. +const DETAILS_STYLE = 'display:grid;grid-template-columns:fit-content(45%) 1fr;gap:1px 6px;margin-top:4px;font-size:11px;line-height:1.35;' +const DETAIL_LABEL_STYLE = 'color:#6b7280;overflow-wrap:anywhere;' +const DETAIL_VALUE_STYLE = 'color:#111827;overflow-wrap:anywhere;' /** Hover-popup card for a planned place: optional photo, name, category row, address. */ export function buildPlacePopupHtml(place: PlaceWithCategory, photoUrl: string | null): string { @@ -57,12 +61,23 @@ export function buildPlacePopupHtml(place: PlaceWithCategory, photoUrl: string | return `${CARD_OPEN}${img}
${esc(place.name)}
${category}${address}
` } -/** Hover-popup card for an OSM "explore" POI: category-coloured icon, name, address. */ +/** + * Hover-popup card for an "explore" POI: category-coloured icon, name, address, and + * for a plugin POI the rows the plugin knows about it. The colour and icon come from + * poiAppearance, so a plugin's are checked before they are written into the card, and + * every piece of text is escaped. + */ export function buildPoiPopupHtml(poi: Poi): string { - const cat = POI_CATEGORY_BY_KEY[poi.category] - const color = cat?.color || '#6b7280' - const icon = cat ? renderIconMarkup(createElement(cat.Icon, { size: 12, color, strokeWidth: 2 })) : '' + const { color, Icon } = poiAppearance(poi) + const icon = Icon ? renderIconMarkup(createElement(Icon, { size: 12, color, strokeWidth: 2 })) : '' const head = `
${icon}${esc(poi.name)}
` const address = poi.address ? `
${esc(poi.address)}
` : '' - return `${CARD_OPEN}${head}${address}
` + return `${CARD_OPEN}${head}${address}${poiDetailsHtml(poi)}` +} + +function poiDetailsHtml(poi: Poi): string { + const rows = poiDetailRows(poi) + if (!rows.length) return '' + const cells = rows.map(row => `${esc(row.label)}${esc(row.value)}`) + return `
${cells.join('')}
` } diff --git a/client/src/components/Map/pluginPoiIcons.test.ts b/client/src/components/Map/pluginPoiIcons.test.ts new file mode 100644 index 000000000..1ffe942ab --- /dev/null +++ b/client/src/components/Map/pluginPoiIcons.test.ts @@ -0,0 +1,34 @@ +// FE-COMP-PLUGINPOIICON-001 to FE-COMP-PLUGINPOIICON-004 +import { describe, it, expect } from 'vitest' +import * as Lucide from 'lucide-react' +import { MapPin, Signpost } from 'lucide-react' +import { PLUGIN_POI_ICONS } from '@trek/shared' +import { POI_DEFAULT_COLOR, pluginPoiColor, resolvePluginPoiIcon } from './pluginPoiIcons' + +describe('resolvePluginPoiIcon', () => { + it('FE-COMP-PLUGINPOIICON-001: every allow-listed name resolves to the lucide icon of that name', () => { + const lucide = Lucide as unknown as Record + for (const name of PLUGIN_POI_ICONS) expect(resolvePluginPoiIcon(name)).toBe(lucide[name]) + expect(resolvePluginPoiIcon('Signpost')).toBe(Signpost) + }) + + it('FE-COMP-PLUGINPOIICON-002: anything off the list is a pin, never a lucide export of that name', () => { + // Real lucide exports, just not on the list, and names that are not icons at all. + for (const name of ['Skull', 'Blocks', 'createLucideIcon', 'icons', 'toString', '', null, undefined, 42]) { + expect(resolvePluginPoiIcon(name)).toBe(MapPin) + } + }) +}) + +describe('pluginPoiColor', () => { + it('FE-COMP-PLUGINPOIICON-003: a #rrggbb colour passes through unchanged', () => { + expect(pluginPoiColor('#2f855a')).toBe('#2f855a') + expect(pluginPoiColor('#2F855A')).toBe('#2F855A') + }) + + it('FE-COMP-PLUGINPOIICON-004: anything else is the default grey, markup included', () => { + for (const value of ['red', '#fff', '#2f855a;background:url(https://x)', 'url(https://x)', '">