Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

feat(plugins): plugins can add POI categories to the map and answer them

Maurice172773284125
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<PluginPoiResponse> =>
+ 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(<AdminPluginsPanel />)
+ 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(<AdminPluginsPanel />)
+ 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(<AdminPluginsPanel />)
+ 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(<AdminPluginsPanel />)
+ 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<T>(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
</div>
)}
+ <PluginPoiCategoryList pluginId={item.id} permissions={permissions} categories={manifest?.capabilities?.poiCategories}
+ className="mt-5" titleClassName="text-[11px] font-semibold uppercase tracking-wider text-content-muted"
+ itemClassName="text-[13px] text-content-secondary" />
+
{manifest && (egress.length > 0 || manifest.operatorEgress) && (
<div className="mt-5">
<h4 className="text-[11px] font-semibold uppercase tracking-wider text-content-muted">{t('admin.plugins.connectsTitle')}</h4>
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(
+ <PluginPoiCategoryList pluginId="trail-finder" permissions={permissions} categories={categories}
+ className="shell-place" titleClassName="shell-title" itemClassName="shell-row" />,
+ )
+}
+
+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: '<img src=x onerror=alert(1)>' }])
+
+ expect(screen.getByText('<img src=x onerror=alert(1)>')).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<Props>) {
+ const { t, language } = useTranslation()
+ const declared = declaredPoiCategories(pluginId, permissions, categories, language)
+ if (declared.length === 0) return null
+ return (
+ <div className={className}>
+ <h4 className={titleClassName}>{t('admin.plugins.poiCategoriesTitle')}</h4>
+ <ul className="mt-2 space-y-1.5">
+ {declared.map(({ id, label, Icon, color }) => (
+ <li key={id} className={`flex items-center gap-2.5 py-0.5 ${itemClassName}`}>
+ <span aria-hidden="true" data-testid="poi-category-swatch"
+ className="grid h-6 w-6 shrink-0 place-items-center rounded-full text-white"
+ style={{ backgroundColor: color }}>
+ <Icon size={13} strokeWidth={2} />
+ </span>
+ <span className="min-w-0">{label}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )
+}
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<string, string> = 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(<MapView pois={[buildPoi({ osm_id: 'node/20' })]} />)
+ expect(iconHtmlOf(markersWithZ('500')[0])).toBe(
+ '<div style="position:relative;width:26px;height:26px;border-radius:50%;background:#B45309;border:2px solid white;box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;cursor:pointer;overflow:hidden;">'
+ + `${renderIconMarkup(pinGlyph(Coffee))}</div>`,
+ )
+ })
+
+ it('FE-COMP-MAPVIEW-085: a plugin POI pin takes the colour and icon its POI carries, checked first', () => {
+ render(<MapView pois={[
+ buildPoi({ osm_id: 'plugin:trail-finder:1', category: 'plugin:trail-finder/pins-085', color: '#2f855a', icon: 'Signpost' }),
+ buildPoi({ osm_id: 'plugin:trail-finder:2', category: 'plugin:trail-finder/bad-085', color: 'red;background:url(https://evil.example/x)', icon: '<img src=x onerror=alert(1)>' }),
+ ]} />)
+ 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('<img')
+ })
+
+ it('FE-COMP-MAPVIEW-086: two plugin looks never share a cached pin, one look is built once', async () => {
+ const trail = { category: 'plugin:trail-finder/trails-086', color: '#2f855a', icon: 'Signpost' }
+ const { rerender } = render(<MapView pois={[
+ buildPoi({ osm_id: 'plugin:trail-finder:a', ...trail }),
+ buildPoi({ osm_id: 'plugin:trail-finder:b', ...trail, lat: 48.3 }),
+ buildPoi({ osm_id: 'plugin:water:c', category: 'plugin:water/wells-086', color: '#3182ce', icon: 'Mountain' }),
+ ]} />)
+ 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(<MapView pois={[buildPoi({ osm_id: 'plugin:trail-finder:a', ...trail, color: '#c53030' })]} />)
+ 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(<MapView pois={[
+ buildPoi({ osm_id: 'node/30', name: 'Café Central' }),
+ buildPoi({
+ osm_id: 'plugin:trail-finder:3', category: 'plugin:trail-finder/pins-087', color: '#2f855a', icon: 'Signpost',
+ name: '<img src=x onerror=alert(1)>',
+ details: [{ label: 'Length', value: '12.4 km' }, { label: '<b onclick=alert(2)>Fee</b>', value: '"><svg onload=alert(3)>' }],
+ }),
+ ]} />)
+ 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', '<b onclick=alert(2)>Fee</b>', '"><svg onload=alert(3)>',
+ ])
+ expect(plugin.textContent).toContain('<img src=x onerror=alert(1)>')
+ 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(<MapView pois={[buildPoi({
+ osm_id: 'plugin:trail-finder:4', category: 'plugin:trail-finder/pins-088', color: '#2f855a', icon: 'Signpost',
+ details: [{ label: 'Wheelchair accessible toilet, ground fl', value: 'Step-free via the side door on the left' }],
+ })]} />)
+ 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<string, L.DivIcon>()
-function createPoiIcon(category: string, brandWikidata?: string | null) {
+function createPoiIcon(poi: Pick<Poi, 'category' | 'icon' | 'color'>, 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: `<div style="position:relative;width:26px;height:26px;border-radius:50%;background:${color};border:2px solid white;box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;cursor:pointer;overflow:hidden;">${svg}</div>`,
@@ -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 (
+ <div className="w-max max-w-56 whitespace-normal">
+ <div className="truncate font-semibold">{poi.name}</div>
+ <div className="mt-1 grid grid-cols-[fit-content(45%)_1fr] gap-x-1.5 font-normal" data-testid="poi-details">
+ {rows.map(row => (
+ <div key={poiDetailRowKey(row)} className="contents">
+ <span className="text-content-muted [overflow-wrap:anywhere]">{row.label}</span>
+ <span className="[overflow-wrap:anywhere]">{row.value}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
+
// 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({
},
}}
>
- <Tooltip direction="top" offset={[0, -10]} opacity={1} className="map-tooltip">{poi.name}</Tooltip>
+ <Tooltip direction="top" offset={[0, -10]} opacity={1} className="map-tooltip"><PoiTooltipBody poi={poi} /></Tooltip>
</Marker>
)), [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>): 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(<MapViewGL places={[]} fitKey={1} pois={[explorePoi({})]} />)
+ 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 = '<div style="position:relative;width:26px;height:26px;border-radius:50%;background:#B45309;border:2px solid #fff;box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;box-sizing:border-box;overflow:hidden;">'
+ + `${pinGlyph(Coffee)}</div>`
+ 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: '<img src=x onerror=alert(1)>', category: 'plugin:trail-finder/trailheads',
+ source: 'plugin:trail-finder', pluginId: 'trail-finder', color: '#2f855a', icon: 'Signpost',
+ details: [{ label: 'Length', value: '12.4 km' }, { label: '<b>Fee</b>', value: '"><svg onload=alert(2)>' }],
+ })
+ const bad = explorePoi({
+ osm_id: 'plugin:trail-finder:2', category: 'plugin:trail-finder/trailheads',
+ color: 'red;background:url(https://evil.example/x)', icon: '<img src=x onerror=alert(3)>',
+ })
+ render(<MapViewGL places={[]} fitKey={1} pois={[plugin, bad]} />)
+ 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('<img src=x onerror=alert(1)>')
+ expect([...card.querySelectorAll('div[style*="grid-template-columns"] > span')].map(el => el.textContent)).toEqual([
+ 'Length', '12.4 km', '<b>Fee</b>', '"><svg onload=alert(2)>',
+ ])
+ })
+
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<Poi, 'category' | 'icon' | 'color'>, 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 = `<div style="position:relative;width:26px;height:26px;border-radius:50%;background:${color};border:2px solid #fff;box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;box-sizing:border-box;overflow:hidden;">${svg}${brandLogoMarkup(brandWikidata)}</div>`
@@ -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<string, string> = {
+ '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<React.ComponentProps<typeof PoiCategoryPill>> = {}) {
return render(
- <PoiCategoryPill active={new Set()} onToggle={vi.fn()} {...props} />,
+ <PoiCategoryPill categories={CORE_ONLY} active={new Set()} onToggle={vi.fn()} {...props} />,
)
}
@@ -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(<PoiCategoryPill categories={WITH_PLUGINS} active={new Set([TRAILHEADS])} onToggle={onToggle} errorKeys={new Set([TRAILHEADS])} />)
+ 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(
+ <div dir="rtl">
+ <PoiCategoryPill categories={WITH_PLUGINS} active={new Set()} onToggle={vi.fn()} />
+ </div>,
+ )
+ 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<string>
onToggle: (key: string) => void
loadingKeys?: Set<string>
@@ -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<HTMLDivElement>) {
+ 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<SegmentProps>) {
+ return (
+ <Tooltip label={cat.label} placement="bottom">
+ <button
+ type="button"
+ onClick={() => onToggle(cat.key)}
+ aria-pressed={on}
+ aria-label={cat.label}
+ className={on ? '' : 'text-content-muted'}
+ style={{
+ position: 'relative',
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
+ flexGrow: fullWidth ? 1 : undefined,
+ // Spread on the phone, fixed on desktop, and never narrower than the touch
+ // target either way: past that the bar scrolls instead of squeezing.
+ flexShrink: fullWidth ? 1 : 0,
+ flexBasis: fullWidth ? 0 : undefined,
+ minWidth: SEGMENT,
+ width: fullWidth ? 'auto' : SEGMENT, height: SEGMENT, borderRadius: 999, border: 'none', cursor: 'pointer',
+ background: on ? cat.color : 'transparent',
+ color: on ? '#fff' : undefined,
+ transition: 'background 0.14s, color 0.14s',
+ }}
+ onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--bg-hover)' }}
+ onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent' }}
+ >
+ {loading ? (
+ <span
+ className="animate-spin"
+ style={{
+ width: 14, height: 14, borderRadius: 999, display: 'inline-block',
+ border: '2px solid', borderColor: on ? 'rgba(255,255,255,0.45)' : 'var(--border-primary)',
+ borderTopColor: on ? '#fff' : 'var(--text-muted)',
+ }}
+ />
+ ) : (
+ <cat.Icon size={16} strokeWidth={2} />
+ )}
+ {on && !loading && failed && (
+ <span style={{
+ position: 'absolute', top: 2, right: 2, width: 8, height: 8,
+ borderRadius: 999, background: 'var(--danger)', border: '1.5px solid var(--sidebar-bg)',
+ }} />
+ )}
+ </button>
+ </Tooltip>
+ )
+}
+
// 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<Props>) {
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 (
+ <Segment
+ key={cat.key}
+ cat={cat}
+ on={on}
+ loading={loading}
+ failed={!!errorKeys?.has(cat.key)}
+ fullWidth={fullWidth}
+ onToggle={onToggle}
+ />
+ )
+ }
+
return (
- <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, width: fullWidth ? '100%' : undefined }}>
- <div style={{
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, width: fullWidth ? '100%' : undefined, maxWidth: '100%', minWidth: 0 }}>
+ <div onWheel={wheelSideways} style={{
display: fullWidth ? 'flex' : 'inline-flex',
alignSelf: fullWidth ? 'stretch' : undefined,
alignItems: 'center', gap: 2, padding: 4, borderRadius: 999, pointerEvents: 'auto', ...frosted,
+ maxWidth: '100%', overflowX: 'auto', scrollbarWidth: 'none',
}}>
- {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 (
- <Tooltip key={cat.key} label={t(cat.labelKey)} placement="bottom">
- <button
- type="button"
- onClick={() => onToggle(cat.key)}
- aria-pressed={on}
- aria-label={t(cat.labelKey)}
- className={on ? '' : 'text-content-muted'}
- style={{
- position: 'relative',
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
- flexGrow: fullWidth ? 1 : undefined,
- flexShrink: fullWidth ? 1 : undefined,
- flexBasis: fullWidth ? 0 : undefined,
- minWidth: fullWidth ? 0 : undefined,
- width: fullWidth ? 'auto' : 34, height: 34, borderRadius: 999, border: 'none', cursor: 'pointer',
- background: on ? cat.color : 'transparent',
- color: on ? '#fff' : undefined,
- transition: 'background 0.14s, color 0.14s',
- }}
- onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--bg-hover)' }}
- onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent' }}
- >
- {loading ? (
- <span
- className="animate-spin"
- style={{
- width: 14, height: 14, borderRadius: 999, display: 'inline-block',
- border: '2px solid', borderColor: on ? 'rgba(255,255,255,0.45)' : 'var(--border-primary)',
- borderTopColor: on ? '#fff' : 'var(--text-muted)',
- }}
- />
- ) : (
- <cat.Icon size={16} strokeWidth={2} />
- )}
- {on && !loading && errorKeys?.has(cat.key) && (
- <span style={{
- position: 'absolute', top: 2, right: 2, width: 8, height: 8,
- borderRadius: 999, background: '#ef4444', border: '1.5px solid var(--sidebar-bg)',
- }} />
- )}
- </button>
- </Tooltip>
- )
- })}
+ {categories.core.map(segment)}
+ {categories.plugin.length > 0 && (
+ <hr
+ aria-orientation="vertical"
+ aria-label={t('poi.pluginCategories')}
+ style={{ flexShrink: 0, width: 1, height: 20, margin: '0 3px', border: 'none', background: 'var(--border-primary)' }}
+ />
+ )}
+ {categories.plugin.map(segment)}
</div>
{(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('<svg')
})
+ it('FE-COMP-PLACEPOPUP-021: a place without a name keeps an empty name line, never the word undefined', () => {
+ const html = buildPlacePopupHtml(popupPlace({ name: undefined as never, address: null }), null)
+ // The name line is there and empty.
+ expect(html).toContain('white-space:nowrap;"></div>')
+ expect(html).not.toContain('undefined')
+ })
+
it('FE-COMP-PLACEPOPUP-002: escapes HTML metacharacters in the name', () => {
const html = buildPlacePopupHtml(popupPlace({ name: 'Bar & "Grill" <b>x</b>' }), null)
expect(html).toContain('Bar &amp; &quot;Grill&quot; &lt;b&gt;x&lt;/b&gt;')
@@ -130,3 +140,78 @@ describe('buildPoiPopupHtml', () => {
expect(buildPoiPopupHtml(poi({ address: 'Herrengasse 14 & 16' }))).toContain('Herrengasse 14 &amp; 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(
+ '<div style="font-family:var(--font-system);max-width:220px;">'
+ + `<div style="display:flex;align-items:center;gap:5px;"><span style="flex-shrink:0;display:inline-flex;line-height:0;">${icon(Coffee, '#B45309')}</span>`
+ + '<span style="font-weight:600;font-size:12.5px;color:#111827;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">Café Central</span></div>'
+ + '<div style="font-size:11px;color:#9ca3af;margin-top:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">Herrengasse 14</div></div>',
+ )
+ })
+
+ 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: '<img src=x onerror=alert(1)>',
+ address: '</div><script>alert(2)</script>',
+ color: '#2f855a', icon: 'Signpost',
+ details: [{ label: '<b onclick=alert(3)>Fee</b>', value: '"><svg onload=alert(4)>' }],
+ }))
+ 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('<img src=x onerror=alert(1)>')
+ expect(box.textContent).toContain('<b onclick=alert(3)>Fee</b>')
+ expect(box.textContent).toContain('"><svg onload=alert(4)>')
+ })
+
+ 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: '<img src=x onerror=alert(1)>',
+ }))
+ 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<HTMLElement>('div[style*="grid-template-columns"]')!
+ expect(grid.style.gridTemplateColumns).toBe('fit-content(45%) 1fr')
+ const [label, value] = [...grid.querySelectorAll<HTMLElement>(':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, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;')
+ 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 = '<div style="font-family:var(--font-system);max-width:220px;">'
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}<div style="${NAME_STYLE}">${esc(place.name)}</div>${category}${address}</div>`
}
-/** 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 = `<div style="display:flex;align-items:center;gap:5px;"><span style="flex-shrink:0;display:inline-flex;line-height:0;">${icon}</span><span style="${NAME_STYLE}">${esc(poi.name)}</span></div>`
const address = poi.address ? `<div style="${ADDR_STYLE}">${esc(poi.address)}</div>` : ''
- return `${CARD_OPEN}${head}${address}</div>`
+ return `${CARD_OPEN}${head}${address}${poiDetailsHtml(poi)}</div>`
+}
+
+function poiDetailsHtml(poi: Poi): string {
+ const rows = poiDetailRows(poi)
+ if (!rows.length) return ''
+ const cells = rows.map(row => `<span style="${DETAIL_LABEL_STYLE}">${esc(row.label)}</span><span style="${DETAIL_VALUE_STYLE}">${esc(row.value)}</span>`)
+ return `<div style="${DETAILS_STYLE}">${cells.join('')}</div>`
}
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<string, unknown>
+ 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)', '"><script>', '', null, 7]) {
+ expect(pluginPoiColor(value)).toBe(POI_DEFAULT_COLOR)
+ }
+ })
+})
diff --git a/client/src/components/Map/pluginPoiIcons.ts b/client/src/components/Map/pluginPoiIcons.ts
new file mode 100644
index 000000000..2aaa92fba
--- /dev/null
+++ b/client/src/components/Map/pluginPoiIcons.ts
@@ -0,0 +1,56 @@
+import {
+ Accessibility, Bath, Bike, Droplet, Droplets, Footprints, Heart, Info, Landmark, MapPin,
+ Mountain, MountainSnow, PlugZap, Signpost, Star, Tent, TentTree, Trees, Waves, Zap,
+ type LucideIcon,
+} from 'lucide-react'
+import { isPluginPoiColor, isPluginPoiIcon, type PluginPoiIcon } from '@trek/shared'
+
+/**
+ * How a plugin POI category (#1781) looks: its icon and its colour, resolved in one
+ * place for everything that draws one (the explore pill, the Leaflet and GL markers,
+ * the hover card and the admin panel).
+ *
+ * The icon table is keyed by the shared allow-list, so a name added to
+ * PLUGIN_POI_ICONS without a component here is a type error rather than a chip
+ * without a glyph. Imported one by one, unlike resolvePluginIcon's lookup over the
+ * whole lucide module: a plugin names one of twenty shapes, never an arbitrary export.
+ */
+const PLUGIN_POI_ICON_COMPONENTS: Record<PluginPoiIcon, LucideIcon> = {
+ Footprints,
+ Mountain,
+ MountainSnow,
+ Signpost,
+ Trees,
+ TentTree,
+ Tent,
+ Accessibility,
+ Droplet,
+ Droplets,
+ PlugZap,
+ Zap,
+ Bath,
+ Bike,
+ Waves,
+ Landmark,
+ MapPin,
+ Star,
+ Heart,
+ Info,
+}
+
+/** The grey an unknown POI category has always been drawn in. */
+export const POI_DEFAULT_COLOR = '#6b7280'
+
+/** The lucide component for an allow-listed icon name; MapPin for anything else. */
+export function resolvePluginPoiIcon(name: unknown): LucideIcon {
+ return isPluginPoiIcon(name) ? PLUGIN_POI_ICON_COMPONENTS[name] : MapPin
+}
+
+/**
+ * The colour to draw, checked again even though the server already did: it ends up
+ * inside marker markup and a CSS background, so only a strict `#rrggbb` gets through
+ * and anything else is the default grey.
+ */
+export function pluginPoiColor(value: unknown): string {
+ return isPluginPoiColor(value) ? value : POI_DEFAULT_COLOR
+}
diff --git a/client/src/components/Map/poiCategories.test.ts b/client/src/components/Map/poiCategories.test.ts
new file mode 100644
index 000000000..349e6593d
--- /dev/null
+++ b/client/src/components/Map/poiCategories.test.ts
@@ -0,0 +1,34 @@
+// FE-COMP-POIAPPEAR-001 to FE-COMP-POIAPPEAR-005
+import { describe, it, expect } from 'vitest'
+import { Coffee, Fuel, MapPin, Signpost } from 'lucide-react'
+import { poiAppearance, POI_CATEGORIES, ROADTRIP_POI_CATEGORIES } from './poiCategories'
+import { POI_DEFAULT_COLOR } from './pluginPoiIcons'
+
+const PLUGIN_KEY = 'plugin:trail-finder/trailheads'
+const coreColor = (key: string) => [...POI_CATEGORIES, ...ROADTRIP_POI_CATEGORIES].find(c => c.key === key)?.color
+
+describe('poiAppearance', () => {
+ it('FE-COMP-POIAPPEAR-001: a core category is drawn with its own colour and icon', () => {
+ expect(poiAppearance({ category: 'cafe' })).toEqual({ color: coreColor('cafe'), Icon: Coffee })
+ })
+
+ it('FE-COMP-POIAPPEAR-002: a road trip category keeps its look, even for a plugin hit with its own colour', () => {
+ // The corridor search asks plugins for core kinds; their hits answer `fuel`, not a plugin key.
+ expect(poiAppearance({ category: 'fuel', color: '#123456', icon: 'Star' })).toEqual({ color: coreColor('fuel'), Icon: Fuel })
+ })
+
+ it('FE-COMP-POIAPPEAR-003: a plugin category is drawn with the colour and icon its POI carries', () => {
+ expect(poiAppearance({ category: PLUGIN_KEY, color: '#2f855a', icon: 'Signpost' })).toEqual({ color: '#2f855a', Icon: Signpost })
+ })
+
+ it('FE-COMP-POIAPPEAR-004: a plugin POI with a colour or icon that fails the checks is grey with a pin', () => {
+ expect(poiAppearance({ category: PLUGIN_KEY, color: 'red;background:url(x)', icon: 'Skull' })).toEqual({ color: POI_DEFAULT_COLOR, Icon: MapPin })
+ expect(poiAppearance({ category: PLUGIN_KEY })).toEqual({ color: POI_DEFAULT_COLOR, Icon: MapPin })
+ })
+
+ it('FE-COMP-POIAPPEAR-005: an unknown category, prototype names included, is the plain grey disc', () => {
+ for (const category of ['unknown', 'constructor', 'toString', 'plugin:trail-finder', 'plugin:TF/x']) {
+ expect(poiAppearance({ category, color: '#2f855a', icon: 'Signpost' })).toEqual({ color: POI_DEFAULT_COLOR, Icon: null })
+ }
+ })
+})
diff --git a/client/src/components/Map/poiCategories.ts b/client/src/components/Map/poiCategories.ts
index 9ecf75df7..b6af10b4c 100644
--- a/client/src/components/Map/poiCategories.ts
+++ b/client/src/components/Map/poiCategories.ts
@@ -1,8 +1,10 @@
import { Utensils, Coffee, Wine, BedDouble, Camera, Landmark, Trees, Ticket, Fuel, Zap, ParkingSquare, Tent, type LucideIcon } from 'lucide-react'
+import { parsePluginPoiCategoryKey, type PluginPoiDetail } from '@trek/shared'
// The road-trip kinds take their colour from the one place that defines it, so the
// search result, the map pin and the road-trip rail cannot drift apart.
import { SERVICE_COLORS } from '../Roadtrip/roadtripModel'
import { CORRIDOR_CATEGORIES, HOTEL_COLOR } from '../Roadtrip/stopKinds'
+import { POI_DEFAULT_COLOR, pluginPoiColor, resolvePluginPoiIcon } from './pluginPoiIcons'
// The POI categories shown in the map "explore" pill. The `key` is the contract
// with the server (CATEGORY_OSM_FILTERS in mapsService.ts) — the OSM tag mapping
@@ -38,9 +40,9 @@ export const ROADTRIP_POI_CATEGORIES: PoiCategory[] = CORRIDOR_CATEGORIES.map(
({ key, labelKey, Icon, color }) => ({ key, labelKey, Icon, color }),
)
-export const POI_CATEGORY_BY_KEY: Record<string, PoiCategory> = Object.fromEntries(
- [...POI_CATEGORIES, ...ROADTRIP_POI_CATEGORIES].map(c => [c.key, c]),
-)
+// A Map rather than an object, so a category named after an Object.prototype member
+// (`constructor`, `toString`) finds nothing rather than a function.
+const CATEGORY_BY_KEY = new Map([...POI_CATEGORIES, ...ROADTRIP_POI_CATEGORIES].map(c => [c.key, c] as const))
// One POI result from /api/maps/pois (mirror of the server's OverpassPoi).
export interface Poi {
@@ -73,4 +75,37 @@ export interface Poi {
source: string
pluginId?: string
rating?: number | null
+ /**
+ * Only on a POI from a plugin category (GET /api/plugin-pois): what the plugin knows
+ * that open data does not, and the declaring category's icon and colour. Plugin text
+ * and a plugin value either way, so they are drawn through poiAppearance and
+ * textContent, never straight into markup.
+ */
+ details?: PluginPoiDetail[]
+ icon?: string
+ color?: string
+}
+
+/** What a POI pin and its hover card are drawn with. */
+export interface PoiAppearance {
+ color: string
+ /** Null for a category nobody knows, which is drawn as a plain grey disc. */
+ Icon: LucideIcon | null
+}
+
+/**
+ * How to draw `poi`. A core or road trip category has its own look; a plugin category
+ * has the one its POI carries, checked again here (a colour that is not `#rrggbb`
+ * turns grey, an icon off the allow-list turns into a pin); anything else is the grey
+ * disc an unknown category has always been. Keyed by the category rather than by
+ * `pluginId`, because a plugin's hit in the road trip corridor search answers a core
+ * category and is drawn like one.
+ */
+export function poiAppearance(poi: Pick<Poi, 'category' | 'icon' | 'color'>): PoiAppearance {
+ const core = CATEGORY_BY_KEY.get(poi.category)
+ if (core) return { color: core.color, Icon: core.Icon }
+ if (parsePluginPoiCategoryKey(poi.category)) {
+ return { color: pluginPoiColor(poi.color), Icon: resolvePluginPoiIcon(poi.icon) }
+ }
+ return { color: POI_DEFAULT_COLOR, Icon: null }
}
diff --git a/client/src/components/Map/poiMarker.test.ts b/client/src/components/Map/poiMarker.test.ts
new file mode 100644
index 000000000..3533499aa
--- /dev/null
+++ b/client/src/components/Map/poiMarker.test.ts
@@ -0,0 +1,68 @@
+// FE-COMP-POIMARKER-001 to FE-COMP-POIMARKER-008
+import { describe, it, expect } from 'vitest'
+import { createElement } from 'react'
+import { Coffee, MapPin, Signpost, type LucideIcon } from 'lucide-react'
+import { PLUGIN_POI_DETAILS_MAX } from '@trek/shared'
+import { renderIconMarkup } from '../../utils/iconMarkup'
+import { POI_CATEGORIES } from './poiCategories'
+import { POI_DEFAULT_COLOR } from './pluginPoiIcons'
+import { poiDetailRowKey, poiDetailRows, poiPinCacheKey, poiPinParts } from './poiMarker'
+
+const PLUGIN_KEY = 'plugin:trail-finder/trailheads'
+const coreColor = (key: string) => POI_CATEGORIES.find(c => c.key === key)?.color
+const glyph = (Icon: LucideIcon) => renderIconMarkup(createElement(Icon, { size: 13, color: 'white', strokeWidth: 2.5 }))
+
+describe('poiPinParts', () => {
+ it('FE-COMP-POIMARKER-001: a core category keeps the colour and glyph it has always had', () => {
+ expect(poiPinParts({ category: 'cafe' })).toEqual({ color: coreColor('cafe'), svg: glyph(Coffee) })
+ // An unknown category is the grey disc without a glyph, as before.
+ expect(poiPinParts({ category: 'spaceport' })).toEqual({ color: POI_DEFAULT_COLOR, svg: '' })
+ })
+
+ it('FE-COMP-POIMARKER-002: a plugin POI is drawn with its own colour and allow-listed icon', () => {
+ expect(poiPinParts({ category: PLUGIN_KEY, color: '#2f855a', icon: 'Signpost' })).toEqual({ color: '#2f855a', svg: glyph(Signpost) })
+ })
+
+ it('FE-COMP-POIMARKER-003: a colour or icon that fails the checks never reaches the markup', () => {
+ const parts = poiPinParts({ category: PLUGIN_KEY, color: 'red;background:url(https://evil.example/x)', icon: '<img src=x onerror=alert(1)>' })
+ expect(parts).toEqual({ color: POI_DEFAULT_COLOR, svg: glyph(MapPin) })
+ expect(parts.svg).not.toContain('evil')
+ expect(parts.svg).not.toContain('<img')
+ })
+})
+
+describe('poiPinCacheKey', () => {
+ it('FE-COMP-POIMARKER-004: a core category is cached under its key alone', () => {
+ expect(poiPinCacheKey({ category: 'museum', color: '#123456', icon: 'Star' })).toBe('museum')
+ expect(poiPinCacheKey({ category: 'spaceport' })).toBe('spaceport')
+ })
+
+ it('FE-COMP-POIMARKER-005: a plugin category adds its checked colour and icon to the key', () => {
+ const key = poiPinCacheKey({ category: PLUGIN_KEY, color: '#2f855a', icon: 'Signpost' })
+ expect(key).toBe(`${PLUGIN_KEY}|#2f855a|Signpost`)
+ // A plugin update that changes the look is a new pin, not the one cached before it.
+ expect(poiPinCacheKey({ category: PLUGIN_KEY, color: '#c53030', icon: 'Signpost' })).not.toBe(key)
+ expect(poiPinCacheKey({ category: PLUGIN_KEY, color: '#2f855a', icon: 'Mountain' })).not.toBe(key)
+ // Values that fail the checks are keyed by what is drawn instead: the grey and no icon name.
+ expect(poiPinCacheKey({ category: PLUGIN_KEY, color: 'url(x)', icon: 'Skull' })).toBe(`${PLUGIN_KEY}|${POI_DEFAULT_COLOR}|`)
+ })
+})
+
+describe('poiDetailRows', () => {
+ it('FE-COMP-POIMARKER-006: a POI without details has no rows', () => {
+ expect(poiDetailRows({})).toEqual([])
+ expect(poiDetailRows({ details: undefined })).toEqual([])
+ expect(poiDetailRows({ details: 'Length: 3 km' as never })).toEqual([])
+ })
+
+ it('FE-COMP-POIMARKER-007: rows are capped at the contract limit and a repeated one shows once', () => {
+ const rows = Array.from({ length: PLUGIN_POI_DETAILS_MAX + 3 }, (_, i) => ({ label: `L${i}`, value: `V${i}` }))
+ expect(poiDetailRows({ details: rows })).toEqual(rows.slice(0, PLUGIN_POI_DETAILS_MAX))
+ const repeated = [{ label: 'Length', value: '3 km' }, { label: 'Length', value: '3 km' }, { label: 'Length', value: '5 km' }]
+ expect(poiDetailRows({ details: repeated })).toEqual([repeated[0], repeated[2]])
+ })
+
+ it('FE-COMP-POIMARKER-008: the row key tells label and value apart', () => {
+ expect(poiDetailRowKey({ label: 'a', value: 'bc' })).not.toBe(poiDetailRowKey({ label: 'ab', value: 'c' }))
+ })
+})
diff --git a/client/src/components/Map/poiMarker.ts b/client/src/components/Map/poiMarker.ts
new file mode 100644
index 000000000..6395cfcc4
--- /dev/null
+++ b/client/src/components/Map/poiMarker.ts
@@ -0,0 +1,59 @@
+import { createElement } from 'react'
+import { PLUGIN_POI_DETAILS_MAX, isPluginPoiIcon, parsePluginPoiCategoryKey, type PluginPoiDetail } from '@trek/shared'
+import { renderIconMarkup } from '../../utils/iconMarkup'
+import { poiAppearance, type Poi } from './poiCategories'
+import { pluginPoiColor } from './pluginPoiIcons'
+
+/**
+ * What an explore POI pin is drawn with, for both map renderers (the Leaflet divIcon
+ * and the GL marker element), so the two cannot draw one POI two ways.
+ *
+ * Each renderer keeps its own disc markup around these parts, because the two have
+ * always differed by a style or two and a core pin has to come out exactly as it did.
+ */
+
+type PoiLook = Pick<Poi, 'category' | 'icon' | 'color'>
+
+/**
+ * The disc colour and the white glyph inside it. The colour has been through
+ * poiAppearance, so a plugin value that is not `#rrggbb` never reaches the markup it is
+ * written into; an unknown category has no glyph.
+ */
+export function poiPinParts(poi: PoiLook): { color: string; svg: string } {
+ const { color, Icon } = poiAppearance(poi)
+ const svg = Icon ? renderIconMarkup(createElement(Icon, { size: 13, color: 'white', strokeWidth: 2.5 })) : ''
+ return { color, svg }
+}
+
+/**
+ * What a cached pin is looked up by. A core category is drawn the same way every time,
+ * so its key alone is enough. A plugin category is drawn from what its POI carries, and
+ * the plugin can change that with an update, so its key adds the checked colour and
+ * icon: a pin cached before the update is never handed out after it.
+ */
+export function poiPinCacheKey(poi: PoiLook): string {
+ if (!parsePluginPoiCategoryKey(poi.category)) return poi.category
+ const icon = isPluginPoiIcon(poi.icon) ? poi.icon : ''
+ return `${poi.category}|${pluginPoiColor(poi.color)}|${icon}`
+}
+
+/** One detail row told apart from the others, for a React key. */
+export function poiDetailRowKey(row: PluginPoiDetail): string {
+ return `${row.label}\n${row.value}`
+}
+
+/**
+ * The plugin's detail rows to show on the hover card, at most as many as the contract
+ * allows and each one once. Plugin text, so every renderer writes it as text (React or
+ * escapeHtml), never as markup. Empty for a core POI, which has none.
+ */
+export function poiDetailRows(poi: Pick<Poi, 'details'>): PluginPoiDetail[] {
+ if (!Array.isArray(poi.details)) return []
+ const seen = new Set<string>()
+ return poi.details.slice(0, PLUGIN_POI_DETAILS_MAX).filter(row => {
+ const key = poiDetailRowKey(row)
+ if (seen.has(key)) return false
+ seen.add(key)
+ return true
+ })
+}
diff --git a/client/src/components/Map/useMergedMapPois.test.ts b/client/src/components/Map/useMergedMapPois.test.ts
index 63d880bb3..eead8a0e8 100644
--- a/client/src/components/Map/useMergedMapPois.test.ts
+++ b/client/src/components/Map/useMergedMapPois.test.ts
@@ -4,7 +4,7 @@ import { useMergedMapPois } from './useMergedMapPois'
import type { Poi } from './poiCategories'
/**
- * FE-MAP-MERGEPOI-001..006 — the two searches that can run at once in road trip mode.
+ * FE-MAP-MERGEPOI-001..010: the two searches that can run at once in road trip mode.
*
* The corridor answers "what is along the drive", the category pill answers "what is in
* view". Both are drawn, the corridor's copy of a shared hit wins, and the reference is
@@ -83,4 +83,15 @@ describe('useMergedMapPois — the refuel offers', () => {
expect(result.current).toBe(first)
expect(result.current).toBe(corridor)
})
+
+ it('FE-MAP-MERGEPOI-010: a plugin POI next to the corridor is its own pin and keeps its look and rows', () => {
+ // Namespaced by the host, so a plugin id never collides with an OSM element of the same number.
+ const trailhead = {
+ ...poi('plugin:trail-finder:1'), category: 'plugin:trail-finder/trailheads',
+ icon: 'Signpost', color: '#2f855a', details: [{ label: 'Length', value: '12 km' }],
+ }
+ const { result } = renderHook(() => useMergedMapPois([poi('node:1')], [trailhead]))
+ expect(result.current.map(p => p.osm_id)).toEqual(['node:1', 'plugin:trail-finder:1'])
+ expect(result.current[1]).toBe(trailhead)
+ })
})
diff --git a/client/src/components/Map/usePoiCategories.test.tsx b/client/src/components/Map/usePoiCategories.test.tsx
new file mode 100644
index 000000000..99394638b
--- /dev/null
+++ b/client/src/components/Map/usePoiCategories.test.tsx
@@ -0,0 +1,119 @@
+// FE-COMP-POICATS-001 to FE-COMP-POICATS-009
+import React from 'react'
+import { describe, it, expect, beforeEach } from 'vitest'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { MapPin, Signpost, Waves } from 'lucide-react'
+import type { PluginPoiCategory } from '@trek/shared'
+import { TranslationProvider } from '../../i18n'
+import { usePluginStore, type ActivePlugin } from '../../store/pluginStore'
+import { useSettingsStore } from '../../store/settingsStore'
+import { POI_CATEGORIES } from './poiCategories'
+import { POI_DEFAULT_COLOR } from './pluginPoiIcons'
+import {
+ corePoiCategories,
+ findPoiCategory,
+ pluginPoiCategories,
+ usePoiCategories,
+} from './usePoiCategories'
+
+const TRAILHEADS: PluginPoiCategory = {
+ id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a',
+}
+const SWIMMING: PluginPoiCategory = { id: 'swimming', label: 'Swimming spots', icon: 'Waves', color: '#0369a1' }
+
+function plugin(id: string, poiCategories?: PluginPoiCategory[]): ActivePlugin {
+ return { id, name: id, type: 'integration', icon: null, ...(poiCategories ? { poiCategories } : {}) }
+}
+
+const initialPlugins = usePluginStore.getState()
+const initialSettings = useSettingsStore.getState()
+
+// Reset before rather than after: an afterEach would change the language under a hook
+// that is still mounted, and the provider would load the other locale outside act.
+beforeEach(() => {
+ usePluginStore.setState(initialPlugins, true)
+ useSettingsStore.setState(initialSettings, true)
+})
+
+const wrapper = ({ children }: { children: React.ReactNode }) => <TranslationProvider>{children}</TranslationProvider>
+
+describe('corePoiCategories', () => {
+ it('FE-COMP-POICATS-001: the core list in its own order, labels translated', () => {
+ const core = corePoiCategories(key => `t:${key}`)
+ expect(core.map(c => c.key)).toEqual(POI_CATEGORIES.map(c => c.key))
+ expect(core[0]).toEqual({ key: 'restaurant', label: 't:poi.cat.restaurants', Icon: POI_CATEGORIES[0].Icon, color: POI_CATEGORIES[0].color })
+ expect(core.every(c => c.pluginId === undefined)).toBe(true)
+ })
+})
+
+describe('pluginPoiCategories', () => {
+ it('FE-COMP-POICATS-002: feed order, then declaration order, each under its namespaced key', () => {
+ const cats = pluginPoiCategories([plugin('trail-finder', [TRAILHEADS, SWIMMING]), plugin('flights'), plugin('eco-map', [SWIMMING])], 'en')
+ expect(cats.map(c => c.key)).toEqual([
+ 'plugin:trail-finder/trailheads',
+ 'plugin:trail-finder/swimming',
+ 'plugin:eco-map/swimming',
+ ])
+ expect(cats.map(c => c.pluginId)).toEqual(['trail-finder', 'trail-finder', 'eco-map'])
+ expect(cats[0]).toMatchObject({ label: 'Trailheads', Icon: Signpost, color: '#2f855a' })
+ expect(cats[1]).toMatchObject({ Icon: Waves, color: '#0369a1' })
+ })
+
+ it('FE-COMP-POICATS-003: the label follows the language and falls back to the default', () => {
+ const plugins = [plugin('trail-finder', [TRAILHEADS, SWIMMING])]
+ expect(pluginPoiCategories(plugins, 'de').map(c => c.label)).toEqual(['Wanderparkplätze', 'Swimming spots'])
+ expect(pluginPoiCategories(plugins, 'fr').map(c => c.label)).toEqual(['Trailheads', 'Swimming spots'])
+ })
+
+ it('FE-COMP-POICATS-004: a colour or icon that got past the store is checked again', () => {
+ const forged = { ...TRAILHEADS, color: 'red;background:url(https://x)', icon: 'Skull' } as unknown as PluginPoiCategory
+ const [cat] = pluginPoiCategories([plugin('trail-finder', [forged])], 'en')
+ expect(cat.color).toBe(POI_DEFAULT_COLOR)
+ expect(cat.Icon).toBe(MapPin)
+ })
+})
+
+describe('findPoiCategory', () => {
+ it('FE-COMP-POICATS-005: finds a core and a plugin chip by key, and nothing for an unknown one', () => {
+ const groups = { core: corePoiCategories(k => k), plugin: pluginPoiCategories([plugin('trail-finder', [TRAILHEADS])], 'en') }
+ expect(findPoiCategory(groups, 'cafe')?.key).toBe('cafe')
+ expect(findPoiCategory(groups, 'plugin:trail-finder/trailheads')?.label).toBe('Trailheads')
+ expect(findPoiCategory(groups, 'plugin:trail-finder/swimming')).toBeUndefined()
+ expect(findPoiCategory(groups, 'fuel')).toBeUndefined()
+ })
+})
+
+describe('usePoiCategories', () => {
+ it('FE-COMP-POICATS-006: without plugin categories only the core chips, translated', () => {
+ const { result } = renderHook(() => usePoiCategories(), { wrapper })
+ expect(result.current.core.map(c => c.key)).toEqual(POI_CATEGORIES.map(c => c.key))
+ expect(result.current.core[1].label).toBe('Cafés')
+ expect(result.current.plugin).toEqual([])
+ })
+
+ it('FE-COMP-POICATS-007: follows the plugin feed, so a plugin switched off takes its chips with it', () => {
+ usePluginStore.setState({ plugins: [plugin('trail-finder', [TRAILHEADS])] })
+ const { result } = renderHook(() => usePoiCategories(), { wrapper })
+ expect(result.current.plugin.map(c => c.key)).toEqual(['plugin:trail-finder/trailheads'])
+
+ act(() => { usePluginStore.setState({ plugins: [] }) })
+ expect(result.current.plugin).toEqual([])
+ expect(result.current.core).toHaveLength(POI_CATEGORIES.length)
+ })
+
+ it('FE-COMP-POICATS-008: core and plugin labels both follow the user language', async () => {
+ useSettingsStore.setState(s => ({ settings: { ...s.settings, language: 'de' } }))
+ usePluginStore.setState({ plugins: [plugin('trail-finder', [TRAILHEADS])] })
+ const { result } = renderHook(() => usePoiCategories(), { wrapper })
+ expect(result.current.plugin[0].label).toBe('Wanderparkplätze')
+ await waitFor(() => expect(result.current.core[5].label).toBe('Museen & Kultur'))
+ })
+
+ it('FE-COMP-POICATS-009: keeps the same lists across renders while nothing changed', () => {
+ usePluginStore.setState({ plugins: [plugin('trail-finder', [TRAILHEADS])] })
+ const { result, rerender } = renderHook(() => usePoiCategories(), { wrapper })
+ const first = result.current
+ rerender()
+ expect(result.current).toBe(first)
+ })
+})
diff --git a/client/src/components/Map/usePoiCategories.ts b/client/src/components/Map/usePoiCategories.ts
new file mode 100644
index 000000000..cdb70efbd
--- /dev/null
+++ b/client/src/components/Map/usePoiCategories.ts
@@ -0,0 +1,67 @@
+import { useMemo } from 'react'
+import type { LucideIcon } from 'lucide-react'
+import { pluginPoiCategoryKey, pluginPoiCategoryLabel } from '@trek/shared'
+import { useTranslation } from '../../i18n'
+import { usePluginStore, type ActivePlugin } from '../../store/pluginStore'
+import { POI_CATEGORIES } from './poiCategories'
+import { pluginPoiColor, resolvePluginPoiIcon } from './pluginPoiIcons'
+
+/**
+ * One chip of the explore pill, core or plugin, ready to draw: the label is already
+ * in the user's language and the colour and icon are already checked.
+ */
+export interface ExplorePoiCategory {
+ /** A core key (`restaurant`) or a plugin key (`plugin:<pluginId>/<categoryId>`). */
+ key: string
+ label: string
+ Icon: LucideIcon
+ color: string
+ /** The plugin that added the chip; absent on a core category. */
+ pluginId?: string
+}
+
+/** The pill's chips in drawing order: the core ones, then what plugins added. */
+export interface PoiCategoryGroups {
+ core: ExplorePoiCategory[]
+ plugin: ExplorePoiCategory[]
+}
+
+/** The core categories with their translated labels. */
+export function corePoiCategories(t: (key: string) => string): ExplorePoiCategory[] {
+ return POI_CATEGORIES.map(({ key, labelKey, Icon, color }) => ({ key, label: t(labelKey), Icon, color }))
+}
+
+/**
+ * Every category the active plugins declared, in feed order and then declaration
+ * order. The label is the plugin's own text for `language`, falling back to its
+ * default; the colour and icon go through the same checks as a plugin POI's pin, so a
+ * value that slipped past the store still cannot reach the pill's markup.
+ */
+export function pluginPoiCategories(plugins: readonly ActivePlugin[], language: string): ExplorePoiCategory[] {
+ return plugins.flatMap(plugin => (plugin.poiCategories ?? []).map(category => ({
+ key: pluginPoiCategoryKey(plugin.id, category.id),
+ label: pluginPoiCategoryLabel(category, language),
+ Icon: resolvePluginPoiIcon(category.icon),
+ color: pluginPoiColor(category.color),
+ pluginId: plugin.id,
+ })))
+}
+
+/** The chip behind `key`, core or plugin; undefined when neither group has it. */
+export function findPoiCategory(groups: PoiCategoryGroups, key: string): ExplorePoiCategory | undefined {
+ return groups.core.find(c => c.key === key) ?? groups.plugin.find(c => c.key === key)
+}
+
+/**
+ * The explore pill's categories: the fixed core list and whatever the active plugins
+ * add (#1781). One hook for the desktop planner and the phone map, so the two can
+ * never offer different chips; it follows the plugin feed, so a plugin switched off
+ * in the admin panel takes its chips with it.
+ */
+export function usePoiCategories(): PoiCategoryGroups {
+ const { t, language } = useTranslation()
+ const plugins = usePluginStore(s => s.plugins)
+ const core = useMemo(() => corePoiCategories(t), [t])
+ const plugin = useMemo(() => pluginPoiCategories(plugins, language), [plugins, language])
+ return useMemo(() => ({ core, plugin }), [core, plugin])
+}
diff --git a/client/src/components/Map/usePoiExplore.test.tsx b/client/src/components/Map/usePoiExplore.test.tsx
index 66d0346d5..35a27b22c 100644
--- a/client/src/components/Map/usePoiExplore.test.tsx
+++ b/client/src/components/Map/usePoiExplore.test.tsx
@@ -1,12 +1,22 @@
-// FE-COMP-POIEXPLORE-001 to FE-COMP-POIEXPLORE-018
+// FE-COMP-POIEXPLORE-001 to FE-COMP-POIEXPLORE-028
import React from 'react'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { act, renderHook, waitFor } from '@testing-library/react'
+import type { PluginPoiCategory } from '@trek/shared'
import { TranslationProvider } from '../../i18n'
import { mapsApi } from '../../api/client'
+import { pluginPoisApi } from '../../api/pluginPois'
+import { pluginPoiRepo } from '../../repo/pluginPoiRepo'
+import { usePluginStore, type ActivePlugin } from '../../store/pluginStore'
import { usePoiExplore, type Bbox } from './usePoiExplore'
import type { Poi } from './poiCategories'
+const net = vi.hoisted(() => ({ offline: false }))
+vi.mock('../../sync/networkMode', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../sync/networkMode')>()),
+ isEffectivelyOffline: () => net.offline,
+}))
+
type PoiResponse = Awaited<ReturnType<typeof mapsApi.pois>>
const BBOX: Bbox = { south: 48.1, west: 16.3, north: 48.3, east: 16.4 }
@@ -53,8 +63,12 @@ function setup() {
const spyOnPois = () => vi.spyOn(mapsApi, 'pois')
let pois: ReturnType<typeof spyOnPois>
+const initialPlugins = usePluginStore.getState()
+
beforeEach(() => {
pois = spyOnPois().mockResolvedValue(response([poi()]))
+ net.offline = false
+ usePluginStore.setState(initialPlugins, true)
})
afterEach(() => {
@@ -271,3 +285,179 @@ describe('usePoiExplore', () => {
await waitFor(() => expect(result.current.loadingKeys.size).toBe(0))
})
})
+
+// Plugin POI categories (#1781): a chip a plugin added is asked of that plugin, through
+// the repo, with the same single selection, cancelling and retry as a core one.
+describe('usePoiExplore with plugin categories', () => {
+ const TRAILHEADS: PluginPoiCategory = { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a' }
+ const KEY = 'plugin:trail-finder/trailheads'
+ const TRAIL_FINDER: ActivePlugin = { id: 'trail-finder', name: 'Trail finder', type: 'integration', icon: null, poiCategories: [TRAILHEADS] }
+
+ type PluginAnswer = Awaited<ReturnType<typeof pluginPoiRepo.search>>
+
+ function pluginPoi(over: Partial<Poi> = {}): Poi {
+ return {
+ osm_id: 'plugin:trail-finder:th-1', name: 'Hochalm trailhead', lat: 48.2, lng: 16.35,
+ category: KEY, poi_type: KEY, 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: [{ label: 'Parking', value: '40 spaces' }], icon: 'Signpost', color: '#2f855a',
+ ...over,
+ }
+ }
+
+ function answer(rows: Poi[]): PluginAnswer {
+ return { pois: rows, source: 'plugin:trail-finder', truncated: false, clamped: false }
+ }
+
+ let search: ReturnType<typeof vi.spyOn>
+
+ beforeEach(() => {
+ usePluginStore.setState({ plugins: [TRAIL_FINDER], loaded: true })
+ search = vi.spyOn(pluginPoiRepo, 'search').mockResolvedValue(answer([pluginPoi()]))
+ })
+
+ it('FE-COMP-POIEXPLORE-019: hands the pill the core chips and then the plugin ones', () => {
+ const { result } = setup()
+ expect(result.current.categories.core.map(c => c.key)).toContain('cafe')
+ expect(result.current.categories.plugin.map(c => c.key)).toEqual([KEY])
+ })
+
+ it('FE-COMP-POIEXPLORE-020: a plugin key asks the plugin POI repo, never the core search', async () => {
+ const { result } = setup()
+ act(() => { result.current.onViewportChange(BBOX) })
+ act(() => { result.current.toggle(KEY) })
+
+ await waitFor(() => expect(result.current.pois).toHaveLength(1))
+ // The TREK language rather than the locale: that is what the SDK promises a plugin.
+ expect(search).toHaveBeenCalledWith('trail-finder', 'trailheads', BBOX, 'en', expect.any(AbortSignal))
+ expect(pois).not.toHaveBeenCalled()
+ expect(result.current.pois[0]).toMatchObject({ osm_id: 'plugin:trail-finder:th-1', color: '#2f855a', icon: 'Signpost' })
+ expect(result.current.pois[0].details).toEqual([{ label: 'Parking', value: '40 spaces' }])
+ })
+
+ it('FE-COMP-POIEXPLORE-021: offline the chip fails at once and no request is made', async () => {
+ search.mockRestore()
+ net.offline = true
+ const api = vi.spyOn(pluginPoisApi, 'search')
+ const { result } = setup()
+ act(() => { result.current.onViewportChange(BBOX) })
+ act(() => { result.current.toggle(KEY) })
+
+ await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true))
+ expect(api).not.toHaveBeenCalled()
+ expect(result.current.loadingKeys.has(KEY)).toBe(false)
+ expect(result.current.pois).toEqual([])
+ })
+
+ it('FE-COMP-POIEXPLORE-022: switching to a core category cancels the plugin request without an error', async () => {
+ const pending = deferred<PluginAnswer>()
+ let signal: AbortSignal | undefined
+ search.mockImplementation((...args: unknown[]) => {
+ signal = args[4] as AbortSignal
+ return pending.promise
+ })
+ const { result } = setup()
+ act(() => { result.current.onViewportChange(BBOX) })
+ act(() => { result.current.toggle(KEY) })
+ act(() => { result.current.toggle('cafe') })
+ expect(signal?.aborted).toBe(true)
+
+ await act(async () => { pending.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' })) })
+ await waitFor(() => expect(result.current.pois).toHaveLength(1))
+ expect(result.current.pois[0].category).toBe('cafe')
+ expect(result.current.errorKeys.size).toBe(0)
+ expect(result.current.loadingKeys.size).toBe(0)
+ })
+
+ it('FE-COMP-POIEXPLORE-023: a failed plugin answer is retried like a core one', async () => {
+ search.mockRejectedValueOnce(new Error('The plugin did not answer'))
+ const { result } = setup()
+ act(() => { result.current.onViewportChange(BBOX) })
+ act(() => { result.current.toggle(KEY) })
+ await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true))
+
+ act(() => { result.current.searchArea() })
+ await waitFor(() => expect(result.current.pois).toHaveLength(1))
+ expect(result.current.errorKeys.size).toBe(0)
+ expect(search).toHaveBeenCalledTimes(2)
+ })
+
+ it('FE-COMP-POIEXPLORE-024: an answer landing after the plugin chip was switched off is dropped', async () => {
+ const pending = deferred<PluginAnswer>()
+ search.mockReturnValue(pending.promise)
+ const { result } = setup()
+ act(() => { result.current.onViewportChange(BBOX) })
+ act(() => { result.current.toggle(KEY) })
+ act(() => { result.current.toggle(KEY) })
+
+ await act(async () => { pending.resolve(answer([pluginPoi()])) })
+ expect(result.current.pois).toEqual([])
+ expect(result.current.active.size).toBe(0)
+ })
+
+ it('FE-COMP-POIEXPLORE-025: a plugin chip that leaves the feed takes its selection and markers with it', async () => {
+ const { result } = setup()
+ act(() => { result.current.onViewportChange(BBOX) })
+ act(() => { result.current.toggle(KEY) })
+ await waitFor(() => expect(result.current.pois).toHaveLength(1))
+
+ // The admin switched the plugin off, and the feed was read again.
+ act(() => { usePluginStore.setState({ plugins: [] }) })
+ expect(result.current.active.size).toBe(0)
+ expect(result.current.pois).toEqual([])
+ expect(result.current.categories.plugin).toEqual([])
+ })
+
+ it('FE-COMP-POIEXPLORE-026: a request in flight when the chip leaves the feed is cancelled', async () => {
+ const pending = deferred<PluginAnswer>()
+ let signal: AbortSignal | undefined
+ search.mockImplementation((...args: unknown[]) => {
+ signal = args[4] as AbortSignal
+ return pending.promise
+ })
+ const { result } = setup()
+ act(() => { result.current.onViewportChange(BBOX) })
+ act(() => { result.current.toggle(KEY) })
+
+ act(() => { usePluginStore.setState({ plugins: [{ ...TRAIL_FINDER, poiCategories: undefined }] }) })
+ expect(signal?.aborted).toBe(true)
+ await act(async () => { pending.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' })) })
+ await waitFor(() => expect(result.current.loadingKeys.size).toBe(0))
+ expect(result.current.errorKeys.size).toBe(0)
+ })
+
+ it('FE-COMP-POIEXPLORE-027: a core selection outlives any change to the plugin feed', async () => {
+ const { result } = setup()
+ act(() => { result.current.onViewportChange(BBOX) })
+ act(() => { result.current.toggle('cafe') })
+ await waitFor(() => expect(result.current.pois).toHaveLength(1))
+
+ act(() => { usePluginStore.setState({ plugins: [] }) })
+ expect(result.current.active).toEqual(new Set(['cafe']))
+ expect(result.current.pois).toHaveLength(1)
+ })
+
+ it('FE-COMP-POIEXPLORE-028: a 404 means the category is gone, so the plugin feed is read again', async () => {
+ const loadPlugins = vi.fn(async () => {})
+ usePluginStore.setState({ loadPlugins })
+ search.mockRejectedValue(Object.assign(new Error('Request failed with status code 404'), { response: { status: 404 } }))
+ const { result } = setup()
+ act(() => { result.current.onViewportChange(BBOX) })
+ act(() => { result.current.toggle(KEY) })
+
+ await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true))
+ expect(loadPlugins).toHaveBeenCalledTimes(1)
+ // The fresh feed no longer lists it, so the chip and its selection go.
+ act(() => { usePluginStore.setState({ plugins: [] }) })
+ expect(result.current.active.size).toBe(0)
+ expect(result.current.categories.plugin).toEqual([])
+
+ // Any other failure keeps the feed as it is.
+ act(() => { usePluginStore.setState({ plugins: [TRAIL_FINDER] }) })
+ search.mockRejectedValue(Object.assign(new Error('Request failed with status code 502'), { response: { status: 502 } }))
+ act(() => { result.current.toggle(KEY) })
+ await waitFor(() => expect(result.current.errorKeys.has(KEY)).toBe(true))
+ expect(loadPlugins).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/client/src/components/Map/usePoiExplore.ts b/client/src/components/Map/usePoiExplore.ts
index 335f3afaa..e6fbe018f 100644
--- a/client/src/components/Map/usePoiExplore.ts
+++ b/client/src/components/Map/usePoiExplore.ts
@@ -1,7 +1,11 @@
-import { useState, useRef, useCallback, useMemo } from 'react'
+import { useState, useRef, useCallback, useMemo, useEffect } from 'react'
+import { parsePluginPoiCategoryKey } from '@trek/shared'
import { mapsApi } from '../../api/client'
import { useTranslation } from '../../i18n'
+import { pluginPoiRepo } from '../../repo/pluginPoiRepo'
+import { usePluginStore } from '../../store/pluginStore'
import type { Poi } from './poiCategories'
+import { findPoiCategory, usePoiCategories } from './usePoiCategories'
export interface Bbox { south: number; west: number; north: number; east: number }
@@ -11,14 +15,24 @@ function isAbortError(err: unknown): boolean {
return e?.name === 'CanceledError' || e?.code === 'ERR_CANCELED' || e?.name === 'AbortError'
}
+function isNotFound(err: unknown): boolean {
+ return (err as { response?: { status?: number } } | null)?.response?.status === 404
+}
+
/**
* State for the map POI "explore" pill. Toggling a category fetches its OSM POIs
* for the current viewport; panning/zooming does NOT auto-refetch — it just marks
* the results stale (`moved`) so the pill can offer "search this area". This keeps
* Overpass load (and visual churn) down.
+ *
+ * A category a plugin added (#1781) is asked of that plugin instead, through the
+ * plugin POI repo, with the same single selection, cancelling and retry. It also
+ * carries the pill's chips, so the selection and the chips on offer come from the
+ * same list.
*/
export function usePoiExplore() {
- const { locale } = useTranslation()
+ const { locale, language } = useTranslation()
+ const categories = usePoiCategories()
const [active, setActive] = useState<Set<string>>(() => new Set())
const [byCat, setByCat] = useState<Record<string, Poi[]>>({})
const [loadingKeys, setLoadingKeys] = useState<Set<string>>(() => new Set())
@@ -49,6 +63,22 @@ export function usePoiExplore() {
return next
}), [])
+ // A plugin key goes to its plugin, a core key to the core search; both answer in the
+ // same row shape, so nothing after this line knows which one it was.
+ const search = useCallback(async (key: string, bbox: Bbox, signal: AbortSignal): Promise<Poi[]> => {
+ const plugin = parsePluginPoiCategoryKey(key)
+ if (!plugin) return (await mapsApi.pois(key, bbox, locale, signal)).pois
+ try {
+ return (await pluginPoiRepo.search(plugin.pluginId, plugin.categoryId, bbox, language, signal)).pois
+ } catch (err) {
+ // The server no longer answers for this category: the plugin was switched off,
+ // uninstalled or lost its grant since the feed was read. Reading the feed again
+ // takes the chip away, and the selection with it (the effect below).
+ if (isNotFound(err)) void usePluginStore.getState().loadPlugins()
+ throw err
+ }
+ }, [locale, language])
+
const fetchCat = useCallback(async (key: string, bbox: Bbox) => {
abortRef.current[key]?.abort()
const ctrl = new AbortController()
@@ -56,10 +86,10 @@ export function usePoiExplore() {
setLoading(key, true)
setError(key, false)
try {
- const res = await mapsApi.pois(key, bbox, locale, ctrl.signal)
+ const found = await search(key, bbox, ctrl.signal)
// Drop the result if the user toggled this category off while the (slow)
// Overpass request was in flight — otherwise stale results re-appear.
- setByCat(prev => (activeRef.current.has(key) ? { ...prev, [key]: res.pois } : prev))
+ setByCat(prev => (activeRef.current.has(key) ? { ...prev, [key]: found } : prev))
} catch (err) {
// A superseded request was aborted on purpose — leave its state untouched
// so the newer request owns the spinner and results.
@@ -81,33 +111,47 @@ export function usePoiExplore() {
setLoading(key, false)
}
}
- }, [setLoading, setError, locale])
+ }, [setLoading, setError, search])
const onViewportChange = useCallback((bbox: Bbox) => {
bboxRef.current = bbox
if (activeRef.current.size > 0) setMoved(true)
}, [])
+ // Drops the results and cancels every in-flight fetch, so nothing lands after the
+ // selection changed.
+ const reset = useCallback(() => {
+ setMoved(false)
+ setErrorKeys(new Set())
+ Object.values(abortRef.current).forEach(c => c.abort())
+ abortRef.current = {}
+ setByCat({})
+ }, [])
+
// Single-select: clicking a category switches to it (dropping the previous one
// and its markers immediately) and fetches it for the current viewport; clicking
// the already-active category turns it off.
const toggle = useCallback((key: string) => {
const isOnlyActive = activeRef.current.has(key) && activeRef.current.size === 1
- setMoved(false)
- setErrorKeys(new Set())
- // Switching to another category (or turning off) — cancel any in-flight
- // fetches so their results can't land after the selection changed.
- Object.values(abortRef.current).forEach(c => c.abort())
- abortRef.current = {}
+ reset()
if (isOnlyActive) {
setActive(new Set())
- setByCat({})
return
}
setActive(new Set([key]))
- setByCat({})
if (bboxRef.current) fetchCat(key, bboxRef.current)
- }, [fetchCat])
+ }, [fetchCat, reset])
+
+ // A plugin chip that stopped being offered (the plugin was switched off,
+ // uninstalled or lost its grant, and the feed was read again) takes its selection
+ // and its markers with it, rather than leaving pins on the map for a chip nobody
+ // can press any more to hide them.
+ useEffect(() => {
+ const orphaned = Array.from(active).some(key => parsePluginPoiCategoryKey(key) !== null && !findPoiCategory(categories, key))
+ if (!orphaned) return
+ reset()
+ setActive(new Set())
+ }, [active, categories, reset])
const searchArea = useCallback(() => {
const bbox = bboxRef.current
@@ -118,5 +162,5 @@ export function usePoiExplore() {
const pois = useMemo(() => Object.values(byCat).flat(), [byCat])
- return { active, pois, loadingKeys, errorKeys, moved, toggle, searchArea, onViewportChange }
+ return { categories, active, pois, loadingKeys, errorKeys, moved, toggle, searchArea, onViewportChange }
}
diff --git a/client/src/components/Planner/PlaceFormModal.test.tsx b/client/src/components/Planner/PlaceFormModal.test.tsx
index 1a0856b64..ad3997f44 100644
--- a/client/src/components/Planner/PlaceFormModal.test.tsx
+++ b/client/src/components/Planner/PlaceFormModal.test.tsx
@@ -1,4 +1,4 @@
-// FE-COMP-PLACEFORM-001 to FE-COMP-PLACEFORM-036, FE-PLANNER-PLACEFORM-016 to FE-PLANNER-PLACEFORM-067, plus FE-PLANNER-PLACEFORM-068 to -091
+// FE-COMP-PLACEFORM-001 to FE-COMP-PLACEFORM-036, FE-PLANNER-PLACEFORM-016 to FE-PLANNER-PLACEFORM-067, plus FE-PLANNER-PLACEFORM-068 to -092
import { render, screen, waitFor, fireEvent, within, act } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -153,6 +153,37 @@ describe('PlaceFormModal', () => {
expect(screen.getByDisplayValue('Paris')).toBeInTheDocument();
});
+ it('FE-PLANNER-PLACEFORM-092: a plugin POI prefill asks the details column about its plugin id and saves it as the osm id', async () => {
+ const asked: unknown[] = [];
+ server.use(
+ http.post('/api/maps/enrichment', async ({ request }) => {
+ asked.push(await request.json());
+ return HttpResponse.json({ photos: [], description: null, facts: [], rating: null, hours: null });
+ }),
+ );
+ const user = userEvent.setup();
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ render(
+ <PlaceFormModal
+ {...defaultProps}
+ onSave={onSave}
+ prefillCoords={{
+ lat: 47.1, lng: 11.2, name: 'Trailhead', address: 'Hut 1',
+ website: 'https://trails.example/th-092', osm_id: 'plugin:trail-finder:th-092',
+ }}
+ />,
+ );
+ expect(screen.getByDisplayValue('Trailhead')).toBeInTheDocument();
+ expect(screen.getByDisplayValue('https://trails.example/th-092')).toBeInTheDocument();
+ // The server picks the provider by this id and never takes a `plugin:` one for Google's.
+ await waitFor(() => expect(asked).toEqual([expect.objectContaining({ placeId: 'plugin:trail-finder:th-092' })]));
+
+ await user.click(screen.getByRole('button', { name: /^Add$/i }));
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
+ expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ name: 'Trailhead', osm_id: 'plugin:trail-finder:th-092' }));
+ expect(onSave).not.toHaveBeenCalledWith(expect.objectContaining({ google_place_id: expect.anything() }));
+ });
+
it('FE-PLANNER-PLACEFORM-017: form resets when isOpen changes from place to null', () => {
const place = buildPlace({ name: 'Old Place' });
const { rerender } = render(<PlaceFormModal {...defaultProps} place={place} isOpen={true} />);
diff --git a/client/src/mobile/screens/admin/MAdminPluginsPanel.tsx b/client/src/mobile/screens/admin/MAdminPluginsPanel.tsx
index b0db824ba..a14bd885d 100644
--- a/client/src/mobile/screens/admin/MAdminPluginsPanel.tsx
+++ b/client/src/mobile/screens/admin/MAdminPluginsPanel.tsx
@@ -3,14 +3,15 @@ import { PLUGIN_PERMISSIONS } from '@trek/shared'
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,
+ SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, Database,
+ Globe, Info, History, PauseCircle, Puzzle, Bot,
} from 'lucide-react'
import PluginIcon from '../../../components/shared/PluginIcon'
import { adminApi } from '../../../api/client'
import { useInstanceSettings } from '../../../components/Admin/useInstanceSettings'
import { bypassChip, bypassOffer, useRangeBypass, type RangeWarning, type TrekRangeBypass } from '../../../components/Admin/useRangeBypass'
+import { deriveCaps } from '../../../components/Admin/pluginCaps'
+import PluginPoiCategoryList from '../../../components/Admin/PluginPoiCategoryList'
import { usePluginStore } from '../../../store/pluginStore'
import { useTranslation } from '../../../i18n'
import { useToast } from '../../../components/shared/Toast'
@@ -138,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
}
@@ -229,53 +232,6 @@ function parseJson<T>(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
@@ -1805,6 +1761,11 @@ function PluginDetailSheet({ item, installed, busy, onInstall, onClose, t, local
</div>
)}
+ {manifest && (
+ <PluginPoiCategoryList pluginId={item.id} permissions={manifest.permissions} categories={manifest.capabilities?.poiCategories}
+ className="mt-5" titleClassName={sectionH} itemClassName="text-[13px] text-m-muted" />
+ )}
+
{manifest && (manifest.egress.length > 0 || manifest.operatorEgress) && (
<div className="mt-5">
<h4 className={sectionH}>{t('admin.plugins.connectsTitle')}</h4>
diff --git a/client/src/mobile/screens/trip/map/MMapArea.tsx b/client/src/mobile/screens/trip/map/MMapArea.tsx
index 2f892ebc1..4695c3981 100644
--- a/client/src/mobile/screens/trip/map/MMapArea.tsx
+++ b/client/src/mobile/screens/trip/map/MMapArea.tsx
@@ -423,6 +423,7 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
<div className="pointer-events-none absolute left-4 right-4 z-[25] flex flex-col items-center gap-2 top-[calc(var(--m-safe-top,12px)+96px)]">
<PoiCategoryPill
fullWidth
+ categories={poi.categories}
active={poi.active}
onToggle={poi.toggle}
loadingKeys={poi.loadingKeys}
diff --git a/client/src/pages/TripPlannerPage.tsx b/client/src/pages/TripPlannerPage.tsx
index 460c0b466..197f3bb63 100644
--- a/client/src/pages/TripPlannerPage.tsx
+++ b/client/src/pages/TripPlannerPage.tsx
@@ -553,10 +553,13 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
// 860px the viewport centre sits under the Places panel, where this
// cluster covered both collapse tabs and Add Place/Activity (#2247).
left: `calc(${mapInsetLeft}px + (100% - ${mapInsetLeft}px - ${mapInsetRight}px) / 2)`,
+ // No wider than that corridor either: once plugins add categories the pill
+ // scrolls inside it instead of running on under a panel.
+ maxWidth: `calc(100% - ${mapInsetLeft}px - ${mapInsetRight}px - 24px)`,
transform: 'translateX(-50%)', zIndex: 25, pointerEvents: 'none', alignItems: 'flex-start', gap: 8,
}}>
{poiPillEnabled && (
- <PoiCategoryPill active={poi.active} onToggle={poi.toggle} loadingKeys={poi.loadingKeys} errorKeys={poi.errorKeys} moved={poi.moved} onSearchArea={poi.searchArea} />
+ <PoiCategoryPill categories={poi.categories} active={poi.active} onToggle={poi.toggle} loadingKeys={poi.loadingKeys} errorKeys={poi.errorKeys} moved={poi.moved} onSearchArea={poi.searchArea} />
)}
{glMap && <MapCompassPill map={glMap} />}
</div>
@@ -574,7 +577,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
buttons so map touch handlers cannot swallow the tap targets. */}
{poiPillEnabled && !mobileSidebarOpen && !showPlaceForm && !showMembersModal && !showReservationModal && createPortal(
<div data-testid="mobile-poi-category-pill" className="flex md:hidden" style={{ position: 'fixed', left: 12, right: 12, bottom: 'calc(var(--bottom-nav-h, 0px) + 12px)', justifyContent: 'center', zIndex: 100, pointerEvents: 'none' }}>
- <PoiCategoryPill active={poi.active} onToggle={poi.toggle} loadingKeys={poi.loadingKeys} errorKeys={poi.errorKeys} moved={poi.moved} onSearchArea={poi.searchArea} />
+ <PoiCategoryPill categories={poi.categories} active={poi.active} onToggle={poi.toggle} loadingKeys={poi.loadingKeys} errorKeys={poi.errorKeys} moved={poi.moved} onSearchArea={poi.searchArea} />
</div>,
document.body
)}
diff --git a/client/src/pages/TripPlannerPage.wiring.test.tsx b/client/src/pages/TripPlannerPage.wiring.test.tsx
index e46add188..c193ab28e 100644
--- a/client/src/pages/TripPlannerPage.wiring.test.tsx
+++ b/client/src/pages/TripPlannerPage.wiring.test.tsx
@@ -1,4 +1,4 @@
-// FE-PAGE-TPW-001 to FE-PAGE-TPW-062
+// FE-PAGE-TPW-001 to FE-PAGE-TPW-064
//
// The planner page is a wiring container: everything stateful lives in
// useTripPlanner (covered in src/pages/tripPlanner/useTripPlanner.test.tsx).
@@ -44,9 +44,19 @@ function props(name: string): Record<string, AnyProp> {
vi.mock('../components/Map/MapViewAuto', () => ({ MapViewAuto: stub('map', 'map-view') }))
vi.mock('../components/Map/MapCompassPill', () => ({ MapCompassPill: stub('compass', 'compass-pill') }))
-vi.mock('../components/Map/PoiCategoryPill', () => ({ default: stub('poiPill', 'poi-pill') }))
+// Every pill mount records its props here, so a test can check each one of them.
+const poiPillMounts = vi.hoisted(() => [] as Record<string, unknown>[])
+const poiCategories = vi.hoisted(() => ({ core: [], plugin: [] }))
+vi.mock('../components/Map/PoiCategoryPill', () => ({
+ default: (props: Record<string, unknown>) => {
+ captured.poiPill = props
+ poiPillMounts.push(props)
+ return React.createElement('div', { 'data-testid': 'poi-pill' })
+ },
+}))
vi.mock('../components/Map/usePoiExplore', () => ({
usePoiExplore: () => ({
+ categories: poiCategories,
active: [], pois: [], loadingKeys: [], errorKeys: [], moved: false,
toggle: vi.fn(), searchArea: vi.fn(), onViewportChange: vi.fn(),
}),
@@ -496,6 +506,24 @@ describe('TripPlannerPage — plan tab', () => {
expect(cluster.style.left).toBe('calc(350px + 0.5 * (100% - 350px - 310px))')
})
+ // Plugins can add POI categories (#1781), so the pill may outgrow the corridor; bounded
+ // to it, the pill scrolls there instead of running on under a panel.
+ it('FE-PAGE-TPW-063: the floating map controls are no wider than the corridor', () => {
+ const { container } = renderPage({ leftWidth: 340, rightWidth: 300 })
+ const cluster = container.querySelector('div[style*="translateX(-50%)"][style*="z-index: 25"]') as HTMLElement
+ // The two panel insets (350 and 310) and a 12px margin on either side.
+ expect(cluster.style.maxWidth).toBe('calc(100% - 684px)')
+ })
+
+ it('FE-PAGE-TPW-064: both pill mounts offer the categories the explore hook merged', () => {
+ poiPillMounts.length = 0
+ renderPage()
+ // The floating desktop pill and the portal the narrow layout uses.
+ expect(poiPillMounts.length).toBeGreaterThanOrEqual(2)
+ expect(poiPillMounts.every(mount => mount.categories === poiCategories)).toBe(true)
+ expect(screen.getByTestId('mobile-poi-category-pill')).toContainElement(screen.getAllByTestId('poi-pill')[1])
+ })
+
it('FE-PAGE-TPW-013d: a hidden panel takes no corridor away from the map controls', () => {
const { container } = renderPage({ leftWidth: 340, rightWidth: 300, rightHidden: true })
const cluster = container.querySelector('div[style*="translateX(-50%)"][style*="z-index: 25"]') as HTMLElement
diff --git a/client/src/pages/tripPlanner/useTripPlanner.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.test.tsx
index 7dab4a5fb..6f0088be4 100644
--- a/client/src/pages/tripPlanner/useTripPlanner.test.tsx
+++ b/client/src/pages/tripPlanner/useTripPlanner.test.tsx
@@ -1,4 +1,4 @@
-// FE-TP-HOOK-001 to FE-TP-HOOK-135
+// FE-TP-HOOK-001 to FE-TP-HOOK-142
import React from 'react'
import { renderHook, act, waitFor } from '@testing-library/react'
import { TranslationProvider } from '../../i18n/TranslationContext'
@@ -1062,6 +1062,44 @@ describe('useTripPlanner — add place entry points', () => {
expect(mapsApi.reverse).not.toHaveBeenCalled()
})
+ it('FE-TP-HOOK-141: a plugin POI prefills with its own id, and a website only when it is a web address', async () => {
+ seedTrip()
+ const { result } = await renderPlanner()
+ const trailhead = {
+ lat: 47.1, lng: 11.2, name: 'Trailhead', address: 'Hut 1', website: 'https://trails.example/th-1', phone: '+43 1',
+ osm_id: 'plugin:trail-finder:th-1', category: 'plugin:trail-finder/trailheads', source: 'plugin:trail-finder',
+ details: [{ label: 'Length', value: '12 km' }], icon: 'Signpost', color: '#2f855a',
+ }
+
+ act(() => { result.current.openAddPlaceFromPoi(trailhead) })
+
+ // Only the fields the form has: the details, icon and colour stay on the map.
+ expect(result.current.prefillCoords).toEqual({
+ lat: 47.1, lng: 11.2, name: 'Trailhead', address: 'Hut 1', website: 'https://trails.example/th-1', phone: '+43 1',
+ osm_id: 'plugin:trail-finder:th-1', stop_type: null, duration_minutes: undefined,
+ })
+ expect(mapsApi.reverse).not.toHaveBeenCalled()
+
+ act(() => { result.current.openAddPlaceFromPoi({ ...trailhead, website: 'javascript:alert(1)' }) })
+ expect(result.current.prefillCoords?.website).toBeUndefined()
+ act(() => { result.current.openAddPlaceFromPoi({ ...trailhead, website: 'trails.example' }) })
+ expect(result.current.prefillCoords?.website).toBe('https://trails.example')
+ })
+
+ it('FE-TP-HOOK-142: a plugin POI tapped on the map opens the same prefilled form', async () => {
+ seedTrip()
+ const { result } = await renderPlanner()
+
+ act(() => {
+ result.current.handlePoiClick({
+ lat: 47.1, lng: 11.2, name: 'Trailhead', address: null, website: null, phone: null, osm_id: 'plugin:trail-finder:th-1',
+ })
+ })
+
+ expect(result.current.showPlaceForm).toBe(true)
+ expect(result.current.prefillCoords).toMatchObject({ name: 'Trailhead', osm_id: 'plugin:trail-finder:th-1', website: undefined })
+ })
+
it('FE-TP-HOOK-050: the pool editor resolves a place\'s lone assignment for its times', async () => {
const place = buildPlace({ id: 1, lat: 1, lng: 2 })
seedTrip({
diff --git a/client/src/pages/tripPlanner/useTripPlanner.ts b/client/src/pages/tripPlanner/useTripPlanner.ts
index 5128a747a..02613edf2 100644
--- a/client/src/pages/tripPlanner/useTripPlanner.ts
+++ b/client/src/pages/tripPlanner/useTripPlanner.ts
@@ -57,7 +57,7 @@ import type { ManualStopTarget, ServiceStopMode } from '../../components/Roadtri
import type { RoadtripStopDraft } from '../../components/Roadtrip/RoadtripStopPopup'
import type { StayDraft } from '../../components/Roadtrip/RoadtripStayModal'
import { inspectorStay } from '../../components/Roadtrip/stayReading'
-import { MAX_TRIP_DAYS, type RoadtripStopType } from '@trek/shared'
+import { MAX_TRIP_DAYS, normalizePlaceWebsite, type RoadtripStopType } from '@trek/shared'
import { usePlaceSelection } from '../../hooks/usePlaceSelection'
import { usePlannerHistory } from '../../hooks/usePlannerHistory'
import { useAirtrailConnection } from '../../hooks/useAirtrailConnection'
@@ -884,8 +884,12 @@ export function useTripPlanner() {
lng: poi.lng,
name: poi.name,
address: poi.address || '',
- website: poi.website || undefined,
+ // Checked again on the way into the form: a plugin POI's website is the plugin's
+ // text, and only an address a browser opens as a page belongs in the field.
+ website: normalizePlaceWebsite(poi.website) ?? undefined,
phone: poi.phone || undefined,
+ // A plugin POI's `plugin:<pluginId>:<id>` rides along as it is. The server never
+ // takes that prefix for a Google place id, so the details column makes no Google call.
osm_id: poi.osm_id,
stop_type: stop?.stopType ?? null,
duration_minutes: stop?.dwellMinutes,
diff --git a/client/src/repo/pluginPoiRepo.test.ts b/client/src/repo/pluginPoiRepo.test.ts
new file mode 100644
index 000000000..a44937bed
--- /dev/null
+++ b/client/src/repo/pluginPoiRepo.test.ts
@@ -0,0 +1,68 @@
+// FE-REPO-PLUGINPOI-001 to FE-REPO-PLUGINPOI-005
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { PluginPoi } from '@trek/shared'
+import { pluginPoiRepo } from './pluginPoiRepo'
+import { isEffectivelyOffline } from '../sync/networkMode'
+import { pluginPoisApi } from '../api/pluginPois'
+
+vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) }))
+vi.mock('../api/pluginPois', () => ({ pluginPoisApi: { search: vi.fn() } }))
+
+const BBOX = { south: 47.1, west: 11.2, north: 47.3, east: 11.5 }
+
+const row: PluginPoi = {
+ 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: 'Almweg 1', website: null, phone: null,
+ opening_hours: null, cuisine: null, brand: null, brand_wikidata: null, charging: null,
+ source: 'plugin:trail-finder', pluginId: 'trail-finder', rating: 4.5,
+ details: [{ label: 'Parking', value: '40 spaces' }], icon: 'Signpost', color: '#2f855a',
+}
+const reply = { pois: [row], source: 'plugin:trail-finder', truncated: false, clamped: true }
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(isEffectivelyOffline).mockReturnValue(false)
+ vi.mocked(pluginPoisApi.search).mockResolvedValue(reply)
+})
+
+describe('pluginPoiRepo.search', () => {
+ it('FE-REPO-PLUGINPOI-001: asks the api for the one plugin and category, with the signal', async () => {
+ const signal = new AbortController().signal
+ const found = await pluginPoiRepo.search('trail-finder', 'trailheads', BBOX, 'de', signal)
+ expect(pluginPoisApi.search).toHaveBeenCalledWith('trail-finder', 'trailheads', BBOX, 'de', signal)
+ expect(found).toEqual(reply)
+ })
+
+ it('FE-REPO-PLUGINPOI-002: offline it refuses without making the request', async () => {
+ vi.mocked(isEffectivelyOffline).mockReturnValue(true)
+ await expect(pluginPoiRepo.search('trail-finder', 'trailheads', BBOX, 'en', new AbortController().signal))
+ .rejects.toThrow('requires a connection')
+ expect(pluginPoisApi.search).not.toHaveBeenCalled()
+ })
+
+ it('FE-REPO-PLUGINPOI-003: an answer off the contract is rejected, not drawn', async () => {
+ // A colour that is not #rrggbb would end up inside marker markup.
+ vi.mocked(pluginPoisApi.search).mockResolvedValue({ ...reply, pois: [{ ...row, color: 'red;background:url(x)' }] })
+ await expect(pluginPoiRepo.search('trail-finder', 'trailheads', BBOX, 'en', new AbortController().signal)).rejects.toThrow()
+ vi.mocked(pluginPoisApi.search).mockResolvedValue({ ...reply, pois: [{ ...row, icon: 'Skull' }] } as never)
+ await expect(pluginPoiRepo.search('trail-finder', 'trailheads', BBOX, 'en', new AbortController().signal)).rejects.toThrow()
+ })
+
+ it('FE-REPO-PLUGINPOI-004: an api failure reaches the caller unchanged', async () => {
+ const failure = Object.assign(new Error('Request failed with status code 404'), { response: { status: 404 } })
+ vi.mocked(pluginPoisApi.search).mockRejectedValue(failure)
+ await expect(pluginPoiRepo.search('trail-finder', 'trailheads', BBOX, 'en', new AbortController().signal)).rejects.toBe(failure)
+ })
+
+ it('FE-REPO-PLUGINPOI-005: hands back the rows as the map draws them, contact fields kept or null', async () => {
+ const contact = { ...row, osm_id: 'plugin:trail-finder:th-2', address: null, website: 'https://example.test/th-2', phone: '+43 1 234' }
+ vi.mocked(pluginPoisApi.search).mockResolvedValue({ ...reply, pois: [row, contact] })
+ const { pois } = await pluginPoiRepo.search('trail-finder', 'trailheads', BBOX, 'en', new AbortController().signal)
+ expect(pois.map(p => [p.address, p.website, p.phone])).toEqual([
+ ['Almweg 1', null, null],
+ [null, 'https://example.test/th-2', '+43 1 234'],
+ ])
+ expect(pois[1]).toMatchObject({ details: row.details, icon: 'Signpost', color: '#2f855a', pluginId: 'trail-finder' })
+ })
+})
diff --git a/client/src/repo/pluginPoiRepo.ts b/client/src/repo/pluginPoiRepo.ts
new file mode 100644
index 000000000..006ddc353
--- /dev/null
+++ b/client/src/repo/pluginPoiRepo.ts
@@ -0,0 +1,27 @@
+import { pluginPoiResponseSchema, type PluginPoi } from '@trek/shared'
+import { pluginPoisApi, type PluginPoiArea } from '../api/pluginPois'
+import type { Poi } from '../components/Map/poiCategories'
+import { isEffectivelyOffline } from '../sync/networkMode'
+
+// The contract row as the map's Poi. The nullable fields are spelled out because the
+// client compiles without strict mode, where zod types them as optional.
+function toPoi(row: PluginPoi): Poi {
+ return { ...row, address: row.address ?? null, website: row.website ?? null, phone: row.phone ?? null }
+}
+
+/**
+ * The places of a plugin POI category (#1781) for the explore pill.
+ *
+ * Online only, like the core categories: the answer comes from the plugin, live, and
+ * is never kept. Offline the request is not made at all and the chip shows its error
+ * dot instead. The answer is checked strictly on top of the api module's development
+ * warning, because a plugin POI's colour and icon go on to be drawn into marker
+ * markup, and only a row the shared contract accepts may get that far.
+ */
+export const pluginPoiRepo = {
+ async search(pluginId: string, categoryId: string, bbox: PluginPoiArea, lang: string, signal: AbortSignal) {
+ if (isEffectivelyOffline()) throw new Error('Plugin POI search requires a connection')
+ const reply = pluginPoiResponseSchema.parse(await pluginPoisApi.search(pluginId, categoryId, bbox, lang, signal))
+ return { ...reply, pois: reply.pois.map(toPoi) }
+ },
+}
diff --git a/client/src/store/pluginStore.test.ts b/client/src/store/pluginStore.test.ts
index 4532978ab..b1239dfd6 100644
--- a/client/src/store/pluginStore.test.ts
+++ b/client/src/store/pluginStore.test.ts
@@ -1,7 +1,7 @@
-// FE-STORE-PLUGIN-001 to 006
+// FE-STORE-PLUGIN-001 to 009
import { http, HttpResponse } from 'msw';
import { server } from '../../tests/helpers/msw/server';
-import { usePluginStore, clearAllPluginSessions } from './pluginStore';
+import { usePluginStore, clearAllPluginSessions, readPoiCategories } from './pluginStore';
const initial = usePluginStore.getState();
@@ -99,4 +99,64 @@ describe('pluginStore', () => {
expect(usePluginStore.getState().loaded).toBe(true);
key.mockRestore();
});
+
+ // Plugin POI categories (#1781) end up in the explore pill and their colour in
+ // marker markup, so the store re-reads them against the shared schema.
+ const trailheads = { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a' };
+
+ it('FE-STORE-PLUGIN-007: carries the POI categories the feed sends and leaves the key off without them', async () => {
+ server.use(
+ http.get('/api/plugins', () =>
+ HttpResponse.json({
+ plugins: [
+ { id: 'trail-finder', name: 'Trail finder', type: 'integration', icon: null, poiCategories: [trailheads] },
+ { id: 'flights', name: 'Flights', type: 'widget', icon: 'Plane' },
+ ],
+ }),
+ ),
+ );
+
+ await usePluginStore.getState().loadPlugins();
+
+ const [trail, flights] = usePluginStore.getState().plugins;
+ expect(trail.poiCategories).toEqual([trailheads]);
+ expect(flights).not.toHaveProperty('poiCategories');
+ });
+
+ it('FE-STORE-PLUGIN-008: drops a malformed category instead of rendering it, and the key when none survive', async () => {
+ server.use(
+ http.get('/api/plugins', () =>
+ HttpResponse.json({
+ plugins: [
+ {
+ id: 'trail-finder', name: 'Trail finder', type: 'integration', icon: null,
+ poiCategories: [
+ { ...trailheads, id: 'bad-colour', color: 'red;background:url(https://x)' },
+ { ...trailheads, id: 'bad-icon', icon: 'Skull' },
+ trailheads,
+ { ...trailheads, label: 'Duplicate id' },
+ null,
+ ],
+ },
+ { id: 'broken', name: 'Broken', type: 'integration', icon: null, poiCategories: [{ id: 'x' }] },
+ ],
+ }),
+ ),
+ );
+
+ await usePluginStore.getState().loadPlugins();
+
+ const [trail, broken] = usePluginStore.getState().plugins;
+ expect(trail.poiCategories).toEqual([trailheads]);
+ expect(broken).not.toHaveProperty('poiCategories');
+ });
+
+ it('FE-STORE-PLUGIN-009: readPoiCategories keeps the cap and refuses what cannot become a pill key', () => {
+ const many = ['a1', 'a2', 'a3', 'a4', 'a5'].map((id) => ({ ...trailheads, id }));
+ expect(readPoiCategories('trail-finder', many).map((c) => c.id)).toEqual(['a1', 'a2', 'a3', 'a4']);
+ expect(readPoiCategories('trail-finder', 'not a list')).toEqual([]);
+ // Nothing parses back out of `plugin:TF/trailheads`, so its chip could never be searched.
+ expect(readPoiCategories('TF', [trailheads])).toEqual([]);
+ expect(readPoiCategories(undefined as unknown as string, [trailheads])).toEqual([]);
+ });
});
diff --git a/client/src/store/pluginStore.ts b/client/src/store/pluginStore.ts
index 859fda666..80d918e2a 100644
--- a/client/src/store/pluginStore.ts
+++ b/client/src/store/pluginStore.ts
@@ -1,4 +1,10 @@
import { create } from 'zustand'
+import {
+ PLUGIN_POI_MAX_CATEGORIES,
+ PLUGIN_POI_PLUGIN_ID_RE,
+ pluginPoiCategorySchema,
+ type PluginPoiCategory,
+} from '@trek/shared'
import { pluginsApi } from '../api/client'
const PLUGIN_SESSION_NAMESPACE = 'trek:plugin-session:'
@@ -58,11 +64,40 @@ export interface ActivePlugin {
/** Routing profiles the planner's route toggle offers (routeProvider hook;
* the server only sends these when the hook permission is granted). */
routeProfiles?: Array<{ id: string; label: string; icon?: string }>
+ /** Categories the map's explore pill offers (poiCategoryProvider hook, #1781; the
+ * server only sends these when the hook permission is granted). Re-validated on
+ * arrival by readPoiCategories, so everything here is safe to draw. */
+ poiCategories?: PluginPoiCategory[]
/** The plugin holds the geolocation:read grant — its frames may ask the host
* for the browser position over the bridge. */
geolocation?: true
}
+/**
+ * A plugin's POI categories as the feed sent them, checked again against the shared
+ * schema before anything draws them: the colour lands in marker markup and the label
+ * in the pill, so an entry the schema refuses is dropped rather than rendered. So is a
+ * repeated id (the pill key must be unique), anything past the cap, and everything
+ * when the plugin id could not be read back out of a pill key.
+ */
+export function readPoiCategories(pluginId: string, raw: unknown): PluginPoiCategory[] {
+ if (!Array.isArray(raw) || typeof pluginId !== 'string' || !PLUGIN_POI_PLUGIN_ID_RE.test(pluginId)) return []
+ const out: PluginPoiCategory[] = []
+ for (const entry of raw.slice(0, PLUGIN_POI_MAX_CATEGORIES)) {
+ const parsed = pluginPoiCategorySchema.safeParse(entry)
+ if (parsed.success && !out.some(c => c.id === parsed.data.id)) out.push(parsed.data)
+ }
+ return out
+}
+
+/** One feed entry with its POI categories re-validated, and the key gone when none survive. */
+function withPoiCategories(plugin: ActivePlugin): ActivePlugin {
+ const { poiCategories: raw, ...rest } = plugin
+ if (raw === undefined) return plugin
+ const poiCategories = readPoiCategories(plugin.id, raw)
+ return poiCategories.length ? { ...rest, poiCategories } : rest
+}
+
interface PluginState {
plugins: ActivePlugin[]
loaded: boolean
@@ -83,7 +118,7 @@ export const usePluginStore = create<PluginState>((set, get) => ({
loadPlugins: async () => {
try {
const data = await pluginsApi.active()
- const plugins = (data.plugins as ActivePlugin[]) || []
+ const plugins = ((data.plugins as ActivePlugin[]) || []).map(withPoiCategories)
set({ plugins, loaded: true })
// After the state is committed: a sessionStorage failure (Safari private
// mode, quota) must not cost us the plugin list we just fetched.
diff --git a/client/tests/unit/mobile/admin/MAdminPluginsPanel.test.tsx b/client/tests/unit/mobile/admin/MAdminPluginsPanel.test.tsx
index 215e0d5b7..b546a215d 100644
--- a/client/tests/unit/mobile/admin/MAdminPluginsPanel.test.tsx
+++ b/client/tests/unit/mobile/admin/MAdminPluginsPanel.test.tsx
@@ -137,6 +137,18 @@ describe('MAdminPluginsPanel — the installed row', () => {
expect(screen.getByText('gotify.net')).toBeInTheDocument();
});
+ it('FE-MOB-PLUGP-094: a plugin adding explore-pill categories says so on its row (#1781)', async () => {
+ mockPanel([plugin({
+ permissions: JSON.stringify(['hook:poi-category-provider']),
+ capabilities: JSON.stringify({
+ poiCategories: [{ id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' }],
+ }),
+ })]);
+ render(<MAdminPluginsPanel />);
+
+ expect(await screen.findByText('Adds map categories')).toBeInTheDocument();
+ });
+
it('FE-MOB-PLUGP-005: covers the whole capability vocabulary, including a replaced planner tab', async () => {
mockPanel([plugin({
permissions: JSON.stringify([
@@ -527,6 +539,46 @@ describe('MAdminPluginsPanel — the registry detail sheet', () => {
expect(screen.getByText('Boarding-pass widget')).toBeInTheDocument();
});
+ it('FE-MOB-PLUGP-095: the sheet lists the map categories a plugin adds, before the install (#1781)', async () => {
+ await openDetail({
+ ...registryEntry(),
+ size: null,
+ publishedAt: null,
+ manifest: {
+ ...manifest,
+ permissions: ['hook:poi-category-provider'],
+ capabilities: {
+ poiCategories: [
+ { id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' },
+ { id: 'swimming', label: 'Swimming spots', icon: 'Waves', color: '#0369a1' },
+ ],
+ },
+ },
+ });
+
+ 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')[1].style.backgroundColor).toBe('rgb(3, 105, 161)');
+ expect(screen.getByText('Adds map categories')).toBeInTheDocument();
+ });
+
+ it('FE-MOB-PLUGP-096: declared categories without the grant are not shown, the feed would never serve them', async () => {
+ await openDetail({
+ ...registryEntry(),
+ size: null,
+ publishedAt: null,
+ manifest: {
+ ...manifest,
+ capabilities: { poiCategories: [{ id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' }] },
+ },
+ });
+
+ expect(await screen.findByText('Reads your trips')).toBeInTheDocument();
+ expect(screen.queryByText('Map categories it adds')).not.toBeInTheDocument();
+ expect(screen.queryByText('Trailheads')).not.toBeInTheDocument();
+ });
+
it('FE-MOB-PLUGP-030: a failed detail fetch is reported inside the sheet', async () => {
mockPanel([], [registryEntry()]);
server.use(http.get('*/api/admin/plugins/registry/trek-gotify', () =>
@@ -910,6 +962,21 @@ describe('MAdminPluginsPanel — updates and consent', () => {
await waitFor(() => expect(consentBody).toEqual({ consent: true }));
});
+ it('FE-MOB-PLUGP-097: an update asking for the POI category grant spells out what it sends (#1781)', async () => {
+ mockPanel([plugin({ source_repo: 'acme/gotify', signed: true, version: '1.0.0' })], [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(<MAdminPluginsPanel />);
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Update → v2.0.0' }));
+ 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();
+ });
+
it('FE-MOB-PLUGP-048: "Keep off for now" drops the prompt and says the update stays off', async () => {
mockPanel([plugin({ source_repo: 'acme/gotify', version: '1.0.0' })], [registryEntry()]);
server.use(http.post('*/api/admin/plugins/trek-gotify/update', () =>
diff --git a/client/tests/unit/mobile/trip/MMapArea.test.tsx b/client/tests/unit/mobile/trip/MMapArea.test.tsx
index ea3502a7a..75f10c5d2 100644
--- a/client/tests/unit/mobile/trip/MMapArea.test.tsx
+++ b/client/tests/unit/mobile/trip/MMapArea.test.tsx
@@ -15,8 +15,9 @@ import type { AlternativeOverlay } from '../../../../src/components/Roadtrip/alt
import type { LegAlternatives } from '../../../../src/components/Roadtrip/useRouteAlternatives'
import { openLeg } from '../../../helpers/legAlternatives'
import { RT_ALT_BAR_LIFT } from '../../../../src/mobile/screens/trip/roadtrip/useMRtAlternatives'
+import { corePoiCategories, pluginPoiCategories } from '../../../../src/components/Map/usePoiCategories'
-// FE-MOB-MAPAREA-001 to FE-MOB-MAPAREA-043
+// FE-MOB-MAPAREA-001 to FE-MOB-MAPAREA-045
//
// The stage's pins come out of the trip store rather than the planner's map list, so the
// stage fixtures seed the store and leave `mapPlaces` to stand for what the plan tab shows.
@@ -177,6 +178,7 @@ beforeEach(() => {
mocks.glMap = COMPASS
mocks.prefs = {}
mocks.poi = {
+ categories: { core: corePoiCategories(key => key), plugin: [] },
active: new Set<string>(), pois: [], loadingKeys: new Set<string>(), errorKeys: new Set<string>(),
moved: false, toggle: vi.fn(), searchArea: vi.fn(), onViewportChange: vi.fn(),
}
@@ -315,6 +317,21 @@ describe('MMapArea', () => {
expect(planner.handlePoiClick).not.toHaveBeenCalled()
})
+ it('FE-MOB-MAPAREA-045: a plugin POI is drawn from the search and tapped into the place form like any other', () => {
+ const trailhead = {
+ osm_id: 'plugin:trail-finder:th-1', name: 'Trailhead', lat: 53.3, lng: 9.6, category: 'plugin:trail-finder/trailheads',
+ source: 'plugin:trail-finder', pluginId: 'trail-finder', icon: 'Signpost', color: '#2f855a',
+ details: [{ label: 'Length', value: '12 km' }],
+ }
+ mocks.poi = { ...mocks.poi, pois: [trailhead] }
+ const { planner } = renderArea({ trTab: 'plan' }, { selectedDayId: 5 })
+
+ // Handed to the renderer whole, so the pin and the hover card can read its look and rows.
+ expect(mocks.props.pois).toEqual([trailhead])
+ ;(mocks.props.onPoiClick as (m: unknown) => void)(trailhead)
+ expect(planner.openAddPlaceFromPoi).toHaveBeenCalledWith(trailhead, 5)
+ })
+
it('FE-MOB-MAPAREA-012: a focused hit takes the camera; with nothing pending the stage frames itself', () => {
const focused = renderArea({ trTab: 'roadtrip' }, { mapFocusPoints: [[53.5, 9.8]] })
expect(mocks.props.focusPoints).toEqual([[53.5, 9.8]])
@@ -920,4 +937,21 @@ describe('MMapArea and a booked night at the edge of the stage', () => {
expect(other.openSheet).not.toHaveBeenCalled()
expect(only.handleMarkerClick).toHaveBeenCalledWith(99)
})
+
+ it('FE-MOB-MAPAREA-044: the POI bar offers the plugin categories after its divider, without shrinking a segment', () => {
+ const plugin = pluginPoiCategories([{
+ id: 'trail-finder', name: 'Trail finder', type: 'integration', icon: null,
+ poiCategories: [{ id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' }],
+ }], 'en')
+ mocks.poi = { ...mocks.poi, categories: { core: corePoiCategories(key => key), plugin } }
+ renderArea()
+
+ const divider = screen.getByRole('separator')
+ const trailheads = screen.getByRole('button', { name: 'Trailheads' })
+ expect(divider.nextElementSibling).toBe(trailheads)
+ expect(trailheads.style.minWidth).toBe('34px')
+ expect((divider.parentElement as HTMLElement).style.overflowX).toBe('auto')
+ trailheads.click()
+ expect(mocks.poi.toggle).toHaveBeenCalledWith('plugin:trail-finder/trailheads')
+ })
})
diff --git a/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx b/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx
index 392148f8c..127c45e1b 100644
--- a/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx
+++ b/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx
@@ -11,7 +11,7 @@ import { server } from '../../../helpers/msw/server'
import { resetAllStores, seedStore } from '../../../helpers/store'
import { fireEvent, render, screen, waitFor } from '../../../helpers/render'
-// FE-MOB-PLEDIT-001 to FE-MOB-PLEDIT-042, plus the 009b, 025b and 029b variants
+// FE-MOB-PLEDIT-001 to FE-MOB-PLEDIT-043, plus the 009b, 025b and 029b variants
// planner.t echoes the key, so every label/placeholder is asserted as its key.
const CATEGORIES = [
@@ -564,4 +564,29 @@ describe('MPlaceEditSheet', () => {
setup({ editingPlace: EDITED })
expect(screen.queryByText('places.details.title')).not.toBeInTheDocument()
})
+
+ it('FE-MOB-PLEDIT-043: a plugin POI pick fills the form and asks the details block about its plugin id, not a Google one', async () => {
+ const asked: unknown[] = []
+ server.use(
+ http.post('/api/maps/enrichment', async ({ request }) => {
+ asked.push(await request.json())
+ return HttpResponse.json({ photos: [], description: null, facts: [], rating: null, hours: null })
+ }),
+ )
+ const { planner } = setup({
+ prefillCoords: {
+ lat: 47.1, lng: 11.2, name: 'Trailhead', address: 'Hut 1', website: 'https://trails.example/th-043',
+ phone: '+43 1', osm_id: 'plugin:trail-finder:th-043',
+ },
+ })
+ expect(nameField()).toHaveValue('Trailhead')
+ expect(screen.getByPlaceholderText('https://')).toHaveValue('https://trails.example/th-043')
+ // The server decides who to ask by this id, and never takes a `plugin:` one for Google's.
+ await waitFor(() => expect(asked).toEqual([expect.objectContaining({ placeId: 'plugin:trail-finder:th-043', lat: 47.1, lng: 11.2 })]))
+
+ fireEvent.click(submit())
+ await waitFor(() => expect(planner.handleSavePlace).toHaveBeenCalledTimes(1))
+ expect(planner.handleSavePlace).toHaveBeenCalledWith(expect.objectContaining({ name: 'Trailhead', osm_id: 'plugin:trail-finder:th-043' }))
+ expect(planner.handleSavePlace).not.toHaveBeenCalledWith(expect.objectContaining({ google_place_id: expect.anything() }))
+ })
})
diff --git a/plugin-sdk/README.md b/plugin-sdk/README.md
index adc14c99d..b6510038e 100644
--- a/plugin-sdk/README.md
+++ b/plugin-sdk/README.md
@@ -226,6 +226,7 @@ skipped, never fatal):
| `warningProvider` | ≤20 warnings per provider, each message ≤300 chars |
| `placeDetailProvider` | ≤12 items per provider |
| `searchProvider` | ≤20 places per provider, 2 s to answer |
+| `poiCategoryProvider` | ≤4 declared categories per plugin; ≤60 places per answer (inside `bounds` only), ≤6 detail rows per place, 8 s to answer |
| `photoProvider` | ≤60 photos per page |
| `calendarSource` | ≤500 events per source per request |
| `tableContributor` | ≤20 columns / ≤10 actions per entity |
@@ -411,3 +412,52 @@ The SDK tooling in this repo is MIT. Your plugin is your own code under your own
### Roadtrip category searches
The `searchProvider.search` request can include `category` and `bounds` (south, west, north, east). Search within that rectangle for the category; `query` remains a readable category query and `near` its centre, so existing providers continue to work. These optional fields are absent on older hosts and ordinary name searches. The host validates and filters coordinates, namespaces IDs, and applies the exact route corridor after combining sources. The existing permission and two-second hook timeout still apply.
+
+### POI categories on the trip map
+
+A plugin can add up to four chips of its own to the trip map's **Explore places** pill
+(trailheads, EV chargers, step-free places, drinking water, campsites...) and answer the
+searches for them. Declare them in the manifest and ask for `hook:poi-category-provider`:
+
+```json
+"permissions": ["hook:poi-category-provider"],
+"capabilities": {
+ "poiCategories": [
+ { "id": "trailheads", "label": "Trailheads", "labels": { "de": "Wanderparkplätze" },
+ "icon": "Signpost", "color": "#2f855a" }
+ ]
+}
+```
+
+| Field | Rule |
+|---|---|
+| `id` | `^[a-z][a-z0-9-]{0,23}$`, unique within the plugin. It is what `getPois` receives as `request.category`. |
+| `label` | Plain text, at most 40 characters, shown when `labels` has nothing for the user's language. Emoji and control characters are stripped. |
+| `labels` | Optional: TREK language code to label (`de`, `fr`, `zh-TW`...), same rules as `label`. A code this TREK does not ship is ignored. |
+| `icon` | One of `POI_CATEGORY_ICONS` (exported): Footprints, Mountain, MountainSnow, Signpost, Trees, TentTree, Tent, Accessibility, Droplet, Droplets, PlugZap, Zap, Bath, Bike, Waves, Landmark, MapPin, Star, Heart, Info. Lucide has no toilet glyph; use Bath. |
+| `color` | `#rrggbb` only. It colours the chip and the markers. |
+
+Then implement the hook:
+
+```ts
+hooks: {
+ poiCategoryProvider: {
+ async getPois({ category, bounds, lang, limit }, ctx) {
+ const rows = await myIndex.within(category, bounds, limit);
+ return rows.map((r) => ({
+ id: r.id, name: r.name, lat: r.lat, lng: r.lng,
+ details: [{ label: 'Length', value: `${r.km} km` }],
+ }));
+ },
+ },
+},
+```
+
+The host asks only the plugin that declared the chip, only for a declared id, and only
+while the grant is held. `bounds` is the viewport narrowed to at most 0.5 degrees a side.
+The host drops places outside `bounds`, keeps 60, caps strings and details (label 40,
+value 120 characters, 6 rows), allows only http/https websites, and namespaces ids as
+`plugin:<yourId>:<id>`. A timeout or a thrown error shows as an error on that chip only.
+Answers are not cached, because the hook runs as the user who picked the chip. Also
+`GET /api/plugin-pois` and, for a connected assistant, the `list_plugin_poi_categories`
+and `search_plugin_pois` MCP tools.
diff --git a/plugin-sdk/package-lock.json b/plugin-sdk/package-lock.json
index ec7820fa4..bd29bd7d3 100644
--- a/plugin-sdk/package-lock.json
+++ b/plugin-sdk/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "trek-plugin-sdk",
- "version": "1.7.1",
+ "version": "1.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "trek-plugin-sdk",
- "version": "1.7.1",
+ "version": "1.8.0",
"license": "MIT",
"dependencies": {
"@clack/prompts": "^1.7.0",
diff --git a/plugin-sdk/package.json b/plugin-sdk/package.json
index f22fa78bd..defd5b17a 100644
--- a/plugin-sdk/package.json
+++ b/plugin-sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "trek-plugin-sdk",
- "version": "1.7.1",
+ "version": "1.8.0",
"description": "SDK for building TREK plugins: types, definePlugin, a mock host, manifest validation, and the create-trek-plugin / trek-plugin CLIs.",
"type": "module",
"license": "MIT",
diff --git a/plugin-sdk/src/cli/ui.ts b/plugin-sdk/src/cli/ui.ts
index 9f596127b..885145d3b 100644
--- a/plugin-sdk/src/cli/ui.ts
+++ b/plugin-sdk/src/cli/ui.ts
@@ -213,6 +213,7 @@ export const PERMISSION_FAMILIES: PermissionFamily[] = [
{ value: 'hook:calendar-source', hint: 'Supply calendar events to TREK' },
{ value: 'hook:place-detail-provider', hint: 'Contribute extra details (reviews, ratings, links) to a place' },
{ value: 'hook:search-provider', hint: 'Answer place searches from your own index, beside the core results' },
+ { value: 'hook:poi-category-provider', hint: 'Add your own categories to the map\'s Explore bar and answer them for the visible area' },
{ value: 'hook:trip-warning-provider', hint: 'Raise validation warnings on a trip (shown in the planner)' },
{ value: 'hook:table-contributor', hint: 'Add columns to TREK\'s tables' },
{ value: 'hook:map-marker-provider', hint: 'Add your own markers to the map' },
diff --git a/plugin-sdk/src/generated/host-facts.ts b/plugin-sdk/src/generated/host-facts.ts
index e48b12ceb..b59c266c8 100644
--- a/plugin-sdk/src/generated/host-facts.ts
+++ b/plugin-sdk/src/generated/host-facts.ts
@@ -1,5 +1,6 @@
// GENERATED — do not edit by hand.
// Source: server/src/nest/plugins/protocol/envelope.ts + server/src/plugin-event-sink.ts
+// + shared/src/plugins/plugin-poi-facts.ts
// Regenerate: node --import tsx server/scripts/gen-plugin-facts.ts
export const HOOK_PERMISSION: Readonly<Record<string, string>> = {
@@ -7,6 +8,7 @@ export const HOOK_PERMISSION: Readonly<Record<string, string>> = {
calendarSource: 'hook:calendar-source',
placeDetailProvider: 'hook:place-detail-provider',
searchProvider: 'hook:search-provider',
+ poiCategoryProvider: 'hook:poi-category-provider',
warningProvider: 'hook:trip-warning-provider',
tableContributor: 'hook:table-contributor',
mapMarkerProvider: 'hook:map-marker-provider',
@@ -67,6 +69,7 @@ export const KNOWN_PERMISSIONS: string[] = [
'hook:calendar-source',
'hook:place-detail-provider',
'hook:search-provider',
+ 'hook:poi-category-provider',
'hook:trip-warning-provider',
'hook:table-contributor',
'hook:map-marker-provider',
@@ -355,3 +358,33 @@ export const EVENT_SNAPSHOT_GRANT: Readonly<Record<string, string>> = {
dayNote: 'db:read:daynotes',
file: 'db:read:files',
};
+
+/**
+ * `capabilities.poiCategories` (#1781): the lucide icons a category may use, how many
+ * categories one plugin may declare, and the longest label.
+ */
+export const POI_CATEGORY_ICONS: string[] = [
+ 'Footprints',
+ 'Mountain',
+ 'MountainSnow',
+ 'Signpost',
+ 'Trees',
+ 'TentTree',
+ 'Tent',
+ 'Accessibility',
+ 'Droplet',
+ 'Droplets',
+ 'PlugZap',
+ 'Zap',
+ 'Bath',
+ 'Bike',
+ 'Waves',
+ 'Landmark',
+ 'MapPin',
+ 'Star',
+ 'Heart',
+ 'Info',
+];
+
+export const POI_CATEGORY_MAX = 4;
+export const POI_CATEGORY_LABEL_MAX = 40;
diff --git a/plugin-sdk/src/index.ts b/plugin-sdk/src/index.ts
index 42c745732..e4fcccc59 100644
--- a/plugin-sdk/src/index.ts
+++ b/plugin-sdk/src/index.ts
@@ -518,6 +518,51 @@ export interface SearchProvider {
* limits, and a request per typed letter would spend them on words nobody finished. */
search(request: SearchRequest, ctx: PluginContext): Promise<SearchResultPlace[]>;
}
+/**
+ * What the host asks a POI category provider for: the places of ONE of your declared
+ * `capabilities.poiCategories` inside the map area the user is looking at.
+ */
+export interface PoiCategoryRequest {
+ /** One of your own `capabilities.poiCategories` ids. The host never sends any other. */
+ category: string;
+ /** The viewport, narrowed to at most 0.5 degrees a side and folded onto -180..180. */
+ bounds: { south: number; west: number; north: number; east: number };
+ /** The user's TREK language (`de`, `zh-TW`...), for indexes with localized names. */
+ lang?: string;
+ /** The most places worth returning. The host keeps at most 60 whatever you send. */
+ limit: number;
+}
+/** One row only your index knows, shown in the map popup: a trail length, a step-free entrance. */
+export interface PoiDetail {
+ /** At most 40 characters. */
+ label: string;
+ /** At most 120 characters. */
+ value: string;
+}
+/** A place in one of your categories. */
+export interface PoiCategoryPlace {
+ /** Stable id in your own index. The host namespaces it as `plugin:<yourId>:<id>`. */
+ id?: string;
+ name: string;
+ lat: number;
+ lng: number;
+ address?: string;
+ website?: string;
+ phone?: string;
+ /** Zero to five. */
+ rating?: number;
+ /** At most 6 rows. */
+ details?: PoiDetail[];
+}
+export interface PoiCategoryProvider {
+ /** Places for a chip you added to the trip map's "Explore places" pill.
+ * Needs `hook:poi-category-provider` and the category declared in
+ * `capabilities.poiCategories`. Runs as the user who picked the chip, so
+ * `ctx.settings.get()` is theirs. The host keeps places inside `bounds` only, at most
+ * 60 of them, and gives you 8 seconds to answer. Called when the user picks the chip
+ * or asks to search the area again, not on every pan. */
+ getPois(request: PoiCategoryRequest, ctx: PluginContext): Promise<PoiCategoryPlace[]>;
+}
/** A validation/warning a plugin raises on a trip; TREK surfaces it in the planner. */
export interface TripWarning { level: 'info' | 'warning' | 'error'; message: string; dayId?: number; placeId?: number; }
export interface WarningProvider {
@@ -871,6 +916,7 @@ export interface PluginDefinition {
calendarSource?: CalendarSource;
placeDetailProvider?: PlaceDetailProvider;
searchProvider?: SearchProvider;
+ poiCategoryProvider?: PoiCategoryProvider;
warningProvider?: WarningProvider;
tableContributor?: TableContributor;
mapMarkerProvider?: MapMarkerProvider;
@@ -920,6 +966,8 @@ export {
export {
EVENT_FAMILIES, EVENT_SNAPSHOT_GRANT, KNOWN_PERMISSIONS,
} from './generated/host-facts.js';
+// The lucide icons a `capabilities.poiCategories` entry may use, and the per-plugin cap.
+export { POI_CATEGORY_ICONS, POI_CATEGORY_MAX } from './generated/host-facts.js';
/** Scope for host-managed, per-user session state in a sandboxed plugin UI. */
export type PluginSessionStorageScope = 'plugin' | 'trip';
diff --git a/plugin-sdk/src/manifest.ts b/plugin-sdk/src/manifest.ts
index 01d5b8d27..8be61a1a4 100644
--- a/plugin-sdk/src/manifest.ts
+++ b/plugin-sdk/src/manifest.ts
@@ -71,6 +71,10 @@ export interface ManifestCapabilities {
tripPage?: { replaces?: string[]; position?: number };
notificationChannel?: { title?: string; events?: string[] };
routeProfiles?: Array<{ id: string; label: string; icon?: string }>;
+ /** Chips in the trip map's Explore places pill, answered by the poiCategoryProvider
+ * hook. Requires `hook:poi-category-provider`. At most 4; `icon` is one of
+ * POI_CATEGORY_ICONS, `color` a `#rrggbb` hex, `labels` per TREK language code. */
+ poiCategories?: Array<{ id: string; label: string; labels?: Record<string, string>; icon: string; color: string }>;
/** MCP tools published via the mcpToolProvider hook. Requires `mcp:tools`. */
mcpTools?: Array<{
name: string;
@@ -171,7 +175,7 @@ export const CHANNEL_EVENTS = [
// in cli/ui.ts, which only supplies the grouping and hints), so a permission added here can
// never again go missing from the scaffolder — test/cli.test.ts fails until it has an entry.
export { KNOWN_PERMISSIONS } from './generated/host-facts.js';
-import { KNOWN_PERMISSIONS } from './generated/host-facts.js';
+import { KNOWN_PERMISSIONS, POI_CATEGORY_ICONS, POI_CATEGORY_LABEL_MAX, POI_CATEGORY_MAX } from './generated/host-facts.js';
function isKnownPermission(p: string): boolean {
return KNOWN_PERMISSIONS.includes(p) || p.startsWith('http:outbound:');
@@ -257,6 +261,7 @@ export function validateManifest(raw: unknown): ValidationResult {
tripPage?: { replaces?: unknown; position?: unknown };
notificationChannel?: { title?: unknown; events?: unknown };
routeProfiles?: unknown;
+ poiCategories?: unknown;
mcpTools?: unknown;
provides?: unknown;
emits?: unknown;
@@ -335,6 +340,7 @@ export function validateManifest(raw: unknown): ValidationResult {
}
}
}
+ validatePoiCategories(capabilities?.poiCategories, permissions, errors);
// MCP tools go into every user's assistant context, so the declaration is
// checked here too rather than only at install: an author should hear about a
// malformed one from `trek-plugin validate`, not from a tool that never shows up.
@@ -497,6 +503,70 @@ export function validateManifest(raw: unknown): ValidationResult {
return { ok: true, errors: [], manifest };
}
+// Mirrors the host's reader for capabilities.poiCategories (server
+// src/nest/plugins/poi-categories.ts): the same checks, so `validate` refuses exactly
+// what an install would. The icon list and the caps are generated from the host.
+const POI_CATEGORY_ID_RE = /^[a-z][a-z0-9-]{0,23}$/;
+const POI_COLOR_RE = /^#[0-9a-fA-F]{6}$/;
+const POI_LANGUAGE_KEY_RE = /^[a-z]{2,3}(?:-[A-Z]{2})?$/;
+
+function poiLabelOk(v: unknown): boolean {
+ const label = typeof v === 'string' ? v.trim() : '';
+ return label.length > 0 && label.length <= POI_CATEGORY_LABEL_MAX;
+}
+
+// The per-language labels are optional; when present every key must be a language
+// code and every value a label, like the host's reader.
+function poiLabelsProblem(id: string, labels: unknown): string | null {
+ if (labels === undefined) return null;
+ if (!labels || typeof labels !== 'object' || Array.isArray(labels)) {
+ return `"${id}" labels must be an object of language code to label`;
+ }
+ for (const [code, label] of Object.entries(labels as Record<string, unknown>)) {
+ if (!POI_LANGUAGE_KEY_RE.test(code)) return `"${id}" labels: "${code}" is not a language code`;
+ if (!poiLabelOk(label)) return `"${id}" labels.${code} is required (max ${POI_CATEGORY_LABEL_MAX} chars)`;
+ }
+ return null;
+}
+
+function poiCategoryProblem(v: unknown): string | null {
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return 'entries must be objects';
+ const p = v as Record<string, unknown>;
+ const id = typeof p.id === 'string' ? p.id : '';
+ if (!POI_CATEGORY_ID_RE.test(id)) return 'id must be lowercase [a-z][a-z0-9-], max 24 chars';
+ if (!poiLabelOk(p.label)) return `"${id}" label is required (max ${POI_CATEGORY_LABEL_MAX} chars)`;
+ if (typeof p.icon !== 'string' || !POI_CATEGORY_ICONS.includes(p.icon)) {
+ return `"${id}" icon must be one of ${POI_CATEGORY_ICONS.join(', ')}`;
+ }
+ if (typeof p.color !== 'string' || !POI_COLOR_RE.test(p.color)) return `"${id}" color must be a #rrggbb hex colour`;
+ return poiLabelsProblem(id, p.labels);
+}
+
+function validatePoiCategories(raw: unknown, permissions: string[], errors: string[]): void {
+ if (raw === undefined) return;
+ // The host installs a declaration without the grant but never shows its chips, so
+ // the author hears about it here instead of from an empty pill.
+ if (!permissions.includes('hook:poi-category-provider')) {
+ errors.push('capabilities.poiCategories requires the "hook:poi-category-provider" permission');
+ }
+ if (!Array.isArray(raw)) {
+ errors.push('capabilities.poiCategories must be an array');
+ return;
+ }
+ if (raw.length > POI_CATEGORY_MAX) errors.push(`capabilities.poiCategories: at most ${POI_CATEGORY_MAX} categories`);
+ const seen = new Set<string>();
+ for (const v of raw) {
+ const problem = poiCategoryProblem(v);
+ if (problem) {
+ errors.push(`capabilities.poiCategories: ${problem}`);
+ continue;
+ }
+ const id = (v as { id: string }).id;
+ if (seen.has(id)) errors.push(`capabilities.poiCategories: duplicate id "${id}"`);
+ seen.add(id);
+ }
+}
+
// Export/event names exposed to other plugins (dots allowed for event names).
const CAPABILITY_NAME_RE = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/;
diff --git a/plugin-sdk/test/sdk.test.ts b/plugin-sdk/test/sdk.test.ts
index 53ba0b723..51e9f279b 100644
--- a/plugin-sdk/test/sdk.test.ts
+++ b/plugin-sdk/test/sdk.test.ts
@@ -109,6 +109,38 @@ describe('validateManifest', () => {
expect(bad('ev')).toBe(false);
});
+ it('validates capabilities.poiCategories exactly like the host and ties it to hook:poi-category-provider', () => {
+ const category = { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze', xx: 'ignored' }, icon: 'Signpost', color: '#2f855a' };
+ const withGrant = (poiCategories: unknown) =>
+ validateManifest({ ...base, permissions: ['hook:poi-category-provider'], capabilities: { poiCategories } });
+ const ok = withGrant([category]);
+ expect(ok.errors).toEqual([]);
+ expect(ok.manifest?.capabilities?.poiCategories?.[0].id).toBe('trailheads');
+ // chips without the grant never show, so validate says so rather than the empty pill
+ expect(validateManifest({ ...base, capabilities: { poiCategories: [category] } }).errors)
+ .toContain('capabilities.poiCategories requires the "hook:poi-category-provider" permission');
+ const bad = (over: Record<string, unknown>) => withGrant([{ ...category, ...over }]).ok;
+ expect(bad({ id: 'Trail' })).toBe(false);
+ expect(bad({ label: ' ' })).toBe(false);
+ expect(bad({ label: 'L'.repeat(41) })).toBe(false);
+ expect(bad({ icon: 'Toilet' })).toBe(false);
+ expect(bad({ icon: undefined })).toBe(false);
+ expect(bad({ color: 'red' })).toBe(false);
+ expect(bad({ color: '#2f855a;background:url(x)' })).toBe(false);
+ expect(bad({ labels: ['de'] })).toBe(false);
+ expect(bad({ labels: { 'de_DE': 'x' } })).toBe(false);
+ expect(bad({ labels: { de: '' } })).toBe(false);
+ expect(bad({ id: 5 })).toBe(false);
+ expect(bad({ label: 5 })).toBe(false);
+ expect(withGrant([1]).errors).toContain('capabilities.poiCategories: entries must be objects');
+ // the per-language labels are optional, as on the host
+ const plain = { id: category.id, label: category.label, icon: category.icon, color: category.color };
+ expect(withGrant([plain]).ok).toBe(true);
+ expect(withGrant([category, category]).errors).toContain('capabilities.poiCategories: duplicate id "trailheads"');
+ expect(withGrant([1, 2, 3, 4, 5].map((i) => ({ ...category, id: `c${i}` }))).ok).toBe(false);
+ expect(withGrant('trailheads').ok).toBe(false);
+ });
+
it('accepts the read-symmetry + broker permissions (collab, file content, trip create, rates)', () => {
const permissions = ['db:read:collab', 'db:create:trips', 'rates:read', 'db:read:files:content'];
const r = validateManifest({ ...base, permissions });
diff --git a/server/scripts/gen-plugin-facts.ts b/server/scripts/gen-plugin-facts.ts
index eccb32a33..add1b3f5a 100644
--- a/server/scripts/gen-plugin-facts.ts
+++ b/server/scripts/gen-plugin-facts.ts
@@ -22,12 +22,19 @@ import {
EVENTS_PERMISSION, JOBS_PERMISSION, USER_DATA_PERMISSION, HTTP_OUTBOUND_PREFIX,
} from '../src/nest/plugins/protocol/envelope';
import { SNAPSHOT_GRANT, ENTITY_ID_KEYS } from '../src/plugin-event-sink';
+// A relative import of the shared SOURCE, not @trek/shared: the plugin-facts CI job
+// installs only the server, so shared's dist does not exist there. The file has no
+// imports of its own for exactly this reason.
+import {
+ PLUGIN_POI_ICONS, PLUGIN_POI_LABEL_MAX, PLUGIN_POI_MAX_CATEGORIES,
+} from '../../shared/src/plugins/plugin-poi-facts';
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const HEADER = [
'// GENERATED — do not edit by hand.',
'// Source: server/src/nest/plugins/protocol/envelope.ts + server/src/plugin-event-sink.ts',
+ '// + shared/src/plugins/plugin-poi-facts.ts',
'// Regenerate: node --import tsx server/scripts/gen-plugin-facts.ts',
'',
].join('\n');
@@ -82,6 +89,17 @@ ${list(EVENT_FAMILIES)}
export const EVENT_SNAPSHOT_GRANT: Readonly<Record<string, string>> = {
${pairs(SNAPSHOT_GRANT)}
};
+
+/**
+ * \`capabilities.poiCategories\` (#1781): the lucide icons a category may use, how many
+ * categories one plugin may declare, and the longest label.
+ */
+export const POI_CATEGORY_ICONS: string[] = [
+${list(PLUGIN_POI_ICONS)}
+];
+
+export const POI_CATEGORY_MAX = ${PLUGIN_POI_MAX_CATEGORIES};
+export const POI_CATEGORY_LABEL_MAX = ${PLUGIN_POI_LABEL_MAX};
`;
const SHARED_FACTS = `${HEADER}
diff --git a/server/src/nest/maps/maps.helpers.ts b/server/src/nest/maps/maps.helpers.ts
index 15f4f9f76..1e61a4889 100644
--- a/server/src/nest/maps/maps.helpers.ts
+++ b/server/src/nest/maps/maps.helpers.ts
@@ -2,6 +2,7 @@ import { normalizePlaceWebsite } from '@trek/shared';
import { readEnv, getAppUrl } from '../../app-config';
import { stripHtmlTags } from '../common/stripHtmlTags';
import { haversineMetres } from '../common/geo';
+import { z } from 'zod';
/**
* Pure maps/geo helpers — no DB, no Nest, no side effects beyond reading env.
@@ -374,6 +375,51 @@ export const CATEGORY_OSM_FILTERS: Record<string, string[]> = {
export const POI_CATEGORY_KEYS = Object.keys(CATEGORY_OSM_FILTERS);
+/**
+ * Largest viewport side one POI search covers. A country-sized box makes Overpass scan
+ * millions of elements and time out, and a plugin POI provider is no better placed to
+ * answer for a continent, so both paths narrow a larger box to a centred window.
+ */
+export const MAX_POI_BBOX_SPAN_DEG = 0.5;
+
+export interface PoiBbox {
+ south: number;
+ west: number;
+ north: number;
+ east: number;
+}
+
+/** Narrow an oversized viewport to a centred window; `clamped` says it happened. */
+export function clampPoiBbox(bbox: PoiBbox): { bbox: PoiBbox; clamped: boolean } {
+ let { south, west, north, east } = bbox;
+ let clamped = false;
+ if (north - south > MAX_POI_BBOX_SPAN_DEG) {
+ const c = (north + south) / 2;
+ south = c - MAX_POI_BBOX_SPAN_DEG / 2;
+ north = c + MAX_POI_BBOX_SPAN_DEG / 2;
+ clamped = true;
+ }
+ if (east - west > MAX_POI_BBOX_SPAN_DEG) {
+ const c = (east + west) / 2;
+ west = c - MAX_POI_BBOX_SPAN_DEG / 2;
+ east = c + MAX_POI_BBOX_SPAN_DEG / 2;
+ clamped = true;
+ }
+ return { bbox: { south, west, north, east }, clamped };
+}
+
+/**
+ * The rectangle the MCP POI tools take: search_pois for the core categories and
+ * search_plugin_pois for the plugin ones. One definition, so both accept the same box
+ * and describe the same window it is narrowed to.
+ */
+export const POI_BBOX_TOOL_INPUT = z.strictObject({
+ south: z.number().min(-90).max(90).describe('Southern edge, latitude'),
+ west: z.number().min(-180).max(180).describe('Western edge, longitude'),
+ north: z.number().min(-90).max(90).describe('Northern edge, latitude'),
+ east: z.number().min(-180).max(180).describe('Eastern edge, longitude'),
+}).describe(`The rectangle to search. Anything wider than ${MAX_POI_BBOX_SPAN_DEG} degrees is narrowed to a centred window so the query stays fast; the answer reports that as \`clamped\``);
+
/** How many categories one POI query may carry, so a caller can't fan out the mirrors. */
export const MAX_POI_CATEGORIES = 8;
@@ -740,13 +786,18 @@ export function parseWikipediaTag(tag: string | undefined | null): { lang: strin
// per place — photo refs, editorial summary, and the photo route.
const NON_GOOGLE_PLACE_ID =
/^(?:coords|gers|node|way|relation|amap):|^https?:\/\/|^-?\d+(?:\.\d+)?,\s*-?\d+(?:\.\d+)?$|~p\d+$/i;
+// `plugin:` too (`plugin:<pluginId>:<id>`, #2221 and #1781): a place picked from a
+// plugin search or a plugin POI category keeps the plugin's id, and it names the
+// plugin's own index, never a Google record. A pattern of its own, because the one
+// above is already as tangled as a pattern should get.
+const PLUGIN_PLACE_ID = /^plugin:/i;
// The subset that still has a provider behind it — Overpass for details,
// Wikimedia for photos. The id has to be the whole of what follows the colon:
// it is written into an Overpass query as it is, and an element id is a number.
export const OSM_PLACE_ID = /^(?:node|way|relation):\d+$/i;
export function isGooglePlaceId(placeId: string): boolean {
- return !NON_GOOGLE_PLACE_ID.test(placeId);
+ return !NON_GOOGLE_PLACE_ID.test(placeId) && !PLUGIN_PLACE_ID.test(placeId);
}
// ── Ranking Commons candidates ───────────────────────────────────────────────
diff --git a/server/src/nest/maps/maps.mcp.ts b/server/src/nest/maps/maps.mcp.ts
index 9f6b0e7ec..a242c12fd 100644
--- a/server/src/nest/maps/maps.mcp.ts
+++ b/server/src/nest/maps/maps.mcp.ts
@@ -1,6 +1,6 @@
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type McpContext } from '../../nest-mcp';
import { z } from 'zod';
-import { POI_CATEGORY_KEYS, MAX_POI_CATEGORIES } from './maps.helpers';
+import { POI_BBOX_TOOL_INPUT, POI_CATEGORY_KEYS, MAX_POI_CATEGORIES } from './maps.helpers';
import { MapsService } from './maps.service';
/**
@@ -95,12 +95,7 @@ export class MapsMcp {
z.enum(POI_CATEGORY_KEYS),
z.array(z.enum(POI_CATEGORY_KEYS)).min(1).max(MAX_POI_CATEGORIES),
]).describe('Which kind of place to look for. Pass several to cover them in one query rather than one request per kind'),
- bbox: z.strictObject({
- south: z.number().min(-90).max(90).describe('Southern edge, latitude'),
- west: z.number().min(-180).max(180).describe('Western edge, longitude'),
- north: z.number().min(-90).max(90).describe('Northern edge, latitude'),
- east: z.number().min(-180).max(180).describe('Eastern edge, longitude'),
- }).describe('The rectangle to search. Anything wider than 0.5 degrees is narrowed to a centred window so the query stays fast; the answer reports that as `clamped`'),
+ bbox: POI_BBOX_TOOL_INPUT,
lang: z.string().max(35).optional().describe('Language for the POI names, e.g. "de" or "ja". Falls back to the OSM international name and then the local one'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
diff --git a/server/src/nest/maps/maps.service.ts b/server/src/nest/maps/maps.service.ts
index 2ceacafac..28b833bd1 100644
--- a/server/src/nest/maps/maps.service.ts
+++ b/server/src/nest/maps/maps.service.ts
@@ -50,6 +50,7 @@ import {
OSM_PLACE_ID,
CATEGORY_OSM_FILTERS,
parsePoiCategories,
+ clampPoiBbox,
resolveOverpassEndpoints,
resolveOverpassTimeoutMs,
OVERPASS_QUERY_TIMEOUT_S,
@@ -573,11 +574,6 @@ interface PoiSearchResult {
// see src/app-config/README.md).
const OVERPASS_MIRRORS = resolveOverpassEndpoints();
const OVERPASS_TIMEOUT_MS = resolveOverpassTimeoutMs();
-// Largest viewport side we send to Overpass. A country/continent-sized bbox makes
-// Overpass scan millions of elements and time out; clamping to a centred window
-// keeps the query cheap so the explore pill returns fast at ANY zoom level.
-const MAX_BBOX_SPAN_DEG = 0.5;
-
// Short-lived cache so panning back over / re-toggling the same area doesn't
// re-hit Overpass. Keyed by category + rounded (post-clamp) bbox.
const POI_CACHE = new Map<string, { at: number; value: PoiSearchResult }>();
@@ -1426,20 +1422,9 @@ export class MapsService {
// Clamp an oversized viewport to a centred window so the query stays cheap and
// returns fast at any zoom, instead of timing out / 502-ing on a huge area.
- let { south, west, north, east } = bbox;
- let clamped = false;
- if (north - south > MAX_BBOX_SPAN_DEG) {
- const c = (north + south) / 2;
- south = c - MAX_BBOX_SPAN_DEG / 2;
- north = c + MAX_BBOX_SPAN_DEG / 2;
- clamped = true;
- }
- if (east - west > MAX_BBOX_SPAN_DEG) {
- const c = (east + west) / 2;
- west = c - MAX_BBOX_SPAN_DEG / 2;
- east = c + MAX_BBOX_SPAN_DEG / 2;
- clamped = true;
- }
+ const searchWindow = clampPoiBbox(bbox);
+ const { south, west, north, east } = searchWindow.bbox;
+ const clamped = searchWindow.clamped;
// OSM `name:*` tags are keyed by language subtag: prefer the user's language
// (the same localization the search/autocomplete path asks the geocoder for)
diff --git a/server/src/nest/plugins/contributions/plugin-contributions.module.ts b/server/src/nest/plugins/contributions/plugin-contributions.module.ts
index c1bfc30b3..c98cb6f5d 100644
--- a/server/src/nest/plugins/contributions/plugin-contributions.module.ts
+++ b/server/src/nest/plugins/contributions/plugin-contributions.module.ts
@@ -7,6 +7,9 @@ import { PluginSearchController } from './plugin-search.controller';
import { TripWarningsController } from './trip-warnings.controller';
import { TripWarningsMcp } from './trip-warnings.mcp';
import { PluginSearchMcp } from './plugin-search.mcp';
+import { PluginPoisController } from './plugin-pois.controller';
+import { PluginPoisMcp } from './plugin-pois.mcp';
+import { PluginPoisService } from './plugin-pois.service';
import { PluginMcpToolsService } from './plugin-mcp-tools.service';
import { ViewContributionsController } from './view-contributions.controller';
import { TripCardContributionsController } from './trip-card-contributions.controller';
@@ -23,9 +26,9 @@ import { JournalEntryRowsController } from './journal-entry-rows.controller';
/**
* The read-only surface plugins contribute to the app: photos, calendar events,
- * place details, search results, trip warnings, table columns, map markers and
- * layers, routes, day schedules and tints, PDF sections, atlas layers, journal entry
- * rows, trip cards.
+ * place details, search results, explore-pill POI categories, trip warnings, table
+ * columns, map markers and layers, routes, day schedules and tints, PDF sections,
+ * atlas layers, journal entry rows, trip cards.
*
* Every one of these is the same shape — fan out over `providersOf(hook)`, call the
* hook through `PluginHooks`, normalize and cap what comes back, skip a provider that
@@ -38,6 +41,7 @@ import { JournalEntryRowsController } from './journal-entry-rows.controller';
controllers: [
PlaceDetailsController,
PluginSearchController,
+ PluginPoisController,
TripWarningsController,
ViewContributionsController,
TripCardContributionsController,
@@ -59,6 +63,10 @@ import { JournalEntryRowsController } from './journal-entry-rows.controller';
// PluginMcpToolsService owns the process-level tool source. It lives here, and
// not on PluginRuntimeService beside the other sinks, because it needs
// PluginHooks and PluginHooks injects PluginRuntimeService.
- providers: [TripWarningsMcp, PluginSearchMcp, PluginMcpToolsService],
+ //
+ // PluginPoisService is the one contribution with a service of its own: its REST
+ // route and its MCP tools ask the same targeted question, so the gate and the
+ // normalization live once, behind both.
+ providers: [TripWarningsMcp, PluginSearchMcp, PluginPoisService, PluginPoisMcp, PluginMcpToolsService],
})
export class PluginContributionsModule {}
diff --git a/server/src/nest/plugins/contributions/plugin-pois.controller.ts b/server/src/nest/plugins/contributions/plugin-pois.controller.ts
new file mode 100644
index 000000000..c25dc809b
--- /dev/null
+++ b/server/src/nest/plugins/contributions/plugin-pois.controller.ts
@@ -0,0 +1,74 @@
+import { Controller, Get, HttpException, Query, UseGuards } from '@nestjs/common';
+import { pluginPoiQuerySchema, type PluginPoiQuery, type PluginPoiResponse } from '@trek/shared';
+import type { User } from '../../../types';
+import { CurrentUser } from '../../auth/current-user.decorator';
+import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
+import { PluginPoisService, UNKNOWN_POI_CATEGORY } from './plugin-pois.service';
+
+const BBOX_FIELDS: ReadonlySet<string> = new Set(['south', 'west', 'north', 'east', 'bbox']);
+
+function missing(v: unknown): boolean {
+ return v === undefined || (typeof v === 'string' && v.trim() === '');
+}
+
+/**
+ * The query through the shared contract, with the bespoke messages of
+ * GET /api/maps/pois for what the two routes share: the client already maps those two
+ * strings, and a chip failing differently depending on whose chip it is would be
+ * noise. A malformed plugin or category id is a 404, not a 400: nothing that shape
+ * can be a declaration, which is the only thing this route answers for.
+ */
+export function parsePluginPoiQuery(raw: Record<string, unknown>): PluginPoiQuery {
+ if (missing(raw.category)) throw new HttpException({ error: 'A category is required' }, 400);
+ if (missing(raw.pluginId)) throw new HttpException({ error: 'A plugin is required' }, 400);
+ const parsed = pluginPoiQuerySchema.safeParse(raw);
+ if (parsed.success) return parsed.data;
+ const fields = new Set(parsed.error.issues.map((i) => String(i.path[0] ?? '')));
+ if ([...fields].some((f) => BBOX_FIELDS.has(f))) {
+ throw new HttpException({ error: 'A valid bbox (south, west, north, east) is required' }, 400);
+ }
+ if (fields.has('lang')) throw new HttpException({ error: 'lang must be at most 35 characters' }, 400);
+ throw new HttpException({ error: UNKNOWN_POI_CATEGORY }, 404);
+}
+
+/**
+ * GET /api/plugin-pois: the places of ONE plugin POI category inside the map area the
+ * user is looking at (#1781), for a chip a plugin added to the explore pill.
+ *
+ * Targeted like the plugin routes rather than a fan-out like the plugin search: the
+ * chip names its plugin, so exactly that plugin is asked, and only for an id its
+ * manifest declared (404 otherwise). The answer is the row shape of /api/maps/pois,
+ * so the map draws it the way it draws a core category, plus the category's icon and
+ * colour and the plugin's own detail rows.
+ *
+ * A route of its own rather than a branch of /api/maps/pois, for the module-cycle
+ * reason plugin-search.controller.ts gives: the plugin runtime imports PlacesModule,
+ * which imports MapsModule. The client sends plugin keys here and core keys there, so
+ * a slow plugin (8 seconds, then 502) only ever holds up its own chip.
+ *
+ * Not trip-scoped, like the core route: the area is the caller's own viewport and
+ * nothing about a trip is passed to the plugin.
+ */
+@Controller('api/plugin-pois')
+@UseGuards(JwtAuthGuard)
+export class PluginPoisController {
+ constructor(private readonly pois: PluginPoisService) {}
+
+ @Get()
+ async list(@Query() raw: Record<string, unknown>, @CurrentUser() user: User): Promise<PluginPoiResponse> {
+ const q = parsePluginPoiQuery(raw);
+ const outcome = await this.pois.search(
+ {
+ pluginId: q.pluginId,
+ category: q.category,
+ bbox: { south: q.south, west: q.west, north: q.north, east: q.east },
+ lang: q.lang,
+ },
+ user.id,
+ );
+ // `in` rather than `!outcome.ok`: the server compiles without strictNullChecks,
+ // where a boolean discriminant does not narrow the union.
+ if ('error' in outcome) throw new HttpException({ error: outcome.error }, outcome.status);
+ return outcome.result;
+ }
+}
diff --git a/server/src/nest/plugins/contributions/plugin-pois.helpers.ts b/server/src/nest/plugins/contributions/plugin-pois.helpers.ts
new file mode 100644
index 000000000..e4dfda8d3
--- /dev/null
+++ b/server/src/nest/plugins/contributions/plugin-pois.helpers.ts
@@ -0,0 +1,131 @@
+import {
+ PLUGIN_POI_DETAIL_LABEL_MAX,
+ PLUGIN_POI_DETAIL_VALUE_MAX,
+ PLUGIN_POI_DETAILS_MAX,
+ PLUGIN_POI_HIT_CAP,
+ pluginPoiCategoryKey,
+ type PluginPoi,
+ type PluginPoiCategory,
+ type PluginPoiDetail,
+} from '@trek/shared';
+import { clampPoiBbox, type PoiBbox } from '../../maps/maps.helpers';
+import { sanitiseAssistantText } from '../text-sanitize';
+import { normalizeSearchHit } from './plugin-search.helpers';
+
+/**
+ * Turning what a `poiCategoryProvider` answers into explore-pill POIs (#1781).
+ *
+ * Shared by the REST route and the MCP tool for the reason plugin-search.helpers.ts
+ * gives: a cap that held on one path and not the other would be a hole with a second
+ * door. Each hit goes through the search normalizer first, so a place from a category
+ * chip is capped, namespaced and url-checked exactly like one from a search, and only
+ * then gains what a POI row carries.
+ */
+
+// How much of a plugin's answer the host is willing to walk. Bounds the WORK, not
+// only the output: an answer of a million malformed rows would otherwise be read in
+// full on the host's event loop before the cap ever applied.
+const MAX_RAW_POIS = PLUGIN_POI_HIT_CAP * 4;
+const MAX_RAW_DETAILS = PLUGIN_POI_DETAILS_MAX * 4;
+
+/**
+ * The box a provider is asked about: the viewport narrowed to the same search window
+ * the Overpass path uses, then folded back onto the globe. A map panned across the
+ * antimeridian reports its edges unwrapped (a west of 190), and no provider should
+ * have to know that.
+ */
+export function pluginPoiWindow(bbox: PoiBbox): { bounds: PoiBbox; clamped: boolean } {
+ const narrowed = clampPoiBbox(bbox);
+ const b = narrowed.bbox;
+ const shift = Math.round((b.west + b.east) / 2 / 360) * 360;
+ const west = b.west - shift;
+ const east = b.east - shift;
+ const bounds = {
+ south: Math.max(-90, b.south),
+ west: Math.max(-180, west),
+ north: Math.min(90, b.north),
+ east: Math.min(180, east),
+ };
+ const cut = bounds.south !== b.south || bounds.north !== b.north || bounds.west !== west || bounds.east !== east;
+ return { bounds, clamped: narrowed.clamped || cut };
+}
+
+function detailText(v: unknown, max: number): string {
+ // A string, or a figure a plugin sent as one. An object would read "[object Object]".
+ if (typeof v === 'string' || typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v))) {
+ return sanitiseAssistantText(String(v), max);
+ }
+ return '';
+}
+
+/**
+ * The rows only a plugin can answer (trail length, step-free entrance, water type).
+ * Flattened to one line each and emoji-stripped, like MCP tool text: the list is shown
+ * in the map popup and also handed to an assistant.
+ */
+export function normalizePoiDetails(raw: unknown): PluginPoiDetail[] {
+ if (!Array.isArray(raw)) return [];
+ const out: PluginPoiDetail[] = [];
+ for (const d of raw.slice(0, MAX_RAW_DETAILS)) {
+ if (out.length >= PLUGIN_POI_DETAILS_MAX) break;
+ if (!d || typeof d !== 'object') continue;
+ const row = d as Record<string, unknown>;
+ const label = detailText(row.label, PLUGIN_POI_DETAIL_LABEL_MAX);
+ const value = detailText(row.value, PLUGIN_POI_DETAIL_VALUE_MAX);
+ if (label && value) out.push({ label, value });
+ }
+ return out;
+}
+
+function inside(bounds: PoiBbox, lat: number, lng: number): boolean {
+ return lat >= bounds.south && lat <= bounds.north && lng >= bounds.west && lng <= bounds.east;
+}
+
+/**
+ * The POIs of one plugin answer: well-formed, inside the box the plugin was asked
+ * about, unique by id, and at most the per-category share a core category gets.
+ * `truncated` says the plugin sent more than that (or more than the host would read).
+ */
+export function normalizePluginPois(
+ pluginId: string,
+ category: PluginPoiCategory,
+ bounds: PoiBbox,
+ raw: unknown[],
+): { pois: PluginPoi[]; truncated: boolean } {
+ const key = pluginPoiCategoryKey(pluginId, category.id);
+ const byId = new Map<string, PluginPoi>();
+ let truncated = raw.length > MAX_RAW_POIS;
+ for (const entry of raw.slice(0, MAX_RAW_POIS)) {
+ const hit = normalizeSearchHit(pluginId, entry);
+ if (!hit || !inside(bounds, hit.lat, hit.lng) || byId.has(hit.osm_id)) continue;
+ if (byId.size >= PLUGIN_POI_HIT_CAP) {
+ truncated = true;
+ break;
+ }
+ byId.set(hit.osm_id, {
+ osm_id: hit.osm_id,
+ name: hit.name,
+ lat: hit.lat,
+ lng: hit.lng,
+ // The host names the category, never the plugin: a hit claiming another
+ // plugin's key (or a core one) would otherwise restyle markers it does not own.
+ category: key,
+ poi_type: key,
+ address: hit.address || null,
+ website: hit.website,
+ phone: hit.phone,
+ opening_hours: null,
+ cuisine: null,
+ brand: null,
+ brand_wikidata: null,
+ charging: null,
+ source: hit.source,
+ pluginId,
+ rating: hit.rating,
+ details: normalizePoiDetails((entry as Record<string, unknown>).details),
+ icon: category.icon,
+ color: category.color,
+ });
+ }
+ return { pois: [...byId.values()], truncated };
+}
diff --git a/server/src/nest/plugins/contributions/plugin-pois.mcp.ts b/server/src/nest/plugins/contributions/plugin-pois.mcp.ts
new file mode 100644
index 000000000..319b52af5
--- /dev/null
+++ b/server/src/nest/plugins/contributions/plugin-pois.mcp.ts
@@ -0,0 +1,67 @@
+import { PLUGIN_POI_CATEGORY_ID_RE, PLUGIN_POI_PLUGIN_ID_RE, isOrderedPoiBbox } from '@trek/shared';
+import { z } from 'zod';
+import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type McpContext } from '../../../nest-mcp';
+import { POI_BBOX_TOOL_INPUT } from '../../maps/maps.helpers';
+import { PluginPoisService } from './plugin-pois.service';
+
+/**
+ * The MCP half of the plugin POI categories (#1781): the chips a plugin adds to the
+ * explore pill, and GET /api/plugin-pois behind them.
+ *
+ * Two tools because the browser has two reads: the feed that tells the pill which
+ * chips exist, and the search one chip runs. An assistant cannot guess a plugin's
+ * category ids, so it lists them first. Both sit here rather than beside
+ * `search_pois` for the module-cycle reason plugin-search.mcp.ts gives, and both use
+ * `search_pois`' access group, since they answer the same question for other sources.
+ */
+@McpController()
+export class PluginPoisMcp {
+ constructor(private readonly pois: PluginPoisService) {}
+
+ @Tool({
+ name: 'list_plugin_poi_categories',
+ description: 'List the extra place categories installed plugins add to the trip map\'s "Explore places" bar, such as hiking trailheads, EV chargers, wheelchair-accessible places, public toilets and drinking water, or campsites. Each entry names the plugin (`pluginId`) and its own category id (`id`), which is what search_plugin_pois takes. Returns an empty list when no plugin adds categories, which is the normal case; the built-in categories are the ones search_pois covers.',
+ inputSchema: {
+ lang: z.string().max(35).optional().describe('Language for the category labels, e.g. "de". Falls back to the plugin\'s default label'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ access: { group: 'geo', mode: 'read' },
+ })
+ listCategories({ lang }: { lang?: string }, _ctx: McpContext) {
+ return ok({ categories: this.pois.available(lang) });
+ }
+
+ @Tool({
+ name: 'search_plugin_pois',
+ description: 'List the places of one plugin-provided category (from list_plugin_poi_categories) inside a map rectangle, as the plugin answers them. Results have the shape search_pois returns, plus the `pluginId` that answered, a `rating` where the plugin has one, and `details`: up to six label and value rows only that plugin knows, such as a trail length or a step-free entrance. Use search_pois for the built-in categories. Never calls Google.',
+ inputSchema: {
+ pluginId: z.string().regex(PLUGIN_POI_PLUGIN_ID_RE).describe('The plugin that declared the category, from list_plugin_poi_categories'),
+ category: z.string().regex(PLUGIN_POI_CATEGORY_ID_RE).describe('The plugin\'s own category id, from list_plugin_poi_categories'),
+ bbox: POI_BBOX_TOOL_INPUT,
+ lang: z.string().max(35).optional().describe('Language for the place names, e.g. "de", for plugins that carry localized names'),
+ },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ access: { group: 'geo', mode: 'read' },
+ })
+ async search(
+ { pluginId, category, bbox, lang }: {
+ pluginId: string;
+ category: string;
+ bbox: { south: number; west: number; north: number; east: number };
+ lang?: string;
+ },
+ ctx: McpContext,
+ ) {
+ // The REST query schema refuses an inverted box; the same box as numbers here.
+ if (!isOrderedPoiBbox(bbox)) return errorResult('A valid bbox (south, west, north, east) is required.');
+ const outcome = await this.pois.search({ pluginId, category, bbox, lang }, ctx.userId);
+ if ('error' in outcome) {
+ return errorResult(
+ outcome.status === 404
+ ? 'Unknown plugin POI category. list_plugin_poi_categories names the ones installed.'
+ : 'Plugin POI search failed.',
+ );
+ }
+ return ok(outcome.result);
+ }
+}
diff --git a/server/src/nest/plugins/contributions/plugin-pois.service.ts b/server/src/nest/plugins/contributions/plugin-pois.service.ts
new file mode 100644
index 000000000..0e0b27526
--- /dev/null
+++ b/server/src/nest/plugins/contributions/plugin-pois.service.ts
@@ -0,0 +1,124 @@
+import { Injectable } from '@nestjs/common';
+import {
+ PLUGIN_POI_HIT_CAP,
+ pluginPoiCategoryKey,
+ pluginPoiCategoryLabel,
+ type PluginPoiCategory,
+ type PluginPoiResponse,
+} from '@trek/shared';
+import { DatabaseService } from '../../database/database.service';
+import { pluginsEnabled } from '../kill-switch';
+import { PluginHooks } from '../plugin-hooks.service';
+import { poiCategoriesOf } from '../poi-categories';
+import { sanitiseAssistantText } from '../text-sanitize';
+import { normalizePluginPois, pluginPoiWindow } from './plugin-pois.helpers';
+
+/** One search for a plugin POI category, as both the REST route and the MCP tool ask it. */
+export interface PluginPoiSearch {
+ pluginId: string;
+ category: string;
+ bbox: { south: number; west: number; north: number; east: number };
+ lang?: string;
+}
+
+/** A category the explore pill can offer right now, with the plugin that answers it. */
+export interface AvailablePoiCategory {
+ /** The pill key, `plugin:<pluginId>/<categoryId>`. */
+ key: string;
+ pluginId: string;
+ pluginName: string;
+ /** The plugin-local id, what `search_plugin_pois` takes as `category`. */
+ id: string;
+ /** In the requested language where the plugin ships one. */
+ label: string;
+ icon: PluginPoiCategory['icon'];
+ color: string;
+}
+
+export type PluginPoiOutcome =
+ | { ok: true; result: PluginPoiResponse }
+ | { ok: false; status: 404 | 502; error: string };
+
+export const UNKNOWN_POI_CATEGORY = 'Unknown POI category';
+
+// The manifest only asks for a non-empty name, and list_plugin_poi_categories hands it
+// to an assistant once per category, so it gets the same flattening and cap as a
+// plugin's tool title before it goes there.
+const PLUGIN_NAME_MAX = 80;
+
+/**
+ * The plugin POI categories (#1781): which ones exist, and asking the plugin that
+ * declared one for its places in a map area.
+ *
+ * A category is only ever answered by the plugin that declared it, and only while
+ * that plugin is a provider (active, implements `poiCategoryProvider`, holds
+ * `hook:poi-category-provider`) and still declares it in its signed manifest. Both
+ * checks are re-read per request, like the route profiles next door, so a plugin
+ * deactivated mid-session answers 404 rather than whatever it said last.
+ *
+ * Nothing is cached. The hook runs as the requesting user, so a provider may filter
+ * by that user's own settings (a wheelchair profile, say), and the shared POI cache of
+ * the core path is keyed by area alone.
+ */
+@Injectable()
+export class PluginPoisService {
+ constructor(
+ private readonly hooks: PluginHooks,
+ private readonly dbs: DatabaseService,
+ ) {}
+
+ /** Every category a provider currently answers, in the order the feed lists plugins. */
+ available(language = 'en'): AvailablePoiCategory[] {
+ if (!pluginsEnabled()) return [];
+ const providers = new Set(this.hooks.providersOf('poiCategoryProvider'));
+ if (providers.size === 0) return [];
+ const rows = this.dbs.all<{ id: string; name: string; capabilities: string | null }>(
+ "SELECT id, name, capabilities FROM plugins WHERE status = 'active' ORDER BY sort_order, name",
+ );
+ return rows
+ .filter((row) => providers.has(row.id))
+ .flatMap((row) => {
+ const pluginName = sanitiseAssistantText(row.name, PLUGIN_NAME_MAX) || row.id;
+ return poiCategoriesOf(row.capabilities).map((c) => ({
+ key: pluginPoiCategoryKey(row.id, c.id),
+ pluginId: row.id,
+ pluginName,
+ id: c.id,
+ label: pluginPoiCategoryLabel(c, language),
+ icon: c.icon,
+ color: c.color,
+ }));
+ });
+ }
+
+ /** The declaration behind (pluginId, categoryId), or null when there is none to answer. */
+ declared(pluginId: string, categoryId: string): PluginPoiCategory | null {
+ if (!pluginsEnabled()) return null;
+ if (!this.hooks.providersOf('poiCategoryProvider').includes(pluginId)) return null;
+ const row = this.dbs.get<{ capabilities: string | null }>('SELECT capabilities FROM plugins WHERE id = ?', pluginId);
+ return poiCategoriesOf(row?.capabilities).find((c) => c.id === categoryId) ?? null;
+ }
+
+ async search(input: PluginPoiSearch, userId: number): Promise<PluginPoiOutcome> {
+ const category = this.declared(input.pluginId, input.category);
+ if (!category) return { ok: false, status: 404, error: UNKNOWN_POI_CATEGORY };
+
+ const { bounds, clamped } = pluginPoiWindow(input.bbox);
+ let raw: unknown;
+ try {
+ raw = await this.hooks.categoryPois(
+ input.pluginId,
+ { category: category.id, bounds, ...(input.lang ? { lang: input.lang } : {}), limit: PLUGIN_POI_HIT_CAP },
+ userId,
+ );
+ } catch {
+ // A timeout, a crash or a thrown error. The chip shows its error dot; the core
+ // categories are separate requests and never wait on this one.
+ return { ok: false, status: 502, error: 'The plugin did not answer' };
+ }
+ if (!Array.isArray(raw)) return { ok: false, status: 502, error: 'The plugin sent an invalid answer' };
+
+ const { pois, truncated } = normalizePluginPois(input.pluginId, category, bounds, raw);
+ return { ok: true, result: { pois, source: `plugin:${input.pluginId}`, truncated, clamped } };
+ }
+}
diff --git a/server/src/nest/plugins/contributions/plugin-search.helpers.ts b/server/src/nest/plugins/contributions/plugin-search.helpers.ts
index 416c80f7c..12e8d9981 100644
--- a/server/src/nest/plugins/contributions/plugin-search.helpers.ts
+++ b/server/src/nest/plugins/contributions/plugin-search.helpers.ts
@@ -53,44 +53,60 @@ const capOrNull = (v: unknown, n: number): string | null => {
* that provider, and dropping the whole hit over it would lose the place as well.
*/
function safeRating(raw: unknown): number | null {
+ // Only a number or a numeric string is a rating. Number(null), Number('') and
+ // Number(true) are 0, 0 and 1, and an unrated place is not a zero-star one.
+ if (typeof raw !== 'number' && (typeof raw !== 'string' || raw.trim() === '')) return null;
const n = Number(raw);
if (!Number.isFinite(n)) return null;
return Math.min(5, Math.max(0, Math.round(n * 10) / 10));
}
+/**
+ * One place a plugin answered, or null when it cannot be shown or picked.
+ *
+ * Also what the plugin POI categories read their hits with (#1781), so a place from a
+ * category chip is capped, namespaced and url-checked exactly like one from a search.
+ */
+export function normalizeSearchHit(pluginId: string, raw: unknown): SearchHit | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const h = raw as Record<string, unknown>;
+ const lat = Number(h.lat);
+ const lng = Number(h.lng);
+ const name = cap(h.name, 200);
+ // A hit with no name or no place on the earth cannot be shown or picked.
+ if (!name || !Number.isFinite(lat) || !Number.isFinite(lng)) return null;
+ if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
+ // Falls back to the coordinate when the plugin has no stable id of its own, which
+ // still tells two rows apart.
+ const ref = cap(h.id, 100) || `${lat},${lng}`;
+ return {
+ // Namespaced so a plugin id can never collide with a real OSM id or a `gers:`
+ // one from the index.
+ osm_id: `plugin:${pluginId}:${ref}`,
+ name,
+ address: cap(h.address, 300),
+ lat,
+ lng,
+ rating: safeRating(h.rating),
+ // Through the helper every other source uses (#2483): a `javascript:` or
+ // `data:` url rendered as a link is click-XSS into the search list, and a
+ // bare host gains https here as it does from the core search.
+ website: normalizePlaceWebsite(h.website),
+ phone: capOrNull(h.phone, 60),
+ category: capOrNull(h.category, 60),
+ description: capOrNull(h.description, 500),
+ source: `plugin:${pluginId}`,
+ pluginId,
+ };
+}
+
export function normalizeSearchHits(pluginId: string, raw: unknown): SearchHit[] {
- const list = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
+ const list = Array.isArray(raw) ? (raw as unknown[]) : [];
const out: SearchHit[] = [];
for (const h of list) {
if (out.length >= MAX_HITS) break;
- if (!h || typeof h !== 'object') continue;
- const lat = Number(h.lat);
- const lng = Number(h.lng);
- const name = cap(h.name, 200);
- // A hit with no name or no place on the earth cannot be shown or picked.
- if (!name || !Number.isFinite(lat) || !Number.isFinite(lng)) continue;
- if (lat < -90 || lat > 90 || lng < -180 || lng > 180) continue;
- const id = cap(h.id, 100);
- out.push({
- // Namespaced so a plugin id can never collide with a real OSM id or a `gers:`
- // one from the index. Falls back to the coordinate when the plugin has no stable
- // id of its own, which still tells two rows apart.
- osm_id: `plugin:${pluginId}:${id || `${lat},${lng}`}`,
- name,
- address: cap(h.address, 300),
- lat,
- lng,
- rating: safeRating(h.rating),
- // Through the helper every other source uses (#2483): a `javascript:` or
- // `data:` url rendered as a link is click-XSS into the search list, and a
- // bare host gains https here as it does from the core search.
- website: normalizePlaceWebsite(h.website),
- phone: capOrNull(h.phone, 60),
- category: capOrNull(h.category, 60),
- description: capOrNull(h.description, 500),
- source: `plugin:${pluginId}`,
- pluginId,
- });
+ const hit = normalizeSearchHit(pluginId, h);
+ if (hit) out.push(hit);
}
return out;
}
diff --git a/server/src/nest/plugins/install/manifest.ts b/server/src/nest/plugins/install/manifest.ts
index c8a7327be..120e324c2 100644
--- a/server/src/nest/plugins/install/manifest.ts
+++ b/server/src/nest/plugins/install/manifest.ts
@@ -10,6 +10,8 @@ import {
sanitiseToolText,
} from '../mcp-tool-schema';
import type { NotifEventType } from '../../notifications/notification-events';
+import { PLUGIN_POI_MAX_CATEGORIES, type PluginPoiCategory } from '@trek/shared';
+import { readPoiCategory } from '../poi-categories';
/**
* Parse + validate a plugin's trek-plugin.json (#plugins, M4). Kept deliberately
@@ -105,6 +107,8 @@ export interface PluginCapabilities {
notificationChannel?: NotificationChannelCapability;
/** Routing profiles offered via the routeProvider hook (max 3). */
routeProfiles?: RouteProfileCapability[];
+ /** Explore-pill categories answered via the poiCategoryProvider hook (max 4, #1781). */
+ poiCategories?: PluginPoiCategory[];
/** MCP tools offered via the mcpToolProvider hook (max 8). */
mcpTools?: McpToolCapability[];
/** Function names this plugin exposes to its dependents via ctx.plugins.call. */
@@ -414,6 +418,10 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
}
if (profiles.length) out.routeProfiles = profiles;
}
+ if (c.poiCategories !== undefined) {
+ const categories = parsePoiCategories(c.poiCategories);
+ if (categories.length) out.poiCategories = categories;
+ }
if (c.mcpTools !== undefined) {
out.mcpTools = parseMcpToolCapabilities(c.mcpTools);
}
@@ -458,6 +466,31 @@ void _channelEventDriftGuard;
// plugin can take over bookings/transports/…, never the whole trip.
const REPLACEABLE_TABS = ['transports', 'buchungen', 'listen', 'finanzplan', 'dateien', 'collab'];
+/**
+ * Validate `capabilities.poiCategories`: the plugin's own chips in the explore pill.
+ *
+ * Like routeProfiles, a declaration without the `hook:poi-category-provider` grant
+ * still installs; the feed shows the chips only while the grant is held, so an admin
+ * who withholds it gets a plugin without them rather than a failed install. Every
+ * entry is otherwise checked here, loudly, by the reader the feed re-validates with.
+ */
+function parsePoiCategories(raw: unknown): PluginPoiCategory[] {
+ if (!Array.isArray(raw)) throw new ManifestError('capabilities.poiCategories must be an array');
+ if (raw.length > PLUGIN_POI_MAX_CATEGORIES) {
+ throw new ManifestError(`capabilities.poiCategories: at most ${PLUGIN_POI_MAX_CATEGORIES} categories`);
+ }
+ const out: PluginPoiCategory[] = [];
+ for (const v of raw) {
+ const read = readPoiCategory(v);
+ if ('reason' in read) throw new ManifestError(`capabilities.poiCategories: ${read.reason}`);
+ if (out.some((x) => x.id === read.value.id)) {
+ throw new ManifestError(`capabilities.poiCategories: duplicate id "${read.value.id}"`);
+ }
+ out.push(read.value);
+ }
+ return out;
+}
+
/** Validate a `provides`/`emits` array: de-duplicated, well-formed names. */
/**
* Validate and bound `capabilities.mcpTools`.
diff --git a/server/src/nest/plugins/plugin-hooks.service.ts b/server/src/nest/plugins/plugin-hooks.service.ts
index b7d0055f0..4671ad89b 100644
--- a/server/src/nest/plugins/plugin-hooks.service.ts
+++ b/server/src/nest/plugins/plugin-hooks.service.ts
@@ -36,6 +36,22 @@ export interface HookSearchRequest {
bounds?: { south: number; west: number; north: number; east: number };
}
+/**
+ * What a POI category provider is asked for (#1781): the places of ONE of its own
+ * declared categories inside the map area the user is looking at.
+ *
+ * `category` is the plugin-local id from `capabilities.poiCategories`, never a pill
+ * key, and the host only ever sends an id the manifest declared. `bounds` is the
+ * viewport after the host narrowed it to a search window, so a provider never has to
+ * answer for a whole continent.
+ */
+export interface HookPoiRequest {
+ category: string;
+ bounds: { south: number; west: number; north: number; east: number };
+ lang?: string;
+ limit: number;
+}
+
/** The waypoint request a route provider is asked to solve. */
export interface HookRouteRequest {
tripId: number;
@@ -47,8 +63,9 @@ export interface HookRouteRequest {
/**
* Every host-to-plugin hook call, in one place.
*
- * The 16 hooks the consent screen offers used to be invoked straight from the
- * controllers, with the fn name and the timeout written out at each call site. That
+ * The hooks the consent screen offers (one per HOOK_PERMISSION key, 18 of them now)
+ * used to be invoked straight from the controllers, with the fn name and the timeout
+ * written out at each call site. That
* made three things impossible to check: that a granted `hook:*` permission actually
* has a consumer (a dead grant on the consent screen looks exactly like a live one),
* that the fn name the host asks for matches the one the SDK documents, and that two
@@ -113,6 +130,20 @@ export class PluginHooks {
return this.runtime.invokeHook(pluginId, 'searchProvider', 'search', [request], userId, 2000);
}
+ /**
+ * A chip in the explore pill, answered by the plugin that declared it.
+ *
+ * Longer than the search budget because nobody is typing: the person picked a
+ * category and waits for markers, the way they wait for the core categories, whose
+ * Overpass path is allowed far more. It is still well short of that, because a
+ * provider behind an external API that has not answered in eight seconds is not
+ * going to, and the chip should show its error dot rather than spin.
+ */
+ @PluginHook('poiCategoryProvider', { permission: 'hook:poi-category-provider', fn: 'getPois', timeoutMs: 8000 })
+ categoryPois(pluginId: string, request: HookPoiRequest, userId: number): Promise<unknown> {
+ return this.runtime.invokeHook(pluginId, 'poiCategoryProvider', 'getPois', [request], userId, 8000);
+ }
+
@PluginHook('warningProvider', { permission: 'hook:trip-warning-provider', fn: 'getWarnings', timeoutMs: 5000 })
tripWarnings(pluginId: string, tripId: number, userId: number): Promise<unknown> {
return this.runtime.invokeHook(pluginId, 'warningProvider', 'getWarnings', [tripId], userId, 5000);
diff --git a/server/src/nest/plugins/plugins-feed.controller.ts b/server/src/nest/plugins/plugins-feed.controller.ts
index 2e6648ef5..98a3a68d1 100644
--- a/server/src/nest/plugins/plugins-feed.controller.ts
+++ b/server/src/nest/plugins/plugins-feed.controller.ts
@@ -1,7 +1,9 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
+import type { PluginPoiCategory } from '@trek/shared';
import { DatabaseService } from '../database/database.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { pluginsEnabled } from './kill-switch';
+import { POI_CATEGORY_PERMISSION, poiCategoriesOf } from './poi-categories';
/**
* GET /api/plugins — the authenticated feed of ACTIVE plugins the client renders
@@ -22,6 +24,8 @@ interface ActivePlugin {
settingsUi?: true;
/** Routing profiles the planner's route toggle offers (routeProvider hook, granted only). */
routeProfiles?: Array<{ id: string; label: string; icon?: string }>;
+ /** Categories the explore pill offers (poiCategoryProvider hook, granted only, #1781). */
+ poiCategories?: PluginPoiCategory[];
/** The plugin holds the geolocation:read grant — its frames may request the
* browser position over the host bridge (the browser prompt still applies). */
geolocation?: true;
@@ -41,12 +45,14 @@ export class PluginsFeedController {
const plugins = rows.map(({ capabilities, granted_permissions, ...p }) => {
const tripPage = p.type === 'trip-page' ? tripPageOf(capabilities) : undefined;
const routeProfiles = routeProfilesOf(capabilities, granted_permissions);
+ const poiCategories = hasGrant(granted_permissions, POI_CATEGORY_PERMISSION) ? poiCategoriesOf(capabilities) : [];
return {
...p,
slot: slotOf(capabilities),
...(tripPage ? { tripPage } : {}),
...(settingsUiOf(capabilities) ? { settingsUi: true as const } : {}),
...(routeProfiles ? { routeProfiles } : {}),
+ ...(poiCategories.length ? { poiCategories } : {}),
...(hasGrant(granted_permissions, 'geolocation:read') ? { geolocation: true as const } : {}),
};
});
diff --git a/server/src/nest/plugins/plugins-runtime.module.ts b/server/src/nest/plugins/plugins-runtime.module.ts
index 3572a3ac7..fcee83bed 100644
--- a/server/src/nest/plugins/plugins-runtime.module.ts
+++ b/server/src/nest/plugins/plugins-runtime.module.ts
@@ -75,7 +75,7 @@ import { JournalRpcModule } from '../journey/journal-rpc.module';
PluginRegistryService,
PluginRpcHostFactory,
PluginRpcRegistryService,
- // Owns no wire method; declares and performs all 18 host-to-plugin hook calls.
+ // Owns no wire method; declares and performs all 21 host-to-plugin hook calls.
PluginHooks,
// The wire surface that belongs to no domain: the plugin's own sqlite, its
// namespaced entity metadata, and the host-mediated calls (user lookup,
diff --git a/server/src/nest/plugins/plugins.module.ts b/server/src/nest/plugins/plugins.module.ts
index b01e52882..a6b69a0b9 100644
--- a/server/src/nest/plugins/plugins.module.ts
+++ b/server/src/nest/plugins/plugins.module.ts
@@ -20,7 +20,7 @@ import { AppConfigModule } from '../app-config/app-config.module';
*
* - `PluginsRuntimeModule` — supervisor, capability router, hook contracts. The half
* with the domain imports, and the only half AdminModule needs.
- * - `PluginContributionsModule` — the 15 read-only hook controllers.
+ * - `PluginContributionsModule`: the 16 read-only hook controllers.
* - `PluginOAuthModule` — the outbound-OAuth leaf.
*
* What is left here is the CRUD and delivery surface: install/activate/configure, the
diff --git a/server/src/nest/plugins/poi-categories.ts b/server/src/nest/plugins/poi-categories.ts
new file mode 100644
index 000000000..b5b919abc
--- /dev/null
+++ b/server/src/nest/plugins/poi-categories.ts
@@ -0,0 +1,116 @@
+import {
+ PLUGIN_POI_CATEGORY_ID_RE,
+ PLUGIN_POI_COLOR_RE,
+ PLUGIN_POI_ICONS,
+ PLUGIN_POI_LABEL_MAX,
+ PLUGIN_POI_MAX_CATEGORIES,
+ SUPPORTED_LANGUAGE_CODES,
+ isPluginPoiIcon,
+ pluginPoiCategorySchema,
+ type PluginPoiCategory,
+} from '@trek/shared';
+import { sanitiseAssistantText } from './text-sanitize';
+
+/**
+ * Reading a plugin's `capabilities.poiCategories` (#1781), in one place for the three
+ * readers that need it: the manifest parser at install, the GET /api/plugins feed, and
+ * the plugin-pois route deciding whether a category is a real declaration.
+ *
+ * One reader with two callers' strictness rather than two readers, because the feed
+ * re-validates the stored JSON (a hand-edited capabilities row must never surface a
+ * value the parser would have refused) and the two sets of rules drifting apart is
+ * exactly how such a value would get through. The install path turns a refusal into a
+ * manifest error; the other two skip the entry.
+ */
+
+export const POI_CATEGORY_PERMISSION = 'hook:poi-category-provider';
+
+// Shaped like a language tag ('de', 'zh-TW'). A well-formed tag for a language TREK
+// does not ship is dropped rather than refused, so a plugin that already carries a
+// label for a language added in a later TREK still installs on this one.
+const LANGUAGE_KEY_RE = /^[a-z]{2,3}(?:-[A-Z]{2})?$/;
+const LANGUAGES: ReadonlySet<string> = new Set(SUPPORTED_LANGUAGE_CODES);
+
+export type PoiCategoryRead = { ok: true; value: PluginPoiCategory } | { ok: false; reason: string };
+
+/**
+ * A label as TREK draws it: control characters and emoji gone, whitespace flattened.
+ * The same cleaning as MCP tool text, because a category label is shown in the pill,
+ * in the admin panel and to an assistant listing the categories.
+ */
+function cleanLabel(raw: string): string {
+ return sanitiseAssistantText(raw, PLUGIN_POI_LABEL_MAX);
+}
+
+/** The author's text, checked the way the SDK checks it: present and not too long. */
+function rawLabel(v: unknown): string | null {
+ const label = typeof v === 'string' ? v.trim() : '';
+ return label && label.length <= PLUGIN_POI_LABEL_MAX ? label : null;
+}
+
+function readLabels(raw: unknown): { ok: true; value?: Record<string, string> } | { ok: false; reason: string } {
+ if (raw === undefined) return { ok: true };
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ return { ok: false, reason: 'labels must be an object of language code to label' };
+ }
+ const out: Record<string, string> = {};
+ for (const [code, value] of Object.entries(raw as Record<string, unknown>)) {
+ if (!LANGUAGE_KEY_RE.test(code)) return { ok: false, reason: `labels: "${code.slice(0, 20)}" is not a language code` };
+ const label = rawLabel(value);
+ if (!label) return { ok: false, reason: `labels.${code} is required (max ${PLUGIN_POI_LABEL_MAX} chars)` };
+ const clean = cleanLabel(label);
+ if (LANGUAGES.has(code) && clean) out[code] = clean;
+ }
+ return { ok: true, value: Object.keys(out).length ? out : undefined };
+}
+
+/** One declared category, or the reason it is not one. */
+export function readPoiCategory(raw: unknown): PoiCategoryRead {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { ok: false, reason: 'entries must be objects' };
+ const p = raw as Record<string, unknown>;
+ const id = typeof p.id === 'string' ? p.id : '';
+ if (!PLUGIN_POI_CATEGORY_ID_RE.test(id)) return { ok: false, reason: 'id must be lowercase [a-z][a-z0-9-], max 24 chars' };
+ const label = rawLabel(p.label);
+ if (!label) return { ok: false, reason: `"${id}" label is required (max ${PLUGIN_POI_LABEL_MAX} chars)` };
+ if (!isPluginPoiIcon(p.icon)) {
+ return { ok: false, reason: `"${id}" icon must be one of ${PLUGIN_POI_ICONS.join(', ')}` };
+ }
+ if (typeof p.color !== 'string' || !PLUGIN_POI_COLOR_RE.test(p.color)) {
+ return { ok: false, reason: `"${id}" color must be a #rrggbb hex colour` };
+ }
+ const labels = readLabels(p.labels);
+ if ('reason' in labels) return { ok: false, reason: `"${id}" ${labels.reason}` };
+ const parsed = pluginPoiCategorySchema.safeParse({
+ id,
+ // An all-emoji label cleans to nothing; the id is still a readable name.
+ label: cleanLabel(label) || id,
+ ...(labels.value ? { labels: labels.value } : {}),
+ icon: p.icon,
+ color: p.color.toLowerCase(),
+ });
+ return parsed.success ? { ok: true, value: parsed.data } : { ok: false, reason: `"${id}" is not a valid category` };
+}
+
+/**
+ * The declared categories that survive re-validation, in declaration order: entries
+ * the parser would refuse are skipped, as is a repeated id and anything past the cap.
+ */
+export function poiCategoriesFrom(raw: unknown): PluginPoiCategory[] {
+ if (!Array.isArray(raw)) return [];
+ const out: PluginPoiCategory[] = [];
+ for (const v of raw.slice(0, PLUGIN_POI_MAX_CATEGORIES)) {
+ const read = readPoiCategory(v);
+ if (read.ok && !out.some((c) => c.id === read.value.id)) out.push(read.value);
+ }
+ return out;
+}
+
+/** The same, read off a plugins.capabilities JSON column. */
+export function poiCategoriesOf(capabilities: string | null | undefined): PluginPoiCategory[] {
+ try {
+ const c = JSON.parse(capabilities || '{}') as { poiCategories?: unknown } | null;
+ return poiCategoriesFrom(c?.poiCategories);
+ } catch {
+ return [];
+ }
+}
diff --git a/server/src/nest/plugins/protocol/envelope.ts b/server/src/nest/plugins/protocol/envelope.ts
index c32a7a9d8..1430c3713 100644
--- a/server/src/nest/plugins/protocol/envelope.ts
+++ b/server/src/nest/plugins/protocol/envelope.ts
@@ -359,6 +359,11 @@ export const KNOWN_PERMISSIONS = [
'hook:calendar-source',
'hook:place-detail-provider',
'hook:search-provider',
+ // Adds the plugin's own categories to the explore pill on the trip map and answers
+ // them for the area the user is looking at (#1781). Its own permission, not a reuse
+ // of hook:search-provider: a search provider is asked about words the user typed, this
+ // one is sent the viewport, and the consent screen has to say which is which.
+ 'hook:poi-category-provider',
'hook:trip-warning-provider',
'hook:table-contributor',
'hook:map-marker-provider',
@@ -432,6 +437,7 @@ export const HOOK_PERMISSION = {
calendarSource: 'hook:calendar-source',
placeDetailProvider: 'hook:place-detail-provider',
searchProvider: 'hook:search-provider',
+ poiCategoryProvider: 'hook:poi-category-provider',
warningProvider: 'hook:trip-warning-provider',
tableContributor: 'hook:table-contributor',
mapMarkerProvider: 'hook:map-marker-provider',
diff --git a/server/src/nest/plugins/registry/registry.service.ts b/server/src/nest/plugins/registry/registry.service.ts
index 65258f662..36afc2f7b 100644
--- a/server/src/nest/plugins/registry/registry.service.ts
+++ b/server/src/nest/plugins/registry/registry.service.ts
@@ -18,6 +18,8 @@ import path from 'node:path';
import semver from 'semver';
import { MCP_TOOLS_MAX, TOOL_DESCRIPTION_MAX, TOOL_TITLE_MAX } from '../mcp-tool-schema';
import { sanitiseAssistantText } from '../text-sanitize';
+import { poiCategoriesFrom } from '../poi-categories';
+import type { PluginPoiCategory } from '@trek/shared';
/**
* TREK-side of the plugin registry (#plugins, M5). Fetches the single aggregated
@@ -135,6 +137,12 @@ export interface ManifestPreview {
* approving the grant rather than meeting it later inside a chat.
*/
mcpTools?: Array<{ name: string; title?: string; description: string }>;
+ /**
+ * The chips this plugin will add to every user's explore pill, and whose searches
+ * it will then be sent the viewport for (#1781). Shown before the install for the
+ * same reason as the tools above.
+ */
+ poiCategories?: PluginPoiCategory[];
};
}
@@ -878,6 +886,10 @@ export function previewManifest(raw: unknown): ManifestPreview {
.map((t) => ({ name: t.name, ...(t.title ? { title: t.title } : {}), description: t.description }));
if (tools.length) capabilities.mcpTools = tools;
}
+ // Through the reader the feed uses, so the preview never shows a category the
+ // installed plugin would not get.
+ const poiCategories = poiCategoriesFrom(rawCaps.poiCategories);
+ if (poiCategories.length) capabilities.poiCategories = poiCategories;
return {
permissions: strings(m.permissions),
diff --git a/server/src/nest/plugins/runtime/plugin-sdk.ts b/server/src/nest/plugins/runtime/plugin-sdk.ts
index ef49f548a..e768dd022 100644
--- a/server/src/nest/plugins/runtime/plugin-sdk.ts
+++ b/server/src/nest/plugins/runtime/plugin-sdk.ts
@@ -450,6 +450,15 @@ export interface SearchRequest {
export interface SearchProvider {
search(request: SearchRequest, ctx: PluginContext): Promise<SearchResultPlace[]>;
}
+/**
+ * A POI category provider (#1781). Only the hook's name and call are spelled out here:
+ * the request and place shapes authors write against live once, in the published SDK.
+ * The child dispatches the hook by name, and the host re-validates every place it
+ * answers (plugin-pois.helpers.ts), so a second typed copy would guard nothing.
+ */
+export interface PoiCategoryProvider {
+ getPois(request: Readonly<Record<string, unknown>>, ctx: PluginContext): Promise<unknown[]>;
+}
/** A validation/warning a plugin raises on a trip; TREK surfaces it in the planner. */
export interface TripWarning { level: 'info' | 'warning' | 'error'; message: string; dayId?: number; placeId?: number; }
export interface WarningProvider {
@@ -758,6 +767,7 @@ export interface PluginDefinition {
calendarSource?: CalendarSource;
placeDetailProvider?: PlaceDetailProvider;
searchProvider?: SearchProvider;
+ poiCategoryProvider?: PoiCategoryProvider;
warningProvider?: WarningProvider;
tableContributor?: TableContributor;
mapMarkerProvider?: MapMarkerProvider;
diff --git a/server/tests/e2e/plugin-pois.e2e.test.ts b/server/tests/e2e/plugin-pois.e2e.test.ts
new file mode 100644
index 000000000..3ad30bf6b
--- /dev/null
+++ b/server/tests/e2e/plugin-pois.e2e.test.ts
@@ -0,0 +1,153 @@
+/**
+ * GET /api/plugin-pois e2e (#1781): the real guard chain and the real contribution
+ * module against a temp SQLite db, with only the plugin itself played by a spy.
+ *
+ * The unit tests pin the parsing and the normalizer. What only a booted container
+ * shows is that the route sits behind JwtAuthGuard (401 before anything else), that
+ * the bespoke 400s survive the global pipe, and that the declaration it re-reads is
+ * the plugins row, so a category the manifest never declared is a 404 however
+ * willing the plugin would be to answer it.
+ */
+import { DatabaseModule } from '../../src/nest/database/database.module';
+import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
+import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
+import { PluginContributionsModule } from '../../src/nest/plugins/contributions/plugin-contributions.module';
+import { PluginHooks } from '../../src/nest/plugins/plugin-hooks.service';
+import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
+import { seedUser, sessionCookie } from './harness';
+import { Test } from '@nestjs/testing';
+
+import cookieParser from 'cookie-parser';
+import type { Server } from 'http';
+import request from 'supertest';
+import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockInstance } from 'vitest';
+
+const { db, pluginsEnabled } = vi.hoisted(() => {
+ const Database = require('better-sqlite3');
+ const tmp = new Database(':memory:');
+ tmp.exec('PRAGMA journal_mode = WAL');
+ tmp.exec('PRAGMA foreign_keys = ON');
+ tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
+ email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0,
+ avatar TEXT);`);
+ tmp.exec(`CREATE TABLE plugins (id TEXT PRIMARY KEY, name TEXT NOT NULL, type TEXT, icon TEXT,
+ status TEXT NOT NULL DEFAULT 'inactive', sort_order INTEGER NOT NULL DEFAULT 0,
+ capabilities TEXT, permissions TEXT DEFAULT '[]', granted_permissions TEXT DEFAULT '[]');`);
+ tmp.exec('CREATE TABLE addons (id TEXT PRIMARY KEY, enabled INTEGER NOT NULL DEFAULT 0, name TEXT, description TEXT, category TEXT, sort_order INTEGER DEFAULT 0);');
+ tmp.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);');
+ // Off while the app boots, so the runtime does not go looking for plugins on disk;
+ // the tests switch it on.
+ return { db: tmp, pluginsEnabled: { value: false } };
+});
+
+vi.mock('../../src/db/database', () => ({
+ db,
+ canAccessTrip: () => undefined,
+ isOwner: () => false,
+ getPlaceWithTags: () => null,
+ closeDb: () => {},
+ reinitialize: () => {},
+}));
+vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
+vi.mock('../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled: () => pluginsEnabled.value }));
+
+const trailheads = { id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' };
+const query = { pluginId: 'trail-finder', category: 'trailheads', south: '47', west: '11', north: '47.5', east: '11.5', lang: 'de' };
+
+describe('Plugin POIs e2e (real guard chain + temp SQLite)', () => {
+ let server: Server;
+ let app: Awaited<ReturnType<typeof build>>;
+ let providersOf: MockInstance;
+ let categoryPois: MockInstance;
+
+ async function build() {
+ const moduleRef = await Test.createTestingModule({
+ imports: [DatabaseModule, RealtimeModule, PluginContributionsModule],
+ }).compile();
+ const nest = moduleRef.createNestApplication();
+ nest.use(cookieParser());
+ nest.useGlobalPipes(new ZodValidationPipe());
+ nest.useGlobalFilters(new TrekExceptionFilter());
+ await nest.init();
+ return nest;
+ }
+
+ beforeAll(async () => {
+ seedUser(db as never, { id: 1 });
+ db.prepare("INSERT INTO plugins (id, name, status, capabilities, granted_permissions) VALUES (?, ?, 'active', ?, ?)")
+ .run('trail-finder', 'Trail Finder', JSON.stringify({ poiCategories: [trailheads] }), JSON.stringify(['hook:poi-category-provider']));
+ app = await build();
+ const hooks = app.get(PluginHooks, { strict: false });
+ providersOf = vi.spyOn(hooks, 'providersOf');
+ categoryPois = vi.spyOn(hooks, 'categoryPois');
+ server = app.getHttpServer();
+ pluginsEnabled.value = true;
+ });
+
+ beforeEach(() => {
+ providersOf.mockReset().mockReturnValue(['trail-finder']);
+ categoryPois.mockReset().mockResolvedValue([
+ { id: 'th-1', name: 'Trailhead', lat: 47.2, lng: 11.2, details: [{ label: 'Length', value: '12 km' }] },
+ { id: 'far', name: 'Elsewhere', lat: 49, lng: 11.2 },
+ ]);
+ });
+
+ afterAll(async () => {
+ await app?.close();
+ });
+
+ const cookie = () => sessionCookie(1);
+
+ it('refuses a caller without a session before anything else', async () => {
+ await request(server).get('/api/plugin-pois').query(query).expect(401);
+ expect(categoryPois).not.toHaveBeenCalled();
+ });
+
+ it('answers the bespoke 400s of /api/maps/pois', async () => {
+ const res = await request(server).get('/api/plugin-pois').set('Cookie', cookie()).query({ ...query, category: '' }).expect(400);
+ expect(res.body).toMatchObject({ error: 'A category is required' });
+ const bbox = await request(server).get('/api/plugin-pois').set('Cookie', cookie()).query({ ...query, north: 'x' }).expect(400);
+ expect(bbox.body).toMatchObject({ error: 'A valid bbox (south, west, north, east) is required' });
+ expect(categoryPois).not.toHaveBeenCalled();
+ });
+
+ it('answers 404 for a category the manifest never declared, or a plugin that is not a provider', async () => {
+ await request(server).get('/api/plugin-pois').set('Cookie', cookie()).query({ ...query, category: 'huts' }).expect(404);
+ providersOf.mockReturnValue([]);
+ await request(server).get('/api/plugin-pois').set('Cookie', cookie()).query(query).expect(404);
+ expect(categoryPois).not.toHaveBeenCalled();
+ });
+
+ it('returns the declared category, answered by its plugin and clipped to the box', async () => {
+ const res = await request(server).get('/api/plugin-pois').set('Cookie', cookie()).query(query).expect(200);
+ expect(res.body).toMatchObject({ source: 'plugin:trail-finder', truncated: false, clamped: false });
+ expect(res.body.pois).toEqual([expect.objectContaining({
+ osm_id: 'plugin:trail-finder:th-1',
+ category: 'plugin:trail-finder/trailheads',
+ icon: 'Signpost',
+ color: '#2f855a',
+ details: [{ label: 'Length', value: '12 km' }],
+ })]);
+ expect(categoryPois).toHaveBeenCalledWith(
+ 'trail-finder',
+ { category: 'trailheads', bounds: { south: 47, west: 11, north: 47.5, east: 11.5 }, lang: 'de', limit: 60 },
+ 1,
+ );
+ });
+
+ it('turns a failing plugin into a 502 for that chip only', async () => {
+ categoryPois.mockRejectedValue(new Error('plugin invoke timed out'));
+ const res = await request(server).get('/api/plugin-pois').set('Cookie', cookie()).query(query).expect(502);
+ expect(res.body).toMatchObject({ error: 'The plugin did not answer' });
+ });
+
+ it('answers 404 while the plugin runtime is switched off', async () => {
+ pluginsEnabled.value = false;
+ try {
+ await request(server).get('/api/plugin-pois').set('Cookie', cookie()).query(query).expect(404);
+ expect(categoryPois).not.toHaveBeenCalled();
+ } finally {
+ pluginsEnabled.value = true;
+ }
+ });
+});
diff --git a/server/tests/helpers/mcp-test-controllers.ts b/server/tests/helpers/mcp-test-controllers.ts
index eca32f666..7b53d192f 100644
--- a/server/tests/helpers/mcp-test-controllers.ts
+++ b/server/tests/helpers/mcp-test-controllers.ts
@@ -109,6 +109,8 @@ import { makeStorageFixture } from './storage-fixture';
// PluginHooks.prototype to play the provider fan-out.
import { TripWarningsMcp } from '../../src/nest/plugins/contributions/trip-warnings.mcp';
import { PluginSearchMcp } from '../../src/nest/plugins/contributions/plugin-search.mcp';
+import { PluginPoisMcp } from '../../src/nest/plugins/contributions/plugin-pois.mcp';
+import { PluginPoisService } from '../../src/nest/plugins/contributions/plugin-pois.service';
import { PluginHooks } from '../../src/nest/plugins/plugin-hooks.service';
import type { PluginRuntimeService } from '../../src/nest/plugins/plugin-runtime.service';
import { AirtrailMcp } from '../../src/nest/integrations/airtrail.mcp';
@@ -255,6 +257,7 @@ export function createMcpTestRegistry(): McpRegistry {
new HelpMcp(), new AddonsMcp(addonsService),
new TripWarningsMcp(new PluginHooks({ providersOf: () => [], invokeHook: async () => [] } as unknown as PluginRuntimeService), dbService),
new PluginSearchMcp(new PluginHooks({ providersOf: () => [], invokeHook: async () => [] } as unknown as PluginRuntimeService)),
+ new PluginPoisMcp(new PluginPoisService(new PluginHooks({ providersOf: () => [], invokeHook: async () => [] } as unknown as PluginRuntimeService), dbService)),
],
{ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess },
);
diff --git a/server/tests/unit/mcp/tools-plugin-pois.test.ts b/server/tests/unit/mcp/tools-plugin-pois.test.ts
new file mode 100644
index 000000000..cebaee127
--- /dev/null
+++ b/server/tests/unit/mcp/tools-plugin-pois.test.ts
@@ -0,0 +1,162 @@
+/**
+ * The MCP half of the plugin POI categories (#1781): list_plugin_poi_categories and
+ * search_plugin_pois (src/nest/plugins/contributions/plugin-pois.mcp.ts), the
+ * counterparts of the GET /api/plugins feed and GET /api/plugin-pois. Both go through
+ * PluginPoisService, so the gate, the window and the normalization are the REST ones.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { testDb, dbMock } = vi.hoisted(() => {
+ const Database = require('better-sqlite3');
+ const db = new Database(':memory:');
+ db.exec('PRAGMA foreign_keys = ON');
+ const mock = {
+ db,
+ closeDb: () => {},
+ reinitialize: () => {},
+ getPlaceWithTags: () => null,
+ canAccessTrip: () => undefined,
+ isOwner: () => false,
+ };
+ return { testDb: db, dbMock: mock };
+});
+
+const { pluginsEnabled } = vi.hoisted(() => ({ pluginsEnabled: vi.fn(() => true) }));
+
+vi.mock('../../../src/db/database', () => dbMock);
+vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
+vi.mock('../../../src/config', () => ({
+ JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
+ ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
+ updateJwtSecret: () => {},
+}));
+vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
+
+import { runMigrations } from '../../../src/db/migrations';
+import { createTables } from '../../../src/db/schema';
+import { createUser } from '../../helpers/factories';
+import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
+import { resetTestDb } from '../../helpers/test-db';
+import { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
+
+const providersOfMock = vi.spyOn(PluginHooks.prototype, 'providersOf');
+const categoryPoisMock = vi.spyOn(PluginHooks.prototype, 'categoryPois');
+
+const trailheads = { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a' };
+const bbox = { south: 47, west: 11, north: 47.5, east: 11.5 };
+
+beforeAll(() => {
+ createTables(testDb);
+ runMigrations(testDb);
+});
+
+beforeEach(() => {
+ resetTestDb(testDb);
+ testDb.prepare('DELETE FROM plugins').run();
+ testDb
+ .prepare("INSERT INTO plugins (id, name, status, capabilities, granted_permissions) VALUES (?, ?, 'active', ?, ?)")
+ .run('trail-finder', 'Trail Finder', JSON.stringify({ poiCategories: [trailheads] }), JSON.stringify(['hook:poi-category-provider']));
+ pluginsEnabled.mockReturnValue(true);
+ providersOfMock.mockReset().mockReturnValue(['trail-finder']);
+ categoryPoisMock.mockReset().mockResolvedValue([]);
+});
+
+afterAll(() => {
+ testDb.close();
+});
+
+async function withHarness(userId: number, fn: (h: McpHarness) => Promise<void>) {
+ const h = await createMcpHarness({ userId, withResources: false, scopes: null });
+ try { await fn(h); } finally { await h.cleanup(); }
+}
+
+const search = (h: McpHarness, args: Record<string, unknown>) =>
+ h.client.callTool({ name: 'search_plugin_pois', arguments: args });
+
+describe('Tool: list_plugin_poi_categories', () => {
+ it('names the categories a provider answers, labelled in the requested language', async () => {
+ const { user } = createUser(testDb);
+ await withHarness(user.id, async (h) => {
+ const res = await h.client.callTool({ name: 'list_plugin_poi_categories', arguments: { lang: 'de' } });
+ expect(parseToolResult(res)).toEqual({
+ categories: [{
+ key: 'plugin:trail-finder/trailheads', pluginId: 'trail-finder', pluginName: 'Trail Finder',
+ id: 'trailheads', label: 'Wanderparkplätze', icon: 'Signpost', color: '#2f855a',
+ }],
+ });
+ expect(providersOfMock).toHaveBeenCalledWith('poiCategoryProvider');
+ });
+ });
+
+ it('is empty while the plugin runtime is switched off', async () => {
+ const { user } = createUser(testDb);
+ pluginsEnabled.mockReturnValue(false);
+ await withHarness(user.id, async (h) => {
+ const res = await h.client.callTool({ name: 'list_plugin_poi_categories', arguments: {} });
+ expect(parseToolResult(res)).toEqual({ categories: [] });
+ });
+ });
+});
+
+describe('Tool: search_plugin_pois', () => {
+ it('returns the plugin answer in the search_pois row shape, asked as the requesting user', async () => {
+ const { user } = createUser(testDb);
+ categoryPoisMock.mockResolvedValue([
+ { id: 'th-1', name: 'Trailhead', lat: 47.2, lng: 11.2, rating: 4.5, details: [{ label: 'Length', value: '12 km' }] },
+ { id: 'far', name: 'Elsewhere', lat: 50, lng: 11.2 },
+ ]);
+ await withHarness(user.id, async (h) => {
+ const payload = parseToolResult(await search(h, { pluginId: 'trail-finder', category: 'trailheads', bbox, lang: 'de' })) as {
+ pois: Array<Record<string, unknown>>; source: string; truncated: boolean; clamped: boolean;
+ };
+ expect(payload.source).toBe('plugin:trail-finder');
+ expect(payload.clamped).toBe(false);
+ expect(payload.pois).toHaveLength(1);
+ expect(payload.pois[0]).toMatchObject({
+ osm_id: 'plugin:trail-finder:th-1',
+ category: 'plugin:trail-finder/trailheads',
+ pluginId: 'trail-finder',
+ rating: 4.5,
+ details: [{ label: 'Length', value: '12 km' }],
+ icon: 'Signpost',
+ color: '#2f855a',
+ });
+ expect(categoryPoisMock).toHaveBeenCalledWith('trail-finder', { category: 'trailheads', bounds: bbox, lang: 'de', limit: 60 }, user.id);
+ });
+ });
+
+ it('refuses an undeclared category and an inverted box without asking the plugin', async () => {
+ const { user } = createUser(testDb);
+ await withHarness(user.id, async (h) => {
+ const unknown = await search(h, { pluginId: 'trail-finder', category: 'huts', bbox });
+ expect(unknown.isError).toBe(true);
+ expect(JSON.stringify(unknown.content)).toContain('list_plugin_poi_categories');
+ const inverted = await search(h, { pluginId: 'trail-finder', category: 'trailheads', bbox: { ...bbox, south: 48 } });
+ expect(inverted.isError).toBe(true);
+ expect(categoryPoisMock).not.toHaveBeenCalled();
+ });
+ });
+
+ it('takes the box search_pois takes and refuses an edge off the globe without asking the plugin', async () => {
+ const { user } = createUser(testDb);
+ await withHarness(user.id, async (h) => {
+ const { tools } = await h.client.listTools();
+ const bboxOf = (name: string) => tools.find((t) => t.name === name)?.inputSchema.properties?.bbox;
+ expect(bboxOf('search_plugin_pois')).toBeDefined();
+ expect(bboxOf('search_plugin_pois')).toEqual(bboxOf('search_pois'));
+ const offGlobe = await search(h, { pluginId: 'trail-finder', category: 'trailheads', bbox: { ...bbox, north: 118 } });
+ expect(offGlobe.isError).toBe(true);
+ expect(categoryPoisMock).not.toHaveBeenCalled();
+ });
+ });
+
+ it('turns a failing plugin into an error result', async () => {
+ const { user } = createUser(testDb);
+ categoryPoisMock.mockRejectedValue(new Error('timed out'));
+ await withHarness(user.id, async (h) => {
+ const res = await search(h, { pluginId: 'trail-finder', category: 'trailheads', bbox });
+ expect(res.isError).toBe(true);
+ expect(JSON.stringify(res.content)).toContain('Plugin POI search failed.');
+ });
+ });
+});
diff --git a/server/tests/unit/nest/maps.service.test.ts b/server/tests/unit/nest/maps.service.test.ts
index e5eca1d6a..a0304b68a 100644
--- a/server/tests/unit/nest/maps.service.test.ts
+++ b/server/tests/unit/nest/maps.service.test.ts
@@ -17,6 +17,8 @@ import {
buildOsmDetails,
googleFtidFromMapsUrl,
isGooglePlaceId,
+ clampPoiBbox,
+ MAX_POI_BBOX_SPAN_DEG,
buildUserAgent,
resolveOverpassEndpoints,
resolveOverpassTimeoutMs,
@@ -2425,6 +2427,34 @@ describe('isGooglePlaceId', () => {
// letters is still a Google id, because the prefix only counts before a colon.
expect(isGooglePlaceId('gersChIJLU7jZClu5kcR')).toBe(true);
});
+
+ it('MAPS-045c: rejects plugin ids, which name a plugin index and never a Google record (#2221, #1781)', () => {
+ // A place picked from a plugin search or a plugin POI category keeps
+ // plugin:<pluginId>:<id>. With a Google key configured, letting it through billed
+ // an invalid photo lookup, an editorial summary and the photo route per place.
+ expect(isGooglePlaceId('plugin:trail-finder:th-1')).toBe(false);
+ expect(isGooglePlaceId('PLUGIN:trail-finder:th-1')).toBe(false);
+ expect(isGooglePlaceId('plugin:trail-finder:th-1~p2')).toBe(false);
+ expect(isGooglePlaceId('pluginChIJLU7jZClu5kcR')).toBe(true);
+ });
+});
+
+describe('clampPoiBbox', () => {
+ it('MAPS-POIBOX-001: narrows each oversized side to a centred window and says so', () => {
+ expect(MAX_POI_BBOX_SPAN_DEG).toBe(0.5);
+ expect(clampPoiBbox({ south: 48, west: 11, north: 48.25, east: 11.25 })).toEqual({
+ bbox: { south: 48, west: 11, north: 48.25, east: 11.25 },
+ clamped: false,
+ });
+ expect(clampPoiBbox({ south: 40, west: 11, north: 50, east: 11.25 })).toEqual({
+ bbox: { south: 44.75, west: 11, north: 45.25, east: 11.25 },
+ clamped: true,
+ });
+ expect(clampPoiBbox({ south: 48, west: 0, north: 48.25, east: 20 })).toEqual({
+ bbox: { south: 48, west: 9.75, north: 48.25, east: 10.25 },
+ clamped: true,
+ });
+ });
});
describe('googleFtidFromMapsUrl', () => {
diff --git a/server/tests/unit/plugins/manifest.test.ts b/server/tests/unit/plugins/manifest.test.ts
index 2880fca44..3c7b8eeb0 100644
--- a/server/tests/unit/plugins/manifest.test.ts
+++ b/server/tests/unit/plugins/manifest.test.ts
@@ -143,6 +143,59 @@ describe('parseManifest capabilities', () => {
expect(() => parseManifest({ ...base, capabilities: { routeProfiles: 'ev' } })).toThrow(ManifestError);
});
+ describe('poiCategories (#1781)', () => {
+ const cat = { id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2F855A' };
+ const parse = (poiCategories: unknown) => parseManifest({ ...base, capabilities: { poiCategories } });
+
+ it('parses a category, lowercasing the colour and keeping known languages only', () => {
+ const m = parse([{ ...cat, label: ' Trailheads ', labels: { de: 'Wanderparkplätze', 'pt-PT': 'Não' } }]);
+ expect(m.capabilities.poiCategories).toEqual([
+ { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a' },
+ ]);
+ });
+
+ it('installs without the hook grant, like routeProfiles (the feed gates the chips on it)', () => {
+ expect(parse([cat]).permissions).toEqual([]);
+ expect(parse([cat]).capabilities.poiCategories).toHaveLength(1);
+ });
+
+ it('strips emoji and control characters from labels and falls back to the id', () => {
+ const m = parse([{ ...cat, label: 'Water\u0007 \u{1F6B0} taps', labels: { de: '\u{1F6BB}' } }, { ...cat, id: 'wc', label: '\u{1F6BB}' }]);
+ expect(m.capabilities.poiCategories?.[0]).toEqual({ id: 'trailheads', label: 'Water taps', icon: 'Signpost', color: '#2f855a' });
+ expect(m.capabilities.poiCategories?.[1].label).toBe('wc');
+ });
+
+ it('refuses every malformed declaration with a manifest error', () => {
+ const bad: unknown[] = [
+ 'trailheads',
+ [1],
+ [{ ...cat, id: 'Trail' }],
+ [{ ...cat, label: '' }],
+ [{ ...cat, label: 'L'.repeat(41) }],
+ [{ ...cat, icon: 'Toilet' }],
+ [{ ...cat, icon: undefined }],
+ [{ ...cat, color: 'green' }],
+ [{ ...cat, color: '#2f855a;background:url(https://x)' }],
+ [{ ...cat, labels: ['de'] }],
+ [{ ...cat, labels: null }],
+ [{ ...cat, labels: { __proto__x: 'x' } }],
+ [{ ...cat, labels: { de: '' } }],
+ [cat, cat],
+ [1, 2, 3, 4, 5].map((i) => ({ ...cat, id: `c${i}` })),
+ ];
+ for (const poiCategories of bad) expect(() => parse(poiCategories), JSON.stringify(poiCategories)).toThrow(ManifestError);
+ });
+
+ it('names the rule that failed', () => {
+ expect(() => parse([{ ...cat, color: 'green' }])).toThrow('capabilities.poiCategories: "trailheads" color must be a #rrggbb hex colour');
+ expect(() => parse([cat, cat])).toThrow('capabilities.poiCategories: duplicate id "trailheads"');
+ });
+
+ it('omits an empty declaration', () => {
+ expect(parse([]).capabilities.poiCategories).toBeUndefined();
+ });
+ });
+
it('parses mcpTools, bounding the text and normalising the schema', () => {
const perms = { permissions: ['mcp:tools'] };
const m = parseManifest({
diff --git a/server/tests/unit/plugins/plugin-hooks.test.ts b/server/tests/unit/plugins/plugin-hooks.test.ts
index 16cb67058..4f36f0146 100644
--- a/server/tests/unit/plugins/plugin-hooks.test.ts
+++ b/server/tests/unit/plugins/plugin-hooks.test.ts
@@ -1,7 +1,7 @@
/**
* The host-to-plugin hook contracts.
*
- * The 15 hooks used to be invoked straight from the controllers, with the fn name and
+ * The hooks used to be invoked straight from the controllers, with the fn name and
* the timeout spelled out at each call site. Nothing checked that a `hook:*` grant on
* the consent screen had a consumer behind it, that the fn name matched what the SDK
* documents, or that two call sites for the same hook agreed on the budget.
@@ -33,6 +33,7 @@ const CONTRACTS: Array<[hook: string, fn: string, timeoutMs: number]> = [
['calendarSource', 'getEvents', 5000],
['placeDetailProvider', 'getDetails', 5000],
['searchProvider', 'search', 2000],
+ ['poiCategoryProvider', 'getPois', 8000],
['warningProvider', 'getWarnings', 5000],
['tableContributor', 'getContributions', 5000],
['mapMarkerProvider', 'getMarkers', 5000],
@@ -149,6 +150,16 @@ describe('PluginHooks contracts', () => {
expect(invokeHook).toHaveBeenCalledWith('p', 'mcpToolProvider', 'callTool', [call], 7, 15_000);
});
+ it('PLUGHOOK-011: a POI category search binds the requesting user and takes the explore budget', async () => {
+ // Runs as the user who picked the chip, so a provider can read that user's own
+ // settings (a wheelchair profile), and gets 8s: long enough for an external index,
+ // short enough that the chip shows its error instead of spinning.
+ const { hooks: h, invokeHook } = hooks();
+ const request = { category: 'trailheads', bounds: { south: 47, west: 11, north: 47.5, east: 11.5 }, lang: 'de', limit: 60 };
+ await h.categoryPois('p', request, 7);
+ expect(invokeHook).toHaveBeenCalledWith('p', 'poiCategoryProvider', 'getPois', [request], 7, 8000);
+ });
+
it('PLUGHOOK-009 the class is listed in its module providers', () => {
// A decorated class no module registers is invisible to discovery, which would
// now fail boot on "no host-side consumer" rather than fail quietly. Cheapest
diff --git a/server/tests/unit/plugins/plugin-pois.test.ts b/server/tests/unit/plugins/plugin-pois.test.ts
new file mode 100644
index 000000000..c003dbcef
--- /dev/null
+++ b/server/tests/unit/plugins/plugin-pois.test.ts
@@ -0,0 +1,276 @@
+/**
+ * Plugin POI categories (#1781): GET /api/plugin-pois, the service behind it and the
+ * normalizer both it and the MCP tools use.
+ *
+ * The route is targeted like the plugin routes: exactly the plugin that declared the
+ * chip is asked, only for an id its manifest declared, and only while it is a
+ * provider. What comes back is capped, clipped to the box the plugin was asked about,
+ * namespaced, and styled by the HOST's copy of the declaration, never the plugin's
+ * answer, because the colour and icon end up inside marker markup.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import Database from 'better-sqlite3';
+import { HttpException } from '@nestjs/common';
+
+const { pluginsEnabled } = vi.hoisted(() => ({ pluginsEnabled: vi.fn(() => true) }));
+vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled }));
+
+import { DatabaseService } from '../../../src/nest/database/database.service';
+import type { PluginHooks } from '../../../src/nest/plugins/plugin-hooks.service';
+import { PluginPoisService } from '../../../src/nest/plugins/contributions/plugin-pois.service';
+import { PluginPoisController, parsePluginPoiQuery } from '../../../src/nest/plugins/contributions/plugin-pois.controller';
+import {
+ normalizePluginPois,
+ normalizePoiDetails,
+ pluginPoiWindow,
+} from '../../../src/nest/plugins/contributions/plugin-pois.helpers';
+import type { PluginPoiCategory } from '@trek/shared';
+import type { User } from '../../../src/types';
+
+const trailheads: PluginPoiCategory = { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a' };
+const bounds = { south: 47, west: 11, north: 47.5, east: 11.5 };
+const hit = (over: Record<string, unknown> = {}) => ({ id: 'th-1', name: 'Trailhead', lat: 47.2, lng: 11.2, ...over });
+
+function makeDb(): DatabaseService {
+ const conn = new Database(':memory:');
+ conn.exec("CREATE TABLE plugins (id TEXT PRIMARY KEY, name TEXT, status TEXT, sort_order INTEGER DEFAULT 0, capabilities TEXT)");
+ const insert = conn.prepare('INSERT INTO plugins (id, name, status, sort_order, capabilities) VALUES (?, ?, ?, ?, ?)');
+ insert.run('trail-finder', 'Trail Finder', 'active', 1, JSON.stringify({ poiCategories: [trailheads, { ...trailheads, id: 'huts', label: 'Huts', labels: undefined, icon: 'Tent' }] }));
+ insert.run('water-map', 'Water Map', 'active', 0, JSON.stringify({ poiCategories: [{ id: 'taps', label: 'Taps', icon: 'Droplet', color: '#2b6cb0' }] }));
+ insert.run('quiet', 'Quiet', 'active', 2, JSON.stringify({ poiCategories: [{ id: 'benches', label: 'Benches', icon: 'Info', color: '#000000' }] }));
+ return new DatabaseService(conn);
+}
+
+function makeService(answer: () => unknown, providers = ['trail-finder', 'water-map'], db = makeDb()) {
+ const hooks = {
+ providersOf: vi.fn(() => providers),
+ categoryPois: vi.fn(async () => answer()),
+ } as unknown as PluginHooks & { providersOf: ReturnType<typeof vi.fn>; categoryPois: ReturnType<typeof vi.fn> };
+ return { service: new PluginPoisService(hooks, db), hooks };
+}
+
+beforeEach(() => pluginsEnabled.mockReturnValue(true));
+
+describe('pluginPoiWindow', () => {
+ it('PLUGPOI-001: passes a small box through untouched', () => {
+ expect(pluginPoiWindow(bounds)).toEqual({ bounds, clamped: false });
+ });
+
+ it('PLUGPOI-002: narrows a large box to the centred 0.5 degree window the Overpass path uses', () => {
+ const { bounds: b, clamped } = pluginPoiWindow({ south: 40, west: 0, north: 50, east: 20 });
+ expect(clamped).toBe(true);
+ expect(b).toEqual({ south: 44.75, west: 9.75, north: 45.25, east: 10.25 });
+ });
+
+ it('PLUGPOI-003: folds a window panned past the antimeridian back onto the globe', () => {
+ expect(pluginPoiWindow({ south: 10, west: 190, north: 10.25, east: 190.25 })).toEqual({
+ bounds: { south: 10, west: -170, north: 10.25, east: -169.75 },
+ clamped: false,
+ });
+ // Straddling the line: the window is folded by its centre and the far side is cut.
+ expect(pluginPoiWindow({ south: 10, west: 179.875, north: 10.25, east: 180.375 })).toEqual({
+ bounds: { south: 10, west: -180, north: 10.25, east: -179.625 },
+ clamped: true,
+ });
+ });
+});
+
+describe('normalizePoiDetails', () => {
+ it('PLUGPOI-004: keeps six one-line rows, capped, and drops the unreadable ones', () => {
+ const rows = normalizePoiDetails([
+ { label: 'Length', value: 12.5 },
+ { label: 'Step-free', value: true },
+ { label: 'Surface\nnote', value: 'Gravel \u{1F97E}' },
+ { label: '', value: 'x' },
+ { label: 'Object', value: { km: 3 } },
+ { label: 'Infinite', value: Number.POSITIVE_INFINITY },
+ null,
+ { label: 'L'.repeat(60), value: 'V'.repeat(200) },
+ { label: 'Five', value: '5' },
+ { label: 'Six', value: '6' },
+ { label: 'Seven', value: '7' },
+ ]);
+ expect(rows).toEqual([
+ { label: 'Length', value: '12.5' },
+ { label: 'Step-free', value: 'true' },
+ { label: 'Surface note', value: 'Gravel' },
+ { label: 'L'.repeat(40), value: 'V'.repeat(120) },
+ { label: 'Five', value: '5' },
+ { label: 'Six', value: '6' },
+ ]);
+ expect(normalizePoiDetails('many')).toEqual([]);
+ });
+});
+
+describe('normalizePluginPois', () => {
+ it('PLUGPOI-005: builds a /api/maps/pois row styled by the declaration', () => {
+ const { pois, truncated } = normalizePluginPois('trail-finder', trailheads, bounds, [
+ hit({ address: 'Hauptstraße 1', website: 'trails.example/th-1', phone: '+43 1', rating: 4.44, details: [{ label: 'Length', value: '12 km' }], category: 'restaurant', color: '#ff0000', icon: 'Skull' }),
+ ]);
+ expect(truncated).toBe(false);
+ expect(pois).toEqual([{
+ osm_id: 'plugin:trail-finder:th-1',
+ name: 'Trailhead',
+ lat: 47.2,
+ lng: 11.2,
+ category: 'plugin:trail-finder/trailheads',
+ poi_type: 'plugin:trail-finder/trailheads',
+ address: 'Hauptstraße 1',
+ website: 'https://trails.example/th-1',
+ phone: '+43 1',
+ opening_hours: null,
+ cuisine: null,
+ brand: null,
+ brand_wikidata: null,
+ charging: null,
+ source: 'plugin:trail-finder',
+ pluginId: 'trail-finder',
+ rating: 4.4,
+ details: [{ label: 'Length', value: '12 km' }],
+ icon: 'Signpost',
+ color: '#2f855a',
+ }]);
+ });
+
+ it('PLUGPOI-006: drops places outside the box, malformed ones and repeats; an absent rating is null', () => {
+ const { pois } = normalizePluginPois('trail-finder', trailheads, bounds, [
+ hit(),
+ hit({ name: 'Again' }),
+ hit({ id: 'far', lat: 48 }),
+ hit({ id: 'nameless', name: '' }),
+ hit({ id: 'nowhere', lat: 'x' }),
+ hit({ id: 'js', website: 'javascript:alert(1)', rating: null, address: '' }),
+ 'nope',
+ ]);
+ expect(pois.map((p) => p.osm_id)).toEqual(['plugin:trail-finder:th-1', 'plugin:trail-finder:js']);
+ expect(pois[1]).toMatchObject({ website: null, rating: null, address: null, details: [] });
+ });
+
+ it('PLUGPOI-007: keeps sixty and says it cut, and never walks more than it would keep four times over', () => {
+ const many = (n: number) => Array.from({ length: n }, (_, i) => hit({ id: `p${i}`, lat: 47 + (i % 400) / 1000 }));
+ const capped = normalizePluginPois('trail-finder', trailheads, bounds, many(61));
+ expect(capped.pois).toHaveLength(60);
+ expect(capped.truncated).toBe(true);
+ expect(normalizePluginPois('trail-finder', trailheads, bounds, many(60)).truncated).toBe(false);
+ // 240 rows outside the box, then one inside: past the walk budget, so never seen.
+ const flood = [...Array.from({ length: 240 }, (_, i) => hit({ id: `out${i}`, lat: 10 })), hit({ id: 'late' })];
+ expect(normalizePluginPois('trail-finder', trailheads, bounds, flood)).toEqual({ pois: [], truncated: true });
+ });
+});
+
+describe('PluginPoisService', () => {
+ it('PLUGPOI-008: asks exactly the declaring plugin, as the user, with the host window', async () => {
+ const { service, hooks } = makeService(() => [hit()]);
+ const outcome = await service.search({ pluginId: 'trail-finder', category: 'trailheads', bbox: { south: 40, west: 0, north: 50, east: 20 }, lang: 'de' }, 7);
+ expect(hooks.categoryPois).toHaveBeenCalledWith(
+ 'trail-finder',
+ { category: 'trailheads', bounds: { south: 44.75, west: 9.75, north: 45.25, east: 10.25 }, lang: 'de', limit: 60 },
+ 7,
+ );
+ // The hit sits outside the narrowed window, so the answer is empty but clamped.
+ expect(outcome).toEqual({ ok: true, result: { pois: [], source: 'plugin:trail-finder', truncated: false, clamped: true } });
+ });
+
+ it('PLUGPOI-009: omits lang when the caller has none', async () => {
+ const { service, hooks } = makeService(() => [hit()]);
+ const outcome = await service.search({ pluginId: 'trail-finder', category: 'trailheads', bbox: bounds }, 7);
+ expect(hooks.categoryPois.mock.calls[0][1]).toEqual({ category: 'trailheads', bounds, limit: 60 });
+ expect(outcome.ok && outcome.result.pois).toHaveLength(1);
+ });
+
+ it('PLUGPOI-010: answers 404 for anything that is not a live declaration, without asking', async () => {
+ const cases: Array<[string, string]> = [
+ ['trail-finder', 'water'], // not declared
+ ['quiet', 'benches'], // declared, but not a provider
+ ['nobody', 'trailheads'], // no such plugin
+ ];
+ for (const [pluginId, category] of cases) {
+ const { service, hooks } = makeService(() => [hit()], ['trail-finder', 'quiet-not']);
+ expect(await service.search({ pluginId, category, bbox: bounds }, 7)).toEqual({ ok: false, status: 404, error: 'Unknown POI category' });
+ expect(hooks.categoryPois).not.toHaveBeenCalled();
+ }
+ pluginsEnabled.mockReturnValue(false);
+ const { service, hooks } = makeService(() => [hit()]);
+ expect((await service.search({ pluginId: 'trail-finder', category: 'trailheads', bbox: bounds }, 7)).ok).toBe(false);
+ expect(hooks.providersOf).not.toHaveBeenCalled();
+ });
+
+ it('PLUGPOI-011: turns a slow, failing or malformed plugin into a quick 502', async () => {
+ const throwing = makeService(() => { throw new Error('plugin invoke timed out'); });
+ expect(await throwing.service.search({ pluginId: 'trail-finder', category: 'trailheads', bbox: bounds }, 7))
+ .toEqual({ ok: false, status: 502, error: 'The plugin did not answer' });
+ const malformed = makeService(() => ({ pois: [hit()] }));
+ expect(await malformed.service.search({ pluginId: 'trail-finder', category: 'trailheads', bbox: bounds }, 7))
+ .toEqual({ ok: false, status: 502, error: 'The plugin sent an invalid answer' });
+ });
+
+ it('PLUGPOI-012: lists the live categories in feed order with the label for the language', () => {
+ const { service } = makeService(() => []);
+ expect(service.available('de')).toEqual([
+ { key: 'plugin:water-map/taps', pluginId: 'water-map', pluginName: 'Water Map', id: 'taps', label: 'Taps', icon: 'Droplet', color: '#2b6cb0' },
+ { key: 'plugin:trail-finder/trailheads', pluginId: 'trail-finder', pluginName: 'Trail Finder', id: 'trailheads', label: 'Wanderparkplätze', icon: 'Signpost', color: '#2f855a' },
+ { key: 'plugin:trail-finder/huts', pluginId: 'trail-finder', pluginName: 'Trail Finder', id: 'huts', label: 'Huts', icon: 'Tent', color: '#2f855a' },
+ ]);
+ expect(service.available().find((c) => c.id === 'trailheads')?.label).toBe('Trailheads');
+ expect(makeService(() => [], []).service.available()).toEqual([]);
+ pluginsEnabled.mockReturnValue(false);
+ expect(service.available()).toEqual([]);
+ });
+
+ it('PLUGPOI-016: flattens and caps the plugin name an assistant reads, and falls back to the id', () => {
+ const db = makeDb();
+ db.run('UPDATE plugins SET name = ? WHERE id = ?', `Trails\u202E\n\n## System ${'x'.repeat(4000)}`, 'trail-finder');
+ db.run('UPDATE plugins SET name = ? WHERE id = ?', '\u0007\u2028\u2066', 'water-map');
+ const names = makeService(() => [], undefined, db).service.available().map((c) => [c.id, c.pluginName]);
+ const trails = names.find(([id]) => id === 'trailheads')?.[1] ?? '';
+ expect(trails.startsWith('Trails ## System xxx')).toBe(true);
+ expect(trails).toHaveLength(80);
+ expect(trails).not.toMatch(/[\n\u202E]/);
+ expect(names.find(([id]) => id === 'huts')?.[1]).toBe(trails);
+ expect(names.find(([id]) => id === 'taps')?.[1]).toBe('water-map');
+ });
+});
+
+describe('GET /api/plugin-pois', () => {
+ const query = { pluginId: 'trail-finder', category: 'trailheads', south: '47', west: '11', north: '47.5', east: '11.5' };
+ const status = (fn: () => unknown): [number, unknown] => {
+ try {
+ fn();
+ } catch (e) {
+ const err = e as HttpException;
+ return [err.getStatus(), err.getResponse()];
+ }
+ return [200, null];
+ };
+
+ it('PLUGPOI-013: answers the bespoke 400s of /api/maps/pois', () => {
+ expect(status(() => parsePluginPoiQuery({ ...query, category: undefined }))).toEqual([400, { error: 'A category is required' }]);
+ expect(status(() => parsePluginPoiQuery({ ...query, category: ' ' }))).toEqual([400, { error: 'A category is required' }]);
+ expect(status(() => parsePluginPoiQuery({ ...query, pluginId: '' }))).toEqual([400, { error: 'A plugin is required' }]);
+ for (const over of [{ south: undefined }, { east: 'abc' }, { south: '48' }, { north: '95' }]) {
+ expect(status(() => parsePluginPoiQuery({ ...query, ...over }))).toEqual([400, { error: 'A valid bbox (south, west, north, east) is required' }]);
+ }
+ // A bad box wins over a bad id: the request is malformed before it is unknown.
+ expect(status(() => parsePluginPoiQuery({ ...query, pluginId: '../x', west: 'x' }))[0]).toBe(400);
+ expect(status(() => parsePluginPoiQuery({ ...query, lang: 'x'.repeat(36) }))).toEqual([400, { error: 'lang must be at most 35 characters' }]);
+ });
+
+ it('PLUGPOI-014: answers 404 for an id no manifest can have declared', () => {
+ for (const over of [{ pluginId: '../etc' }, { category: 'Trail Heads' }, { category: ['a', 'b'] }]) {
+ expect(status(() => parsePluginPoiQuery({ ...query, ...over }))).toEqual([404, { error: 'Unknown POI category' }]);
+ }
+ });
+
+ it('PLUGPOI-015: hands the parsed query to the service and maps its outcome', async () => {
+ const { service, hooks } = makeService(() => [hit()]);
+ const controller = new PluginPoisController(service);
+ const user = { id: 5 } as User;
+ const res = await controller.list({ ...query, lang: 'de' }, user);
+ expect(res.pois.map((p) => p.osm_id)).toEqual(['plugin:trail-finder:th-1']);
+ expect(hooks.categoryPois).toHaveBeenCalledWith('trail-finder', expect.objectContaining({ lang: 'de' }), 5);
+
+ await expect(controller.list({ ...query, category: 'water' }, user)).rejects.toMatchObject({ status: 404 });
+ const failing = new PluginPoisController(makeService(() => { throw new Error('boom'); }).service);
+ await expect(failing.list(query, user)).rejects.toMatchObject({ status: 502, response: { error: 'The plugin did not answer' } });
+ });
+});
diff --git a/server/tests/unit/plugins/plugin-search.controller.test.ts b/server/tests/unit/plugins/plugin-search.controller.test.ts
index 0fbb1edb5..68356e61a 100644
--- a/server/tests/unit/plugins/plugin-search.controller.test.ts
+++ b/server/tests/unit/plugins/plugin-search.controller.test.ts
@@ -152,6 +152,19 @@ describe('PluginSearchController', () => {
expect(places[2].rating).toBeNull();
});
+ it('reads an explicit null, a blank or a boolean rating as unrated, not as zero stars', async () => {
+ const { c } = controller({
+ searchPlaces: vi.fn(async () => [
+ hit({ id: 'n', rating: null }),
+ hit({ id: 'b', rating: ' ' }),
+ hit({ id: 't', rating: true }),
+ hit({ id: 's', rating: '4.25' }),
+ ]) as unknown as PluginHooks['searchPlaces'],
+ });
+ const { places } = await c.search('milan', undefined, undefined, undefined, undefined, req(5));
+ expect(places.map(p => p.rating)).toEqual([null, null, null, 4.3]);
+ });
+
// #2483: a plugin index is one more source of websites typed without a scheme.
it('PLUGIN-SEARCH-2483-01: a website without a scheme gains https like one from the core search', async () => {
const { c } = controller({
diff --git a/server/tests/unit/plugins/plugins-feed.controller.test.ts b/server/tests/unit/plugins/plugins-feed.controller.test.ts
index c6d17f4a6..fcbf6139b 100644
--- a/server/tests/unit/plugins/plugins-feed.controller.test.ts
+++ b/server/tests/unit/plugins/plugins-feed.controller.test.ts
@@ -63,6 +63,46 @@ describe('PluginsFeedController', () => {
expect(profiles.every(p => p.label.length <= 40)).toBe(true);
});
+ describe('poiCategories (#1781)', () => {
+ const cat = { id: 'trailheads', label: 'Trailheads', labels: { de: 'Wanderparkplätze' }, icon: 'Signpost', color: '#2f855a' };
+ const granted = JSON.stringify(['hook:poi-category-provider']);
+
+ it('serves them only alongside the recorded hook:poi-category-provider grant', () => {
+ rows.value = [
+ row({ id: 'granted', capabilities: JSON.stringify({ poiCategories: [cat] }), granted_permissions: granted }),
+ row({ id: 'ungranted', capabilities: JSON.stringify({ poiCategories: [cat] }) }),
+ row({ id: 'searchOnly', capabilities: JSON.stringify({ poiCategories: [cat] }), granted_permissions: JSON.stringify(['hook:search-provider']) }),
+ ];
+ const { plugins } = c.list();
+ expect(plugins.find(p => p.id === 'granted')?.poiCategories).toEqual([cat]);
+ expect(plugins.find(p => p.id === 'ungranted')?.poiCategories).toBeUndefined();
+ expect(plugins.find(p => p.id === 'searchOnly')?.poiCategories).toBeUndefined();
+ });
+
+ it('re-validates a hand-edited row: bad colour, icon or id dropped, duplicates and the fifth one gone', () => {
+ rows.value = [row({
+ capabilities: JSON.stringify({
+ poiCategories: [
+ { ...cat, color: '#fff;background:url(https://tracker.example)' },
+ { ...cat, id: 'x', icon: 'Skull' },
+ { ...cat, id: '../x' },
+ { ...cat, id: 'ok', label: 'Water \u{1F6B0}' },
+ { ...cat, id: 'ok' },
+ { ...cat, id: 'late' },
+ ],
+ }),
+ granted_permissions: granted,
+ })];
+ // The first four entries are the ones read (the cap), and only one of them survives.
+ expect(c.list().plugins[0].poiCategories).toEqual([{ ...cat, id: 'ok', label: 'Water' }]);
+ });
+
+ it('omits the field when nothing survives', () => {
+ rows.value = [row({ capabilities: JSON.stringify({ poiCategories: [{ ...cat, color: 'red' }] }), granted_permissions: granted })];
+ expect(c.list().plugins[0]).not.toHaveProperty('poiCategories');
+ });
+ });
+
it('flags geolocation only when the grant is recorded', () => {
rows.value = [
row({ id: 'granted', granted_permissions: JSON.stringify(['geolocation:read']) }),
diff --git a/server/tests/unit/plugins/poi-categories.test.ts b/server/tests/unit/plugins/poi-categories.test.ts
new file mode 100644
index 000000000..36f820e66
--- /dev/null
+++ b/server/tests/unit/plugins/poi-categories.test.ts
@@ -0,0 +1,56 @@
+/**
+ * The one reader of `capabilities.poiCategories` (#1781). The manifest parser, the
+ * feed and the plugin-pois route all go through it, so these pin the rules once:
+ * what refuses an entry, what is cleaned rather than refused, and that the lenient
+ * readers skip exactly what the install would refuse.
+ */
+import { describe, it, expect } from 'vitest';
+import { poiCategoriesFrom, poiCategoriesOf, readPoiCategory } from '../../../src/nest/plugins/poi-categories';
+
+const cat = { id: 'water', label: 'Drinking water', icon: 'Droplet', color: '#2B6CB0' };
+
+describe('readPoiCategory', () => {
+ it('POICAT-001: reads a declaration into the feed shape', () => {
+ expect(readPoiCategory({ ...cat, labels: { fr: 'Eau potable', 'zh-TW': '飲用水' } })).toEqual({
+ ok: true,
+ value: { id: 'water', label: 'Drinking water', labels: { fr: 'Eau potable', 'zh-TW': '飲用水' }, icon: 'Droplet', color: '#2b6cb0' },
+ });
+ });
+
+ it('POICAT-002: drops a well-formed language TREK does not ship, and a label that cleans to nothing', () => {
+ const read = readPoiCategory({ ...cat, labels: { fi: 'Juomavesi', de: '\u{1F6B0}' } });
+ expect(read).toEqual({ ok: true, value: { id: 'water', label: 'Drinking water', icon: 'Droplet', color: '#2b6cb0' } });
+ });
+
+ it('POICAT-003: flattens a label to one line', () => {
+ const read = readPoiCategory({ ...cat, label: 'Drinking\n\u202Ewater' });
+ expect(read.ok && read.value.label).toBe('Drinking water');
+ });
+
+ it('POICAT-004: gives the reason for a refusal', () => {
+ expect(readPoiCategory(null)).toEqual({ ok: false, reason: 'entries must be objects' });
+ expect(readPoiCategory([cat])).toEqual({ ok: false, reason: 'entries must be objects' });
+ expect(readPoiCategory({ ...cat, id: 7 })).toEqual({ ok: false, reason: 'id must be lowercase [a-z][a-z0-9-], max 24 chars' });
+ expect(readPoiCategory({ ...cat, label: 42 })).toEqual({ ok: false, reason: '"water" label is required (max 40 chars)' });
+ expect(readPoiCategory({ ...cat, icon: 'droplet' })).toMatchObject({ ok: false, reason: expect.stringContaining('"water" icon must be one of Footprints') });
+ expect(readPoiCategory({ ...cat, color: 12 })).toEqual({ ok: false, reason: '"water" color must be a #rrggbb hex colour' });
+ expect(readPoiCategory({ ...cat, labels: { 'de-de': 'x' } })).toEqual({ ok: false, reason: '"water" labels: "de-de" is not a language code' });
+ expect(readPoiCategory({ ...cat, labels: { de: 'L'.repeat(41) } })).toEqual({ ok: false, reason: '"water" labels.de is required (max 40 chars)' });
+ expect(readPoiCategory({ ...cat, labels: 'de' })).toEqual({ ok: false, reason: '"water" labels must be an object of language code to label' });
+ });
+});
+
+describe('poiCategoriesFrom / poiCategoriesOf', () => {
+ it('POICAT-005: skips refused entries and repeated ids, and reads at most four', () => {
+ const list = [{ ...cat, color: 'blue' }, cat, { ...cat, label: 'Again' }, { ...cat, id: 'wc', icon: 'Bath' }, { ...cat, id: 'late' }];
+ expect(poiCategoriesFrom(list).map((c) => c.id)).toEqual(['water', 'wc']);
+ expect(poiCategoriesFrom('water')).toEqual([]);
+ });
+
+ it('POICAT-006: reads a capabilities column and survives a broken one', () => {
+ expect(poiCategoriesOf(JSON.stringify({ poiCategories: [cat] }))).toHaveLength(1);
+ expect(poiCategoriesOf('{broken')).toEqual([]);
+ expect(poiCategoriesOf(null)).toEqual([]);
+ expect(poiCategoriesOf('null')).toEqual([]);
+ });
+});
diff --git a/server/tests/unit/plugins/provider-hook-grant.test.ts b/server/tests/unit/plugins/provider-hook-grant.test.ts
index 404ed8731..d3787e773 100644
--- a/server/tests/unit/plugins/provider-hook-grant.test.ts
+++ b/server/tests/unit/plugins/provider-hook-grant.test.ts
@@ -67,6 +67,14 @@ describe('providersOf enforces the hook:* grant', () => {
expect(s.providersOf('routeProvider')).toEqual(['ev']);
});
+ it('maps poiCategoryProvider to hook:poi-category-provider (not the search grant)', () => {
+ const s = makeSupervisor();
+ put(s, 'trails', 'active', ['poiCategoryProvider'], ['hook:poi-category-provider']);
+ // A search provider only sees words the user typed; the viewport is its own consent.
+ put(s, 'searchOnly', 'active', ['poiCategoryProvider'], ['hook:search-provider']);
+ expect(s.providersOf('poiCategoryProvider')).toEqual(['trails']);
+ });
+
it('maps dayScheduleProvider to hook:day-schedule-provider', () => {
const s = makeSupervisor();
put(s, 'times', 'active', ['dayScheduleProvider'], ['hook:day-schedule-provider']);
diff --git a/server/tests/unit/plugins/registry-preview.test.ts b/server/tests/unit/plugins/registry-preview.test.ts
index e63400e8a..cf56afbe6 100644
--- a/server/tests/unit/plugins/registry-preview.test.ts
+++ b/server/tests/unit/plugins/registry-preview.test.ts
@@ -69,5 +69,21 @@ describe('previewManifest', () => {
it('MCPPREV-005: omits the key entirely when nothing is declared', () => {
const none = { ...base, capabilities: { widget: { slot: 'hero' } } };
expect(previewManifest(none).capabilities.mcpTools).toBeUndefined();
+ expect(previewManifest(none).capabilities.poiCategories).toBeUndefined();
+ });
+
+ it('POICATPREV-001: shows the explore-pill categories before install, through the feed reader (#1781)', () => {
+ const trails = {
+ ...base,
+ capabilities: {
+ poiCategories: [
+ { id: 'trailheads', label: 'Trailheads \u{1F97E}', icon: 'Signpost', color: '#2F855A' },
+ { id: 'bad', label: 'Bad', icon: 'Signpost', color: 'url(https://x)' },
+ ],
+ },
+ };
+ expect(previewManifest(trails).capabilities.poiCategories).toEqual([
+ { id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' },
+ ]);
});
});
diff --git a/shared/src/i18n/ar/admin.ts b/shared/src/i18n/ar/admin.ts
index ed4d8b24e..47fdf2043 100644
--- a/shared/src/i18n/ar/admin.ts
+++ b/shared/src/i18n/ar/admin.ts
@@ -396,6 +396,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:calendar-source': 'توفير الأحداث للتقويم',
'admin.plugins.perm.hook:place-detail-provider': 'المساهمة بتفاصيل إضافية (مراجعات، تقييمات، روابط) لمكان ما',
'admin.plugins.perm.hook:search-provider': 'الإجابة على عمليات البحث عن الأماكن من فهرس خاص به، إلى جانب نتائج TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'إضافة فئات أماكن خاصة بها إلى «استكشاف الأماكن على الخريطة»؛ وعند اختيار إحداها تتلقى الإضافة منطقة الخريطة التي تعرضها',
'admin.plugins.perm.hook:trip-warning-provider': 'إظهار تحذيرات التحقق على الرحلة (تظهر في المخطط)',
'admin.plugins.perm.hook:table-contributor': 'إضافة أعمدة وإجراءات إلى عروض الرحلة (الحجوزات، الأماكن، الأيام)',
'admin.plugins.perm.hook:map-marker-provider': 'إضافة علامات إلى خريطة الرحلة (مثل عرض الحجوزات أو نقاط الاهتمام)',
@@ -408,6 +410,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'ينشر أدوات ذكاء اصطناعي',
'admin.plugins.mcpToolsTitle': 'أدوات الذكاء الاصطناعي المنشورة',
'admin.plugins.mcpToolsHint': 'يمكن لمساعد ذكي تشغيلها نيابة عن المستخدم. وتعمل كل أداة بالصلاحيات الممنوحة أعلاه.',
+ 'admin.plugins.poiCategoriesTitle': 'فئات الخريطة التي يضيفها',
'admin.plugins.perm.mcp:tools':
'نشر أدوات يمكن لمساعد ذكاء اصطناعي تشغيلها نيابة عنك (يعمل بالصلاحيات التي تمنحها للإضافة هنا، وليس بصلاحياته هو)',
'admin.plugins.perm.geolocation:read':
@@ -548,6 +551,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'يوفّر أحداث التقويم',
'admin.plugins.cap.placeDetails': 'يُثري الأماكن',
'admin.plugins.cap.search': 'يجيب على عمليات البحث',
+ 'admin.plugins.cap.poiCategories': 'يضيف فئات إلى الخريطة',
'admin.plugins.cap.warnings': 'يرصد المشكلات',
'admin.plugins.cap.mapLayers': 'يرسم على الخريطة',
'admin.plugins.cap.routing': 'يوفّر التوجيه',
diff --git a/shared/src/i18n/ar/map.ts b/shared/src/i18n/ar/map.ts
index a1f4ca267..0cc93aeed 100644
--- a/shared/src/i18n/ar/map.ts
+++ b/shared/src/i18n/ar/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'متاحف وثقافة',
'poi.cat.nature': 'طبيعة وحدائق',
'poi.cat.activities': 'أنشطة',
+ 'poi.pluginCategories': 'فئات من الإضافات الخارجية',
'map.showAllConnections': 'إظهار جميع مسارات الحجوزات',
'map.hideAllConnections': 'إخفاء جميع مسارات الحجوزات',
'map.baseLayer.default': 'خريطة',
diff --git a/shared/src/i18n/az/admin.ts b/shared/src/i18n/az/admin.ts
index c8317497a..d022a4561 100644
--- a/shared/src/i18n/az/admin.ts
+++ b/shared/src/i18n/az/admin.ts
@@ -467,6 +467,8 @@ const admin: TranslationStrings = {
'Məkana əlavə məlumatlar (rəylər, reytinqlər və keçidlər) təqdim etmək',
'admin.plugins.perm.hook:search-provider':
'TREK-in öz nəticələri ilə yanaşı, öz indeksindən məkan axtarışlarına cavab vermək',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Öz məkan kateqoriyalarını “Xəritədə məkanları kəşf et” bölməsinə əlavə etmək; birini seçdikdə plaginə baxdığınız xəritə sahəsi göndərilir',
'admin.plugins.perm.hook:trip-warning-provider':
'Səyahətlə bağlı doğrulama xəbərdarlıqları yaratmaq (planlayıcıda göstərilir)',
'admin.plugins.perm.hook:table-contributor':
@@ -485,6 +487,7 @@ const admin: TranslationStrings = {
'admin.plugins.mcpToolsTitle': 'Yayımladığı süni intellekt alətləri',
'admin.plugins.mcpToolsHint':
'Köməkçi bunları istifadəçinin adından işə sala bilər. Hər biri yuxarıda verilmiş giriş icazələri ilə işləyir.',
+ 'admin.plugins.poiCategoriesTitle': 'Əlavə etdiyi xəritə kateqoriyaları',
'admin.plugins.perm.mcp:tools':
'Süni intellekt köməkçisinin sizin adınızdan işə sala biləcəyi alətlər yayımlamaq (köməkçinin öz icazələri ilə deyil, burada plaginə verdiyiniz giriş icazələri ilə işləyir)',
'admin.plugins.perm.geolocation:read':
@@ -637,6 +640,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Təqvim tədbirləri təqdim edir',
'admin.plugins.cap.placeDetails': 'Məkan məlumatlarını zənginləşdirir',
'admin.plugins.cap.search': 'Axtarışlara cavab verir',
+ 'admin.plugins.cap.poiCategories': 'Xəritəyə kateqoriyalar əlavə edir',
'admin.plugins.cap.warnings': 'Problemləri işarələyir',
'admin.plugins.cap.mapLayers': 'Xəritədə təsvirlər çəkir',
'admin.plugins.cap.routing': 'Marşrutlaşdırma təqdim edir',
diff --git a/shared/src/i18n/az/map.ts b/shared/src/i18n/az/map.ts
index 824a72f3a..bf316b715 100644
--- a/shared/src/i18n/az/map.ts
+++ b/shared/src/i18n/az/map.ts
@@ -14,6 +14,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Muzeylər və mədəniyyət',
'poi.cat.nature': 'Təbiət və parklar',
'poi.cat.activities': 'Fəaliyyətlər',
+ 'poi.pluginCategories': 'Plaginlərdən gələn kateqoriyalar',
'map.showAllConnections':
'Bütün rezervasiya marşrutlarını göstər',
diff --git a/shared/src/i18n/br/admin.ts b/shared/src/i18n/br/admin.ts
index f6e2b9ef4..bdd6b6f0e 100644
--- a/shared/src/i18n/br/admin.ts
+++ b/shared/src/i18n/br/admin.ts
@@ -379,6 +379,8 @@ const admin: TranslationStrings = {
'Contribuir com detalhes extras (avaliações, notas, links) para um local',
'admin.plugins.perm.hook:search-provider':
'Responder buscas de lugares a partir de um índice próprio, ao lado dos resultados do TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Adicionar categorias de lugares próprias a “Explorar lugares no mapa”; ao escolher uma, o plugin recebe a área do mapa que você está vendo',
'admin.plugins.perm.hook:trip-warning-provider': 'Emitir avisos de validação em uma viagem (exibidos no planejador)',
'admin.plugins.perm.hook:table-contributor':
'Adicionar colunas e ações às visualizações da viagem (reservas, locais, dias)',
@@ -394,6 +396,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Publica ferramentas de IA',
'admin.plugins.mcpToolsTitle': 'Ferramentas de IA publicadas',
'admin.plugins.mcpToolsHint': 'Um assistente pode executá-las em nome de um usuário. Cada uma age com o acesso concedido acima.',
+ 'admin.plugins.poiCategoriesTitle': 'Categorias de mapa que adiciona',
'admin.plugins.perm.mcp:tools':
'Publicar ferramentas que um assistente de IA pode executar em seu nome (ele age com o acesso que você concede ao plugin aqui, não com o dele)',
'admin.plugins.perm.geolocation:read':
@@ -537,6 +540,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Fornece eventos de calendário',
'admin.plugins.cap.placeDetails': 'Enriquece locais',
'admin.plugins.cap.search': 'Responde buscas',
+ 'admin.plugins.cap.poiCategories': 'Adiciona categorias ao mapa',
'admin.plugins.cap.warnings': 'Sinaliza problemas',
'admin.plugins.cap.mapLayers': 'Desenha no mapa',
'admin.plugins.cap.routing': 'Oferece roteamento',
diff --git a/shared/src/i18n/br/map.ts b/shared/src/i18n/br/map.ts
index 5a1c03d32..1c7b88142 100644
--- a/shared/src/i18n/br/map.ts
+++ b/shared/src/i18n/br/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Museus e cultura',
'poi.cat.nature': 'Natureza e parques',
'poi.cat.activities': 'Atividades',
+ 'poi.pluginCategories': 'Categorias de plugins',
'map.showAllConnections': 'Mostrar todas as rotas de reservas',
'map.hideAllConnections': 'Ocultar todas as rotas de reservas',
'map.baseLayer.default': 'Mapa',
diff --git a/shared/src/i18n/ca/admin.ts b/shared/src/i18n/ca/admin.ts
index 2aad646b4..e82b372e3 100644
--- a/shared/src/i18n/ca/admin.ts
+++ b/shared/src/i18n/ca/admin.ts
@@ -548,6 +548,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:map-layer-provider': 'Dibuixar rutes, corredors i zones al mapa del viatge',
'admin.plugins.perm.hook:search-provider':
"Respondre cerques de llocs des d'un índex propi, al costat dels resultats de TREK",
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Afegir categories de llocs pròpies a «Explora llocs al mapa»; triar-ne una envia al connector la zona del mapa que estàs mirant',
'admin.plugins.perm.hook:route-provider':
'Oferir perfils de ruta amb què el planificador pot calcular els dies (p. ex. rutes per a cotxe elèctric amb parades de recàrrega)',
'admin.plugins.perm.hook:day-schedule-provider':
@@ -557,6 +559,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Publica eines d’IA',
'admin.plugins.mcpToolsTitle': 'Eines d’IA que publica',
'admin.plugins.mcpToolsHint': 'Un assistent pot executar-les en nom d’un usuari. Cadascuna actua amb els permisos concedits a dalt.',
+ 'admin.plugins.poiCategoriesTitle': 'Categories del mapa que afegeix',
'admin.plugins.perm.mcp:tools':
"Publicar eines que un assistent d'IA pot executar en nom teu (actua amb els permisos que concedeixes aquí al connector, no amb els seus)",
'admin.plugins.perm.geolocation:read':
@@ -681,6 +684,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Proporciona esdeveniments de calendari',
'admin.plugins.cap.placeDetails': 'Enriqueix els llocs',
'admin.plugins.cap.search': 'Respon cerques',
+ 'admin.plugins.cap.poiCategories': 'Afegeix categories al mapa',
'admin.plugins.cap.warnings': 'Marca problemes',
'admin.plugins.cap.mapLayers': 'Dibuixa al mapa',
'admin.plugins.cap.routing': 'Calcula rutes',
diff --git a/shared/src/i18n/ca/map.ts b/shared/src/i18n/ca/map.ts
index 741598ca0..d3ea045fc 100644
--- a/shared/src/i18n/ca/map.ts
+++ b/shared/src/i18n/ca/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Museus i cultura',
'poi.cat.nature': 'Natura i parcs',
'poi.cat.activities': 'Activitats',
+ 'poi.pluginCategories': 'Categories dels connectors',
'map.showAllConnections': 'Mostra totes les rutes de reserva',
'map.hideAllConnections': 'Amaga totes les rutes de reserva',
'map.baseLayer.default': 'Mapa',
diff --git a/shared/src/i18n/cs/admin.ts b/shared/src/i18n/cs/admin.ts
index 17af1b66a..b8f4fc217 100644
--- a/shared/src/i18n/cs/admin.ts
+++ b/shared/src/i18n/cs/admin.ts
@@ -382,6 +382,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:calendar-source': 'Poskytovat události do kalendáře',
'admin.plugins.perm.hook:place-detail-provider': 'Přidávat další podrobnosti (recenze, hodnocení, odkazy) k místu',
'admin.plugins.perm.hook:search-provider': 'Odpovídat na vyhledávání míst z vlastního indexu, vedle výsledků TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Přidávat vlastní kategorie míst do „Objevovat místa na mapě“; výběrem některé z nich doplněk obdrží oblast mapy, kterou si právě prohlížíte',
'admin.plugins.perm.hook:trip-warning-provider': 'Vyvolávat ověřovací upozornění u cesty (zobrazená v plánovači)',
'admin.plugins.perm.hook:table-contributor': 'Přidávat sloupce a akce do zobrazení cesty (rezervace, místa, dny)',
'admin.plugins.perm.hook:map-marker-provider': 'Přidávat značky na mapu cesty (např. zobrazit rezervace nebo POI)',
@@ -395,6 +397,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Zveřejňuje AI nástroje',
'admin.plugins.mcpToolsTitle': 'Zveřejněné AI nástroje',
'admin.plugins.mcpToolsHint': 'Asistent je může spustit jménem uživatele. Každý jedná s oprávněními udělenými výše.',
+ 'admin.plugins.poiCategoriesTitle': 'Kategorie mapy, které přidává',
'admin.plugins.perm.mcp:tools':
'Zveřejňovat nástroje, které může AI asistent spustit vaším jménem (jedná s oprávněními, která zde pluginu udělíte, ne se svými)',
'admin.plugins.perm.geolocation:read':
@@ -535,6 +538,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Poskytuje události kalendáře',
'admin.plugins.cap.placeDetails': 'Obohacuje místa',
'admin.plugins.cap.search': 'Odpovídá na vyhledávání',
+ 'admin.plugins.cap.poiCategories': 'Přidává kategorie na mapu',
'admin.plugins.cap.warnings': 'Označuje problémy',
'admin.plugins.cap.mapLayers': 'Kreslí na mapě',
'admin.plugins.cap.routing': 'Nabízí trasování',
diff --git a/shared/src/i18n/cs/map.ts b/shared/src/i18n/cs/map.ts
index fb0f5e6b5..6884ba718 100644
--- a/shared/src/i18n/cs/map.ts
+++ b/shared/src/i18n/cs/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Muzea a kultura',
'poi.cat.nature': 'Příroda a parky',
'poi.cat.activities': 'Aktivity',
+ 'poi.pluginCategories': 'Kategorie z pluginů',
'map.showAllConnections': 'Zobrazit všechny trasy rezervací',
'map.hideAllConnections': 'Skrýt všechny trasy rezervací',
'map.baseLayer.default': 'Mapa',
diff --git a/shared/src/i18n/de/admin.ts b/shared/src/i18n/de/admin.ts
index 0e2aac636..d9e1929a0 100644
--- a/shared/src/i18n/de/admin.ts
+++ b/shared/src/i18n/de/admin.ts
@@ -385,6 +385,8 @@ const admin: TranslationStrings = {
'Zusatzdetails (Bewertungen, Ratings, Links) zu einem Ort beisteuern',
'admin.plugins.perm.hook:search-provider':
'Ortssuchen aus einem eigenen Index beantworten, neben TREKs eigenen Ergebnissen',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Eigene Ortskategorien zu „Orte auf der Karte entdecken“ hinzufügen; wählst du eine davon, erhält das Plugin den Kartenausschnitt, den du gerade ansiehst',
'admin.plugins.perm.hook:trip-warning-provider':
'Validierungswarnungen zu einer Reise ausgeben (im Planer angezeigt)',
'admin.plugins.perm.hook:table-contributor':
@@ -400,6 +402,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Veröffentlicht KI-Tools',
'admin.plugins.mcpToolsTitle': 'Veröffentlichte KI-Tools',
'admin.plugins.mcpToolsHint': 'Ein Assistent kann sie im Namen eines Nutzers ausführen. Jedes handelt mit den oben erteilten Rechten.',
+ 'admin.plugins.poiCategoriesTitle': 'Kartenkategorien, die es hinzufügt',
'admin.plugins.perm.mcp:tools':
'Tools veröffentlichen, die ein KI-Assistent in deinem Namen ausführen kann (es handelt mit den Rechten, die du dem Plugin hier erteilst, nicht mit denen des Assistenten)',
'admin.plugins.perm.geolocation:read':
@@ -544,6 +547,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Liefert Kalender-Events',
'admin.plugins.cap.placeDetails': 'Reichert Orte an',
'admin.plugins.cap.search': 'Beantwortet Suchen',
+ 'admin.plugins.cap.poiCategories': 'Fügt Kartenkategorien hinzu',
'admin.plugins.cap.warnings': 'Meldet Probleme',
'admin.plugins.cap.mapLayers': 'Zeichnet auf der Karte',
'admin.plugins.cap.routing': 'Bietet Routing an',
diff --git a/shared/src/i18n/de/map.ts b/shared/src/i18n/de/map.ts
index b7d57b732..54a0dcd12 100644
--- a/shared/src/i18n/de/map.ts
+++ b/shared/src/i18n/de/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Museen & Kultur',
'poi.cat.nature': 'Natur & Parks',
'poi.cat.activities': 'Aktivitäten',
+ 'poi.pluginCategories': 'Kategorien aus Plugins',
'map.showAllConnections': 'Alle Buchungsrouten anzeigen',
'map.hideAllConnections': 'Alle Buchungsrouten ausblenden',
'map.baseLayer.default': 'Karte',
diff --git a/shared/src/i18n/en/admin.ts b/shared/src/i18n/en/admin.ts
index 4ae4ade7e..a38b1bffc 100644
--- a/shared/src/i18n/en/admin.ts
+++ b/shared/src/i18n/en/admin.ts
@@ -430,6 +430,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:calendar-source': 'Provide events to the calendar',
'admin.plugins.perm.hook:place-detail-provider': 'Contribute extra details (reviews, ratings, links) to a place',
'admin.plugins.perm.hook:search-provider': "Answer place searches from its own index, beside TREK's own results",
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Add its own place categories to Explore places on the map; picking one sends the plugin the map area you are viewing',
'admin.plugins.perm.hook:trip-warning-provider': 'Raise validation warnings on a trip (shown in the planner)',
'admin.plugins.perm.hook:table-contributor': 'Add columns and actions to trip views (reservations, places, days)',
'admin.plugins.perm.hook:map-marker-provider': 'Add markers to the trip map (e.g. show bookings or POIs)',
@@ -443,6 +445,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Publishes AI tools',
'admin.plugins.mcpToolsTitle': 'AI tools it publishes',
'admin.plugins.mcpToolsHint': 'An assistant can run these on a user’s behalf. Each one acts with the access granted above.',
+ 'admin.plugins.poiCategoriesTitle': 'Map categories it adds',
'admin.plugins.perm.mcp:tools':
'Publish tools that an AI assistant can run on your behalf (it acts with the access you grant the plugin here, not with the assistant’s own)',
'admin.plugins.perm.geolocation:read':
@@ -584,6 +587,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Provides calendar events',
'admin.plugins.cap.placeDetails': 'Enriches places',
'admin.plugins.cap.search': 'Answers searches',
+ 'admin.plugins.cap.poiCategories': 'Adds map categories',
'admin.plugins.cap.warnings': 'Flags issues',
'admin.plugins.cap.mapLayers': 'Draws on the map',
'admin.plugins.cap.routing': 'Offers routing',
diff --git a/shared/src/i18n/en/map.ts b/shared/src/i18n/en/map.ts
index 3a7612d69..68a1322a0 100644
--- a/shared/src/i18n/en/map.ts
+++ b/shared/src/i18n/en/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Museums & culture',
'poi.cat.nature': 'Nature & parks',
'poi.cat.activities': 'Activities',
+ 'poi.pluginCategories': 'Categories from plugins',
'map.showAllConnections': 'Show all booking routes',
'map.hideAllConnections': 'Hide all booking routes',
'map.baseLayer.default': 'Map',
diff --git a/shared/src/i18n/es/admin.ts b/shared/src/i18n/es/admin.ts
index 6fc1b9cfb..73e470218 100644
--- a/shared/src/i18n/es/admin.ts
+++ b/shared/src/i18n/es/admin.ts
@@ -388,6 +388,8 @@ const admin: TranslationStrings = {
'Aportar detalles adicionales (reseñas, valoraciones, enlaces) a un lugar',
'admin.plugins.perm.hook:search-provider':
'Responder a búsquedas de lugares desde su propio índice, junto a los resultados de TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Añadir sus propias categorías de lugares a «Explorar lugares en el mapa»; al elegir una, el plugin recibe la zona del mapa que estás viendo',
'admin.plugins.perm.hook:trip-warning-provider':
'Generar advertencias de validación en un viaje (mostradas en el planificador)',
'admin.plugins.perm.hook:table-contributor':
@@ -403,6 +405,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Publica herramientas de IA',
'admin.plugins.mcpToolsTitle': 'Herramientas de IA que publica',
'admin.plugins.mcpToolsHint': 'Un asistente puede ejecutarlas en nombre de un usuario. Cada una actúa con los permisos concedidos arriba.',
+ 'admin.plugins.poiCategoriesTitle': 'Categorías de mapa que añade',
'admin.plugins.perm.mcp:tools':
'Publicar herramientas que un asistente de IA puede ejecutar en tu nombre (actúa con el acceso que concedes aquí al complemento, no con el del asistente)',
'admin.plugins.perm.geolocation:read':
@@ -546,6 +549,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Proporciona eventos de calendario',
'admin.plugins.cap.placeDetails': 'Enriquece lugares',
'admin.plugins.cap.search': 'Responde búsquedas',
+ 'admin.plugins.cap.poiCategories': 'Añade categorías al mapa',
'admin.plugins.cap.warnings': 'Marca problemas',
'admin.plugins.cap.mapLayers': 'Dibuja en el mapa',
'admin.plugins.cap.routing': 'Ofrece rutas',
diff --git a/shared/src/i18n/es/map.ts b/shared/src/i18n/es/map.ts
index d54e61d7c..e933e9002 100644
--- a/shared/src/i18n/es/map.ts
+++ b/shared/src/i18n/es/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Museos y cultura',
'poi.cat.nature': 'Naturaleza y parques',
'poi.cat.activities': 'Actividades',
+ 'poi.pluginCategories': 'Categorías de plugins',
'map.showAllConnections': 'Mostrar todas las rutas de reservas',
'map.hideAllConnections': 'Ocultar todas las rutas de reservas',
'map.baseLayer.default': 'Mapa',
diff --git a/shared/src/i18n/et/admin.ts b/shared/src/i18n/et/admin.ts
index 43adb28ef..6c2a0a5a0 100644
--- a/shared/src/i18n/et/admin.ts
+++ b/shared/src/i18n/et/admin.ts
@@ -440,6 +440,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:place-detail-provider':
'Lisada kohale täiendavaid üksikasju (arvustused, hinnangud, lingid)',
'admin.plugins.perm.hook:search-provider': 'Vastata kohaotsingutele oma indeksist kõrvuti TREKi enda tulemustega',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Lisada oma kohakategooriaid jaotisesse „Avasta kaardil kohti“; ühe valimisel saab plugin kaardiala, mida sa parasjagu vaatad',
'admin.plugins.perm.hook:trip-warning-provider': 'Tõstatada reisi kontrollimisel hoiatusi (kuvatakse planeerijas)',
'admin.plugins.perm.hook:table-contributor':
'Lisada reisi vaadetesse veerge ja toiminguid (broneeringud, kohad, päevad)',
@@ -456,6 +458,7 @@ const admin: TranslationStrings = {
'admin.plugins.mcpToolsTitle': 'Avaldatavad tehisintellekti tööriistad',
'admin.plugins.mcpToolsHint':
'Assistent saab neid kasutaja nimel käivitada. Iga tööriist tegutseb ülal antud õigustega.',
+ 'admin.plugins.poiCategoriesTitle': 'Kaardikategooriad, mida see lisab',
'admin.plugins.perm.mcp:tools':
'Avaldada tööriistu, mida tehisintellekti assistent saab sinu nimel käivitada (see tegutseb siin pluginale antud õigustega, mitte assistendi enda omadega)',
'admin.plugins.perm.geolocation:read':
@@ -600,6 +603,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Pakub kalendrisündmusi',
'admin.plugins.cap.placeDetails': 'Täiendab kohaandmeid',
'admin.plugins.cap.search': 'Vastab otsingutele',
+ 'admin.plugins.cap.poiCategories': 'Lisab kaardikategooriaid',
'admin.plugins.cap.warnings': 'Märgib probleeme',
'admin.plugins.cap.mapLayers': 'Joonistab kaardile',
'admin.plugins.cap.routing': 'Pakub marsruutimist',
diff --git a/shared/src/i18n/et/map.ts b/shared/src/i18n/et/map.ts
index c44b3c04b..88f75e7fc 100644
--- a/shared/src/i18n/et/map.ts
+++ b/shared/src/i18n/et/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Muuseumid ja kultuur',
'poi.cat.nature': 'Loodus ja pargid',
'poi.cat.activities': 'Tegevused',
+ 'poi.pluginCategories': 'Pluginate kategooriad',
'map.showAllConnections': 'Näita kõiki broneeringute marsruute',
'map.hideAllConnections': 'Peida kõik broneeringute marsruudid',
'map.baseLayer.default': 'Kaart',
diff --git a/shared/src/i18n/fr/admin.ts b/shared/src/i18n/fr/admin.ts
index 3e5b47cec..202752248 100644
--- a/shared/src/i18n/fr/admin.ts
+++ b/shared/src/i18n/fr/admin.ts
@@ -388,6 +388,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:place-detail-provider': 'Ajouter des détails supplémentaires (avis, notes, liens) à un lieu',
'admin.plugins.perm.hook:search-provider':
'Répondre aux recherches de lieux depuis son propre index, à côté des résultats de TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ "Ajouter ses propres catégories de lieux à « Explorer les lieux sur la carte » ; en choisir une envoie à l'extension la zone de la carte que vous consultez",
'admin.plugins.perm.hook:trip-warning-provider':
'Émettre des avertissements de validation sur un voyage (affichés dans le planificateur)',
'admin.plugins.perm.hook:table-contributor':
@@ -405,6 +407,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Publie des outils IA',
'admin.plugins.mcpToolsTitle': 'Outils IA publiés',
'admin.plugins.mcpToolsHint': "Un assistant peut les exécuter au nom d'un utilisateur. Chacun agit avec les accès accordés ci-dessus.",
+ 'admin.plugins.poiCategoriesTitle': 'Catégories de carte ajoutées',
'admin.plugins.perm.mcp:tools':
"Publier des outils qu'un assistant IA peut exécuter en votre nom (il agit avec les accès que vous accordez ici à l'extension, pas avec les siens)",
'admin.plugins.perm.geolocation:read':
@@ -549,6 +552,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Fournit des événements de calendrier',
'admin.plugins.cap.placeDetails': 'Enrichit les lieux',
'admin.plugins.cap.search': 'Répond aux recherches',
+ 'admin.plugins.cap.poiCategories': 'Ajoute des catégories à la carte',
'admin.plugins.cap.warnings': 'Signale les problèmes',
'admin.plugins.cap.mapLayers': 'Dessine sur la carte',
'admin.plugins.cap.routing': 'Propose des itinéraires',
diff --git a/shared/src/i18n/fr/map.ts b/shared/src/i18n/fr/map.ts
index 10883dab5..f8729292d 100644
--- a/shared/src/i18n/fr/map.ts
+++ b/shared/src/i18n/fr/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Musées & culture',
'poi.cat.nature': 'Nature & parcs',
'poi.cat.activities': 'Activités',
+ 'poi.pluginCategories': 'Catégories des plugins',
'map.showAllConnections': 'Afficher tous les itinéraires',
'map.hideAllConnections': 'Masquer tous les itinéraires',
'map.baseLayer.default': 'Carte',
diff --git a/shared/src/i18n/gr/admin.ts b/shared/src/i18n/gr/admin.ts
index 75b31980a..0413054ec 100644
--- a/shared/src/i18n/gr/admin.ts
+++ b/shared/src/i18n/gr/admin.ts
@@ -441,6 +441,8 @@ const admin: TranslationStrings = {
'Συνεισφορά επιπλέον λεπτομερειών (κριτικές, βαθμολογίες, σύνδεσμοι) σε ένα μέρος',
'admin.plugins.perm.hook:search-provider':
'Απάντηση σε αναζητήσεις τοποθεσιών από δικό του ευρετήριο, δίπλα στα αποτελέσματα του TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Προσθήκη δικών του κατηγοριών τοποθεσιών στην «Εξερεύνηση μερών στον χάρτη»· όταν επιλέγετε μία, το πρόσθετο λαμβάνει την περιοχή του χάρτη που βλέπετε',
'admin.plugins.perm.hook:trip-warning-provider':
'Εμφάνιση προειδοποιήσεων επικύρωσης σε ένα ταξίδι (εμφανίζονται στον σχεδιαστή)',
'admin.plugins.perm.hook:table-contributor':
@@ -457,6 +459,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Δημοσιεύει εργαλεία AI',
'admin.plugins.mcpToolsTitle': 'Δημοσιευμένα εργαλεία AI',
'admin.plugins.mcpToolsHint': 'Ένας βοηθός μπορεί να τα εκτελέσει εκ μέρους ενός χρήστη. Καθένα ενεργεί με τα δικαιώματα που δόθηκαν παραπάνω.',
+ 'admin.plugins.poiCategoriesTitle': 'Κατηγορίες χάρτη που προσθέτει',
'admin.plugins.perm.mcp:tools':
'Δημοσίευση εργαλείων που μπορεί να εκτελέσει ένας βοηθός AI εκ μέρους σας (ενεργεί με τα δικαιώματα που δίνετε εδώ στο πρόσθετο, όχι με τα δικά του)',
'admin.plugins.perm.geolocation:read':
@@ -601,6 +604,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Παρέχει συμβάντα ημερολογίου',
'admin.plugins.cap.placeDetails': 'Εμπλουτίζει μέρη',
'admin.plugins.cap.search': 'Απαντά σε αναζητήσεις',
+ 'admin.plugins.cap.poiCategories': 'Προσθέτει κατηγορίες στον χάρτη',
'admin.plugins.cap.warnings': 'Επισημαίνει ζητήματα',
'admin.plugins.cap.mapLayers': 'Σχεδιάζει στον χάρτη',
'admin.plugins.cap.routing': 'Παρέχει δρομολόγηση',
diff --git a/shared/src/i18n/gr/map.ts b/shared/src/i18n/gr/map.ts
index 820b01925..594712798 100644
--- a/shared/src/i18n/gr/map.ts
+++ b/shared/src/i18n/gr/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Μουσεία & πολιτισμός',
'poi.cat.nature': 'Φύση & πάρκα',
'poi.cat.activities': 'Δραστηριότητες',
+ 'poi.pluginCategories': 'Κατηγορίες από πρόσθετα',
'map.showAllConnections': 'Εμφάνιση όλων των διαδρομών κρατήσεων',
'map.hideAllConnections': 'Απόκρυψη όλων των διαδρομών κρατήσεων',
'map.baseLayer.default': 'Χάρτης',
diff --git a/shared/src/i18n/hu/admin.ts b/shared/src/i18n/hu/admin.ts
index a63b16703..b4dc623b7 100644
--- a/shared/src/i18n/hu/admin.ts
+++ b/shared/src/i18n/hu/admin.ts
@@ -391,6 +391,8 @@ const admin: TranslationStrings = {
'További részletek (értékelések, minősítések, hivatkozások) hozzáadása egy helyhez',
'admin.plugins.perm.hook:search-provider':
'Helykeresések megválaszolása saját indexből, a TREK saját találatai mellett',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Saját helykategóriák hozzáadása a „Helyek felfedezése a térképen” sávhoz; ha kiválasztasz egyet, a bővítmény megkapja a térképnek azt a részét, amelyet éppen nézel',
'admin.plugins.perm.hook:trip-warning-provider':
'Ellenőrzési figyelmeztetések megjelenítése egy utazáson (a tervezőben látható)',
'admin.plugins.perm.hook:table-contributor':
@@ -407,6 +409,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'MI-eszközöket tesz közzé',
'admin.plugins.mcpToolsTitle': 'Közzétett MI-eszközök',
'admin.plugins.mcpToolsHint': 'Egy asszisztens futtathatja őket a felhasználó nevében. Mindegyik a fent megadott jogosultságokkal működik.',
+ 'admin.plugins.poiCategoriesTitle': 'Térképkategóriák, amelyeket hozzáad',
'admin.plugins.perm.mcp:tools':
'Olyan eszközök közzététele, amelyeket egy MI-asszisztens futtathat a nevedben (a bővítménynek itt adott jogosultságokkal működik, nem a sajátjával)',
'admin.plugins.perm.geolocation:read':
@@ -550,6 +553,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Naptáreseményeket biztosít',
'admin.plugins.cap.placeDetails': 'Helyeket gazdagít',
'admin.plugins.cap.search': 'Válaszol a keresésekre',
+ 'admin.plugins.cap.poiCategories': 'Térképkategóriákat ad hozzá',
'admin.plugins.cap.warnings': 'Problémákat jelez',
'admin.plugins.cap.mapLayers': 'Rajzol a térképre',
'admin.plugins.cap.routing': 'Útvonaltervezést biztosít',
diff --git a/shared/src/i18n/hu/map.ts b/shared/src/i18n/hu/map.ts
index 9c4320e5f..72d265fb7 100644
--- a/shared/src/i18n/hu/map.ts
+++ b/shared/src/i18n/hu/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Múzeumok és kultúra',
'poi.cat.nature': 'Természet és parkok',
'poi.cat.activities': 'Programok',
+ 'poi.pluginCategories': 'Pluginok kategóriái',
'map.showAllConnections': 'Összes foglalási útvonal megjelenítése',
'map.hideAllConnections': 'Összes foglalási útvonal elrejtése',
'map.baseLayer.default': 'Térkép',
diff --git a/shared/src/i18n/i18n-permission-wording.spec.ts b/shared/src/i18n/i18n-permission-wording.spec.ts
index b2f93cd47..8835a0009 100644
--- a/shared/src/i18n/i18n-permission-wording.spec.ts
+++ b/shared/src/i18n/i18n-permission-wording.spec.ts
@@ -24,4 +24,14 @@ describe('canonical permission wording', () => {
// It has to say where the position does come from, or it explains nothing.
expect(copy).toMatch(/permission/i);
});
+
+ it('I18N-PERM-002: the POI category permission says the plugin is sent the map area', () => {
+ // Unlike a search provider, which only sees words the user typed, this hook is
+ // handed the viewport every time one of its chips is picked. An admin reading the
+ // consent line has to learn that there, not from the plugin's own documentation.
+ const copy = admin['admin.plugins.perm.hook:poi-category-provider'];
+
+ expect(copy).toBeTruthy();
+ expect(copy).toMatch(/map area/i);
+ });
});
diff --git a/shared/src/i18n/id/admin.ts b/shared/src/i18n/id/admin.ts
index 981a3d9c4..13df8884f 100644
--- a/shared/src/i18n/id/admin.ts
+++ b/shared/src/i18n/id/admin.ts
@@ -437,6 +437,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:place-detail-provider':
'Menyumbangkan detail tambahan (ulasan, peringkat, tautan) untuk suatu tempat',
'admin.plugins.perm.hook:search-provider': 'Menjawab pencarian tempat dari indeks sendiri, di samping hasil TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Menambahkan kategori tempat sendiri ke “Jelajahi tempat di peta”; saat Anda memilih salah satunya, plugin menerima area peta yang sedang Anda lihat',
'admin.plugins.perm.hook:trip-warning-provider':
'Munculkan peringatan validasi pada perjalanan (ditampilkan di perencana)',
'admin.plugins.perm.hook:table-contributor':
@@ -453,6 +455,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Menerbitkan alat AI',
'admin.plugins.mcpToolsTitle': 'Alat AI yang diterbitkan',
'admin.plugins.mcpToolsHint': 'Asisten dapat menjalankannya atas nama pengguna. Masing-masing bertindak dengan akses yang diberikan di atas.',
+ 'admin.plugins.poiCategoriesTitle': 'Kategori peta yang ditambahkannya',
'admin.plugins.perm.mcp:tools':
'Menerbitkan alat yang dapat dijalankan asisten AI atas nama Anda (bertindak dengan akses yang Anda berikan ke plugin di sini, bukan milik asisten)',
'admin.plugins.perm.geolocation:read':
@@ -594,6 +597,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Menyediakan acara kalender',
'admin.plugins.cap.placeDetails': 'Memperkaya tempat',
'admin.plugins.cap.search': 'Menjawab pencarian',
+ 'admin.plugins.cap.poiCategories': 'Menambahkan kategori peta',
'admin.plugins.cap.warnings': 'Tandai masalah',
'admin.plugins.cap.mapLayers': 'Menggambar di peta',
'admin.plugins.cap.routing': 'Menyediakan routing',
diff --git a/shared/src/i18n/id/map.ts b/shared/src/i18n/id/map.ts
index 60fb1eff4..81df858ee 100644
--- a/shared/src/i18n/id/map.ts
+++ b/shared/src/i18n/id/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Museum & budaya',
'poi.cat.nature': 'Alam & taman',
'poi.cat.activities': 'Aktivitas',
+ 'poi.pluginCategories': 'Kategori dari plugin',
'map.showAllConnections': 'Tampilkan semua rute pemesanan',
'map.hideAllConnections': 'Sembunyikan semua rute pemesanan',
'map.baseLayer.default': 'Peta',
diff --git a/shared/src/i18n/it/admin.ts b/shared/src/i18n/it/admin.ts
index 8c570fe2a..9377866a0 100644
--- a/shared/src/i18n/it/admin.ts
+++ b/shared/src/i18n/it/admin.ts
@@ -386,6 +386,8 @@ const admin: TranslationStrings = {
'Fornire dettagli aggiuntivi (recensioni, valutazioni, link) a un luogo',
'admin.plugins.perm.hook:search-provider':
'Rispondere alle ricerche di luoghi dal proprio indice, accanto ai risultati di TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ "Aggiungere categorie di luoghi proprie a «Esplora luoghi sulla mappa»; sceglierne una invia al plugin l'area della mappa che stai guardando",
'admin.plugins.perm.hook:trip-warning-provider':
'Segnala avvisi di validazione su un viaggio (mostrati nel pianificatore)',
'admin.plugins.perm.hook:table-contributor':
@@ -402,6 +404,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Pubblica strumenti IA',
'admin.plugins.mcpToolsTitle': 'Strumenti IA pubblicati',
'admin.plugins.mcpToolsHint': 'Un assistente può eseguirli per conto di un utente. Ognuno agisce con i permessi concessi sopra.',
+ 'admin.plugins.poiCategoriesTitle': 'Categorie della mappa che aggiunge',
'admin.plugins.perm.mcp:tools':
'Pubblicare strumenti che un assistente IA può eseguire per tuo conto (agisce con i permessi che concedi qui al plugin, non con i propri)',
'admin.plugins.perm.geolocation:read':
@@ -544,6 +547,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Fornisce eventi calendario',
'admin.plugins.cap.placeDetails': 'Arricchisce luoghi',
'admin.plugins.cap.search': 'Risponde alle ricerche',
+ 'admin.plugins.cap.poiCategories': 'Aggiunge categorie alla mappa',
'admin.plugins.cap.warnings': 'Segnala problemi',
'admin.plugins.cap.mapLayers': 'Disegna sulla mappa',
'admin.plugins.cap.routing': 'Offre routing',
diff --git a/shared/src/i18n/it/map.ts b/shared/src/i18n/it/map.ts
index ac5b58c08..26e02c19e 100644
--- a/shared/src/i18n/it/map.ts
+++ b/shared/src/i18n/it/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Musei e cultura',
'poi.cat.nature': 'Natura e parchi',
'poi.cat.activities': 'Attività',
+ 'poi.pluginCategories': 'Categorie dai plugin',
'map.showAllConnections': 'Mostra tutti i percorsi prenotati',
'map.hideAllConnections': 'Nascondi tutti i percorsi prenotati',
'map.baseLayer.default': 'Mappa',
diff --git a/shared/src/i18n/ja/admin.ts b/shared/src/i18n/ja/admin.ts
index a68e1f0b1..f66f513da 100644
--- a/shared/src/i18n/ja/admin.ts
+++ b/shared/src/i18n/ja/admin.ts
@@ -408,6 +408,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:calendar-source': 'カレンダーへの予定の提供',
'admin.plugins.perm.hook:place-detail-provider': '場所に追加の詳細情報(レビュー、評価、リンク)を提供',
'admin.plugins.perm.hook:search-provider': '独自のインデックスから場所の検索に回答(TREK 自身の結果と並べて表示)',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ '独自のスポットカテゴリを「地図でスポットを探す」に追加(カテゴリを選ぶと、表示中の地図の範囲がプラグインに送られます)',
'admin.plugins.perm.hook:trip-warning-provider': '旅程に検証警告を表示(プランナー内に表示)',
'admin.plugins.perm.hook:table-contributor': '旅行のビュー(予約、場所、日程)に列とアクションを追加',
'admin.plugins.perm.hook:map-marker-provider': '旅行の地図にマーカーを追加(例: 予約や POI を表示)',
@@ -420,6 +422,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'AI ツールを公開',
'admin.plugins.mcpToolsTitle': '公開する AI ツール',
'admin.plugins.mcpToolsHint': 'アシスタントがユーザーの代わりに実行できます。各ツールは上記で付与した権限で動作します。',
+ 'admin.plugins.poiCategoriesTitle': '追加する地図カテゴリ',
'admin.plugins.perm.mcp:tools':
'AI アシスタントがあなたの代わりに実行できるツールを公開する(ここでプラグインに付与した権限で動作し、アシスタント自身の権限ではありません)',
'admin.plugins.perm.geolocation:read':
@@ -559,6 +562,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'カレンダー予定を提供',
'admin.plugins.cap.placeDetails': '場所を充実',
'admin.plugins.cap.search': '検索に回答',
+ 'admin.plugins.cap.poiCategories': '地図にカテゴリを追加',
'admin.plugins.cap.warnings': '問題を検出',
'admin.plugins.cap.mapLayers': '地図に描画',
'admin.plugins.cap.routing': 'ルーティングを提供',
diff --git a/shared/src/i18n/ja/map.ts b/shared/src/i18n/ja/map.ts
index 3ae0a5752..357689713 100644
--- a/shared/src/i18n/ja/map.ts
+++ b/shared/src/i18n/ja/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': '美術館・文化施設',
'poi.cat.nature': '自然・公園',
'poi.cat.activities': 'アクティビティ',
+ 'poi.pluginCategories': 'プラグインのカテゴリ',
'map.showAllConnections': 'すべての予約ルートを表示',
'map.hideAllConnections': 'すべての予約ルートを非表示',
'map.baseLayer.default': '地図',
diff --git a/shared/src/i18n/ko/admin.ts b/shared/src/i18n/ko/admin.ts
index 2e4cf791c..165b5b563 100644
--- a/shared/src/i18n/ko/admin.ts
+++ b/shared/src/i18n/ko/admin.ts
@@ -410,6 +410,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:calendar-source': '캘린더에 일정 제공',
'admin.plugins.perm.hook:place-detail-provider': '장소에 추가 정보(리뷰, 평점, 링크)를 제공',
'admin.plugins.perm.hook:search-provider': '자체 색인에서 장소 검색에 응답 (TREK 자체 결과와 함께 표시)',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ '자체 장소 카테고리를 ‘지도에서 장소 탐색’에 추가 (카테고리를 선택하면 보고 있는 지도 영역이 플러그인에 전송됨)',
'admin.plugins.perm.hook:trip-warning-provider': '여행에 검증 경고를 표시 (플래너에 표시됨)',
'admin.plugins.perm.hook:table-contributor': '여행 보기(예약, 장소, 일자)에 열과 작업 추가',
'admin.plugins.perm.hook:map-marker-provider': '여행 지도에 마커 추가(예: 예약 또는 POI 표시)',
@@ -421,6 +423,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'AI 도구 게시',
'admin.plugins.mcpToolsTitle': '게시하는 AI 도구',
'admin.plugins.mcpToolsHint': '어시스턴트가 사용자를 대신해 실행할 수 있습니다. 각 도구는 위에서 부여한 권한으로 동작합니다.',
+ 'admin.plugins.poiCategoriesTitle': '추가하는 지도 카테고리',
'admin.plugins.perm.mcp:tools':
'AI 어시스턴트가 사용자를 대신해 실행할 수 있는 도구 게시 (여기서 플러그인에 부여한 권한으로 동작하며, 어시스턴트 자신의 권한이 아닙니다)',
'admin.plugins.perm.geolocation:read':
@@ -559,6 +562,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': '캘린더 일정 제공',
'admin.plugins.cap.placeDetails': '장소 정보 강화',
'admin.plugins.cap.search': '검색에 응답',
+ 'admin.plugins.cap.poiCategories': '지도 카테고리 추가',
'admin.plugins.cap.warnings': '문제 표시',
'admin.plugins.cap.mapLayers': '지도에 그리기',
'admin.plugins.cap.routing': '라우팅 제공',
diff --git a/shared/src/i18n/ko/map.ts b/shared/src/i18n/ko/map.ts
index 0f06e3c7b..7212bd751 100644
--- a/shared/src/i18n/ko/map.ts
+++ b/shared/src/i18n/ko/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': '박물관 & 문화',
'poi.cat.nature': '자연 & 공원',
'poi.cat.activities': '액티비티',
+ 'poi.pluginCategories': '플러그인 카테고리',
'map.showAllConnections': '모든 예약 경로 표시',
'map.hideAllConnections': '모든 예약 경로 숨기기',
'map.baseLayer.default': '지도',
diff --git a/shared/src/i18n/nl/admin.ts b/shared/src/i18n/nl/admin.ts
index cbcb144f3..10a3f8ccd 100644
--- a/shared/src/i18n/nl/admin.ts
+++ b/shared/src/i18n/nl/admin.ts
@@ -386,6 +386,8 @@ const admin: TranslationStrings = {
'Extra details (reviews, beoordelingen, links) aan een plek toevoegen',
'admin.plugins.perm.hook:search-provider':
'Zoekopdrachten naar locaties beantwoorden vanuit een eigen index, naast de resultaten van TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Eigen plaatscategorieën toevoegen aan “Plaatsen op de kaart ontdekken”; kies je er een, dan ontvangt de plug-in het kaartgebied dat je bekijkt',
'admin.plugins.perm.hook:trip-warning-provider':
'Validatiewaarschuwingen tonen bij een reis (zichtbaar in de planner)',
'admin.plugins.perm.hook:table-contributor':
@@ -401,6 +403,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Publiceert AI-tools',
'admin.plugins.mcpToolsTitle': 'Gepubliceerde AI-tools',
'admin.plugins.mcpToolsHint': 'Een assistent kan deze namens een gebruiker uitvoeren. Elke tool handelt met de hierboven verleende rechten.',
+ 'admin.plugins.poiCategoriesTitle': 'Kaartcategorieën die het toevoegt',
'admin.plugins.perm.mcp:tools':
'Tools publiceren die een AI-assistent namens jou kan uitvoeren (die handelt met de rechten die je de plug-in hier geeft, niet met die van de assistent)',
'admin.plugins.perm.geolocation:read':
@@ -543,6 +546,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Levert kalenderevenementen',
'admin.plugins.cap.placeDetails': 'Verrijkt plekken',
'admin.plugins.cap.search': 'Beantwoordt zoekopdrachten',
+ 'admin.plugins.cap.poiCategories': 'Voegt kaartcategorieën toe',
'admin.plugins.cap.warnings': 'Signaleert problemen',
'admin.plugins.cap.mapLayers': 'Tekent op de kaart',
'admin.plugins.cap.routing': 'Biedt routering aan',
diff --git a/shared/src/i18n/nl/map.ts b/shared/src/i18n/nl/map.ts
index 1b6832fb2..97fa583bb 100644
--- a/shared/src/i18n/nl/map.ts
+++ b/shared/src/i18n/nl/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Musea & cultuur',
'poi.cat.nature': 'Natuur & parken',
'poi.cat.activities': 'Activiteiten',
+ 'poi.pluginCategories': 'Categorieën uit plugins',
'map.showAllConnections': 'Alle boekingsroutes tonen',
'map.hideAllConnections': 'Alle boekingsroutes verbergen',
'map.baseLayer.default': 'Kaart',
diff --git a/shared/src/i18n/pl/admin.ts b/shared/src/i18n/pl/admin.ts
index 181b1bd83..61a9d1075 100644
--- a/shared/src/i18n/pl/admin.ts
+++ b/shared/src/i18n/pl/admin.ts
@@ -382,6 +382,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:place-detail-provider':
'Dodawanie dodatkowych szczegółów (recenzji, ocen, linków) do miejsca',
'admin.plugins.perm.hook:search-provider': 'Odpowiadać na wyszukiwania miejsc z własnego indeksu, obok wyników TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Dodawanie własnych kategorii miejsc do „Odkrywaj miejsca na mapie”; wybranie jednej z nich wysyła wtyczce obszar mapy, który oglądasz',
'admin.plugins.perm.hook:trip-warning-provider':
'Zgłaszanie ostrzeżeń walidacyjnych dla podróży (widocznych w planerze)',
'admin.plugins.perm.hook:table-contributor': 'Dodawanie kolumn i akcji do widoków podróży (rezerwacje, miejsca, dni)',
@@ -397,6 +399,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Publikuje narzędzia AI',
'admin.plugins.mcpToolsTitle': 'Publikowane narzędzia AI',
'admin.plugins.mcpToolsHint': 'Asystent może je uruchomić w imieniu użytkownika. Każde działa z uprawnieniami nadanymi powyżej.',
+ 'admin.plugins.poiCategoriesTitle': 'Kategorie mapy, które dodaje',
'admin.plugins.perm.mcp:tools':
'Publikowanie narzędzi, które asystent AI może uruchomić w Twoim imieniu (działa z uprawnieniami nadanymi tutaj wtyczce, nie z własnymi)',
'admin.plugins.perm.geolocation:read':
@@ -541,6 +544,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Dostarcza wydarzenia kalendarza',
'admin.plugins.cap.placeDetails': 'Wzbogaca miejsca',
'admin.plugins.cap.search': 'Odpowiada na wyszukiwania',
+ 'admin.plugins.cap.poiCategories': 'Dodaje kategorie mapy',
'admin.plugins.cap.warnings': 'Zgłasza problemy',
'admin.plugins.cap.mapLayers': 'Rysuje na mapie',
'admin.plugins.cap.routing': 'Oferuje trasowanie',
diff --git a/shared/src/i18n/pl/map.ts b/shared/src/i18n/pl/map.ts
index 6a944356c..134b54f9c 100644
--- a/shared/src/i18n/pl/map.ts
+++ b/shared/src/i18n/pl/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Muzea i kultura',
'poi.cat.nature': 'Przyroda i parki',
'poi.cat.activities': 'Aktywności',
+ 'poi.pluginCategories': 'Kategorie z wtyczek',
'map.showAllConnections': 'Pokaż wszystkie trasy rezerwacji',
'map.hideAllConnections': 'Ukryj wszystkie trasy rezerwacji',
'map.baseLayer.default': 'Mapa',
diff --git a/shared/src/i18n/ru/admin.ts b/shared/src/i18n/ru/admin.ts
index 325ee0191..ab912c4d3 100644
--- a/shared/src/i18n/ru/admin.ts
+++ b/shared/src/i18n/ru/admin.ts
@@ -387,6 +387,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:place-detail-provider': 'Добавлять дополнительные сведения (отзывы, оценки, ссылки) к месту',
'admin.plugins.perm.hook:search-provider':
'Отвечать на поиск мест из собственного индекса, рядом с результатами TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Добавлять собственные категории мест в «Поиск мест на карте»; при выборе одной из них плагин получает область карты, которую вы просматриваете',
'admin.plugins.perm.hook:trip-warning-provider':
'Выдавать предупреждения проверки для поездки (отображаются в планировщике)',
'admin.plugins.perm.hook:table-contributor':
@@ -403,6 +405,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Публикует ИИ-инструменты',
'admin.plugins.mcpToolsTitle': 'Публикуемые ИИ-инструменты',
'admin.plugins.mcpToolsHint': 'Ассистент может запускать их от имени пользователя. Каждый действует с правами, выданными выше.',
+ 'admin.plugins.poiCategoriesTitle': 'Категории карты, которые он добавляет',
'admin.plugins.perm.mcp:tools':
'Публиковать инструменты, которые ИИ-ассистент может запускать от вашего имени (он действует с правами, выданными плагину здесь, а не со своими)',
'admin.plugins.perm.geolocation:read':
@@ -546,6 +549,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Предоставляет события календаря',
'admin.plugins.cap.placeDetails': 'Обогащает места',
'admin.plugins.cap.search': 'Отвечает на поиск',
+ 'admin.plugins.cap.poiCategories': 'Добавляет категории на карту',
'admin.plugins.cap.warnings': 'Отмечает проблемы',
'admin.plugins.cap.mapLayers': 'Рисует на карте',
'admin.plugins.cap.routing': 'Предоставляет маршрутизацию',
diff --git a/shared/src/i18n/ru/map.ts b/shared/src/i18n/ru/map.ts
index af1399212..ec612c61f 100644
--- a/shared/src/i18n/ru/map.ts
+++ b/shared/src/i18n/ru/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Музеи и культура',
'poi.cat.nature': 'Природа и парки',
'poi.cat.activities': 'Развлечения',
+ 'poi.pluginCategories': 'Категории из плагинов',
'map.showAllConnections': 'Показать все маршруты бронирований',
'map.hideAllConnections': 'Скрыть все маршруты бронирований',
'map.baseLayer.default': 'Карта',
diff --git a/shared/src/i18n/sk/admin.ts b/shared/src/i18n/sk/admin.ts
index b7ce1448f..4d7d182ec 100644
--- a/shared/src/i18n/sk/admin.ts
+++ b/shared/src/i18n/sk/admin.ts
@@ -437,6 +437,8 @@ const admin: TranslationStrings = {
'Prispievať ďalšími podrobnosťami (recenzie, hodnotenia, odkazy) k miestu',
'admin.plugins.perm.hook:search-provider':
'Odpovedať na vyhľadávania miest z vlastného indexu, popri vlastných výsledkoch TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Pridávať vlastné kategórie miest do „Objavovať miesta na mape“; výberom niektorej z nich plugin dostane oblasť mapy, ktorú si práve prezeráte',
'admin.plugins.perm.hook:trip-warning-provider': 'Vyvolávať overovacie upozornenia na ceste (zobrazené v plánovači)',
'admin.plugins.perm.hook:table-contributor': 'Pridávať stĺpce a akcie do zobrazení ciest (rezervácie, miesta, dni)',
'admin.plugins.perm.hook:map-marker-provider': 'Pridávať značky na mapu cesty (napr. zobraziť rezervácie alebo POI)',
@@ -450,6 +452,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Zverejňuje AI nástroje',
'admin.plugins.mcpToolsTitle': 'AI nástroje, ktoré zverejňuje',
'admin.plugins.mcpToolsHint': 'Asistent ich môže spustiť v mene používateľa. Každý koná s prístupom udeleným vyššie.',
+ 'admin.plugins.poiCategoriesTitle': 'Kategórie mapy, ktoré pridáva',
'admin.plugins.perm.mcp:tools':
'Zverejňovať nástroje, ktoré môže AI asistent spustiť vo vašom mene (koná s prístupom, ktorý tu pluginu udelíte, nie s vlastným prístupom asistenta)',
'admin.plugins.perm.geolocation:read':
@@ -595,6 +598,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Poskytuje udalosti kalendára',
'admin.plugins.cap.placeDetails': 'Obohacuje miesta',
'admin.plugins.cap.search': 'Odpovedá na vyhľadávania',
+ 'admin.plugins.cap.poiCategories': 'Pridáva kategórie na mapu',
'admin.plugins.cap.warnings': 'Označuje problémy',
'admin.plugins.cap.mapLayers': 'Kreslí na mape',
'admin.plugins.cap.routing': 'Ponúka trasovanie',
diff --git a/shared/src/i18n/sk/map.ts b/shared/src/i18n/sk/map.ts
index e2a78eb45..134c4b2de 100644
--- a/shared/src/i18n/sk/map.ts
+++ b/shared/src/i18n/sk/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Múzeá a kultúra',
'poi.cat.nature': 'Príroda a parky',
'poi.cat.activities': 'Aktivity',
+ 'poi.pluginCategories': 'Kategórie z pluginov',
'map.showAllConnections': 'Zobraziť všetky trasy rezervácií',
'map.hideAllConnections': 'Skryť všetky trasy rezervácií',
'map.baseLayer.default': 'Mapa',
diff --git a/shared/src/i18n/sv/admin.ts b/shared/src/i18n/sv/admin.ts
index 412a0bdbb..9cec67d2c 100644
--- a/shared/src/i18n/sv/admin.ts
+++ b/shared/src/i18n/sv/admin.ts
@@ -450,6 +450,8 @@ const admin: TranslationStrings = {
'Bidra med extra detaljer (recensioner, betyg, länkar) till en plats',
'admin.plugins.perm.hook:search-provider':
'Besvara platssökningar från ett eget index, vid sidan av TREK:s egna resultat',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Lägga till egna platskategorier i ”Utforska platser på kartan”; väljer du en får tillägget det kartområde du tittar på',
'admin.plugins.perm.hook:trip-warning-provider': 'Visa valideringsvarningar på en resa (visas i planeraren)',
'admin.plugins.perm.hook:table-contributor':
'Lägga till kolumner och åtgärder i rese­vyer (bokningar, platser, dagar)',
@@ -464,6 +466,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Publicerar AI-verktyg',
'admin.plugins.mcpToolsTitle': 'Publicerade AI-verktyg',
'admin.plugins.mcpToolsHint': 'En assistent kan köra dem åt en användare. Varje verktyg agerar med de rättigheter som getts ovan.',
+ 'admin.plugins.poiCategoriesTitle': 'Kartkategorier som tillägget lägger till',
'admin.plugins.perm.mcp:tools':
'Publicera verktyg som en AI-assistent kan köra åt dig (det agerar med de rättigheter du ger tillägget här, inte med assistentens egna)',
'admin.plugins.perm.geolocation:read':
@@ -607,6 +610,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Tillhandahåller kalenderhändelser',
'admin.plugins.cap.placeDetails': 'Berikar platser',
'admin.plugins.cap.search': 'Besvarar sökningar',
+ 'admin.plugins.cap.poiCategories': 'Lägger till kartkategorier',
'admin.plugins.cap.warnings': 'Flaggar problem',
'admin.plugins.cap.mapLayers': 'Ritar på kartan',
'admin.plugins.cap.routing': 'Erbjuder ruttplanering',
diff --git a/shared/src/i18n/sv/map.ts b/shared/src/i18n/sv/map.ts
index 6a99addd4..5eca67426 100644
--- a/shared/src/i18n/sv/map.ts
+++ b/shared/src/i18n/sv/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Museer och kultur',
'poi.cat.nature': 'Natur och parker',
'poi.cat.activities': 'Aktiviteter',
+ 'poi.pluginCategories': 'Kategorier från tillägg',
'map.showAllConnections': 'Visa alla bokningsvägar',
'map.hideAllConnections': 'Dölj alla bokningsvägar',
'map.baseLayer.default': 'Karta',
diff --git a/shared/src/i18n/th/admin.ts b/shared/src/i18n/th/admin.ts
index aa8de921d..3a350655c 100644
--- a/shared/src/i18n/th/admin.ts
+++ b/shared/src/i18n/th/admin.ts
@@ -372,6 +372,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:calendar-source': "จัดให้มีกิจกรรมในปฏิทิน",
'admin.plugins.perm.hook:place-detail-provider': "เพิ่มรายละเอียด (บทวิจารณ์ คะแนน และลิงก์) ให้กับสถานที่",
'admin.plugins.perm.hook:search-provider': 'ตอบการค้นหาสถานที่จากดัชนีของตัวเอง ควบคู่กับผลลัพธ์ของ TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'เพิ่มหมวดหมู่สถานที่ของตัวเองลงใน “สำรวจสถานที่บนแผนที่” เมื่อคุณเลือกหมวดหมู่ใด ปลั๊กอินจะได้รับพื้นที่แผนที่ที่คุณกำลังดูอยู่',
'admin.plugins.perm.hook:trip-warning-provider': "แจ้งเตือนการตรวจสอบความถูกต้องในการเดินทาง (แสดงใน Planner)",
'admin.plugins.perm.hook:table-contributor': "เพิ่มคอลัมน์และการดำเนินการให้กับมุมมองการเดินทาง (การจอง สถานที่ วัน)",
'admin.plugins.perm.hook:map-marker-provider': "เพิ่มเครื่องหมายลงในแผนที่การเดินทาง (เช่น แสดงการจองหรือ POI)",
@@ -385,6 +387,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': "เผยแพร่เครื่องมือ AI",
'admin.plugins.mcpToolsTitle': "เครื่องมือ AI ที่เผยแพร่",
'admin.plugins.mcpToolsHint': "ผู้ช่วยสามารถเรียกใช้สิ่งเหล่านี้ในนามของผู้ใช้ได้ แต่ละคนดำเนินการตามสิทธิ์การเข้าถึงที่ได้รับข้างต้น",
+ 'admin.plugins.poiCategoriesTitle': 'หมวดหมู่แผนที่ที่ปลั๊กอินเพิ่ม',
'admin.plugins.perm.mcp:tools':
"เผยแพร่เครื่องมือที่ผู้ช่วย AI สามารถทำงานในนามของคุณ (จะกระทำกับการเข้าถึงที่คุณให้สิทธิ์ปลั๊กอินที่นี่ ไม่ใช่กับผู้ช่วยเอง)",
'admin.plugins.perm.geolocation:read':
@@ -766,6 +769,7 @@ const admin: TranslationStrings = {
'admin.placeShadow.title': "บันทึกการค้นหาสถานที่",
'admin.placeShadow.subtitle': "บันทึกผลค้นหาที่ถูกเลือก เพื่อวัดดัชนีสถานที่อื่นกับการค้นหาจริงในอนาคต ข้อมูลจะไม่ออกจากอินสแตนซ์นี้ และผู้ดูแลส่งออกหรือลบบันทึกได้ทุกเมื่อ",
'admin.plugins.cap.search': "ตอบการค้นหา",
+ 'admin.plugins.cap.poiCategories': 'เพิ่มหมวดหมู่บนแผนที่',
'admin.addons.catalog.roadtrip.name': "โรดทริป",
'admin.addons.catalog.roadtrip.description': "วางแผนการขับรถด้วยจุดแวะตามเส้นทาง เวลาเดินทาง และเวลาไปถึงที่อัปเดตเอง",
'admin.addons.catalog.dawarich.name': "Dawarich",
diff --git a/shared/src/i18n/th/map.ts b/shared/src/i18n/th/map.ts
index 46a55ea36..4f335fb8a 100644
--- a/shared/src/i18n/th/map.ts
+++ b/shared/src/i18n/th/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': "พิพิธภัณฑ์และวัฒนธรรม",
'poi.cat.nature': "ธรรมชาติและอุทยาน",
'poi.cat.activities': "กิจกรรม",
+ 'poi.pluginCategories': "หมวดหมู่จากปลั๊กอิน",
'map.showAllConnections': "แสดงเส้นทางการจองทั้งหมด",
'map.hideAllConnections': "ซ่อนเส้นทางการจองทั้งหมด",
'map.baseLayer.default': "แผนที่",
diff --git a/shared/src/i18n/tr/admin.ts b/shared/src/i18n/tr/admin.ts
index 6555fccfd..ff7a690b6 100644
--- a/shared/src/i18n/tr/admin.ts
+++ b/shared/src/i18n/tr/admin.ts
@@ -435,6 +435,8 @@ const admin: TranslationStrings = {
'Bir yere ek ayrıntılar (yorumlar, puanlar, bağlantılar) katkıda bulunur',
'admin.plugins.perm.hook:search-provider':
"Yer aramalarını kendi dizininden yanıtlama, TREK'in kendi sonuçlarının yanında",
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Kendi yer kategorilerini “Haritada yerleri keşfet” alanına ekler; birini seçtiğinde eklentiye görüntülediğin harita alanı gönderilir',
'admin.plugins.perm.hook:trip-warning-provider': 'Bir gezide doğrulama uyarıları oluşturur (planlayıcıda gösterilir)',
'admin.plugins.perm.hook:table-contributor':
'Seyahat görünümlerine sütunlar ve eylemler ekler (rezervasyonlar, yerler, günler)',
@@ -450,6 +452,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Yapay zekâ araçları yayımlar',
'admin.plugins.mcpToolsTitle': 'Yayımlanan yapay zekâ araçları',
'admin.plugins.mcpToolsHint': 'Bir asistan bunları kullanıcı adına çalıştırabilir. Her biri yukarıda verilen yetkilerle çalışır.',
+ 'admin.plugins.poiCategoriesTitle': 'Eklediği harita kategorileri',
'admin.plugins.perm.mcp:tools':
'Bir yapay zekâ asistanının sizin adınıza çalıştırabileceği araçlar yayımlamak (burada eklentiye verdiğiniz yetkilerle çalışır, asistanın kendi yetkileriyle değil)',
'admin.plugins.perm.geolocation:read':
@@ -592,6 +595,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Takvim etkinlikleri sağlar',
'admin.plugins.cap.placeDetails': 'Yerleri zenginleştirir',
'admin.plugins.cap.search': 'Aramaları yanıtlar',
+ 'admin.plugins.cap.poiCategories': 'Haritaya kategori ekler',
'admin.plugins.cap.warnings': 'Sorunları işaretler',
'admin.plugins.cap.mapLayers': 'Haritada çizim yapar',
'admin.plugins.cap.routing': 'Rota sunar',
diff --git a/shared/src/i18n/tr/map.ts b/shared/src/i18n/tr/map.ts
index 46e8702ee..7712ee3b3 100644
--- a/shared/src/i18n/tr/map.ts
+++ b/shared/src/i18n/tr/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Müzeler ve kültür',
'poi.cat.nature': 'Doğa ve parklar',
'poi.cat.activities': 'Aktiviteler',
+ 'poi.pluginCategories': 'Eklentilerden gelen kategoriler',
'map.showAllConnections': 'Tüm rezervasyon rotalarını göster',
'map.hideAllConnections': 'Tüm rezervasyon rotalarını gizle',
'map.baseLayer.default': 'Harita',
diff --git a/shared/src/i18n/uk/admin.ts b/shared/src/i18n/uk/admin.ts
index 1d6014889..9498c9aac 100644
--- a/shared/src/i18n/uk/admin.ts
+++ b/shared/src/i18n/uk/admin.ts
@@ -385,6 +385,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:place-detail-provider': 'Додавати додаткові деталі (відгуки, оцінки, посилання) до місця',
'admin.plugins.perm.hook:search-provider':
'Відповідати на пошук місць із власного індексу, поряд із результатами TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Додавати власні категорії місць до «Досліджуйте місця на карті»; коли ви обираєте одну з них, розширення отримує область карти, яку ви переглядаєте',
'admin.plugins.perm.hook:trip-warning-provider':
'Створювати попередження перевірки для подорожі (показуються в планувальнику)',
'admin.plugins.perm.hook:table-contributor': 'Додавати стовпці та дії до подань подорожі (бронювання, місця, дні)',
@@ -400,6 +402,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Публікує ШІ-інструменти',
'admin.plugins.mcpToolsTitle': 'Опубліковані ШІ-інструменти',
'admin.plugins.mcpToolsHint': 'Асистент може запускати їх від імені користувача. Кожен діє з правами, наданими вище.',
+ 'admin.plugins.poiCategoriesTitle': 'Категорії карти, які він додає',
'admin.plugins.perm.mcp:tools':
'Публікувати інструменти, які ШІ-асистент може запускати від вашого імені (він діє з правами, наданими плаґіну тут, а не зі своїми)',
'admin.plugins.perm.geolocation:read':
@@ -543,6 +546,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Надає події календаря',
'admin.plugins.cap.placeDetails': 'Збагачує місця',
'admin.plugins.cap.search': 'Відповідає на пошук',
+ 'admin.plugins.cap.poiCategories': 'Додає категорії на карту',
'admin.plugins.cap.warnings': 'Позначає проблеми',
'admin.plugins.cap.mapLayers': 'Малює на карті',
'admin.plugins.cap.routing': 'Пропонує маршрутизацію',
diff --git a/shared/src/i18n/uk/map.ts b/shared/src/i18n/uk/map.ts
index 7bed81e37..3b0bbfabe 100644
--- a/shared/src/i18n/uk/map.ts
+++ b/shared/src/i18n/uk/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Музеї та культура',
'poi.cat.nature': 'Природа та парки',
'poi.cat.activities': 'Активності',
+ 'poi.pluginCategories': 'Категорії з плагінів',
'map.showAllConnections': 'Показати всі маршрути бронювань',
'map.hideAllConnections': 'Приховати всі маршрути бронювань',
'map.baseLayer.default': 'Карта',
diff --git a/shared/src/i18n/vi/admin.ts b/shared/src/i18n/vi/admin.ts
index 1e60f9114..703175936 100644
--- a/shared/src/i18n/vi/admin.ts
+++ b/shared/src/i18n/vi/admin.ts
@@ -390,6 +390,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:place-detail-provider':
'Đóng góp thêm thông tin chi tiết (đánh giá, xếp hạng, liên kết) cho một địa điểm',
'admin.plugins.perm.hook:search-provider': 'Trả lời tìm kiếm địa điểm từ chỉ mục riêng, bên cạnh kết quả của TREK',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ 'Thêm các danh mục địa điểm riêng vào “Khám phá các địa điểm trên bản đồ”; khi bạn chọn một danh mục, plugin sẽ nhận vùng bản đồ bạn đang xem',
'admin.plugins.perm.hook:trip-warning-provider':
'Đưa ra cảnh báo xác thực trên một chuyến đi (hiển thị trong trình lập kế hoạch)',
'admin.plugins.perm.hook:table-contributor':
@@ -406,6 +408,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': 'Xuất bản công cụ AI',
'admin.plugins.mcpToolsTitle': 'Công cụ AI được xuất bản',
'admin.plugins.mcpToolsHint': 'Trợ lý có thể chạy chúng thay cho người dùng. Mỗi công cụ hoạt động với quyền được cấp ở trên.',
+ 'admin.plugins.poiCategoriesTitle': 'Danh mục bản đồ mà plugin thêm vào',
'admin.plugins.perm.mcp:tools':
'Xuất bản các công cụ mà trợ lý AI có thể chạy thay bạn (nó hoạt động với quyền bạn cấp cho tiện ích tại đây, không phải quyền của trợ lý)',
'admin.plugins.perm.geolocation:read':
@@ -548,6 +551,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': 'Cung cấp sự kiện lịch',
'admin.plugins.cap.placeDetails': 'Làm phong phú địa điểm',
'admin.plugins.cap.search': 'Trả lời tìm kiếm',
+ 'admin.plugins.cap.poiCategories': 'Thêm danh mục bản đồ',
'admin.plugins.cap.warnings': 'Gắn cờ vấn đề',
'admin.plugins.cap.mapLayers': 'Vẽ trên bản đồ',
'admin.plugins.cap.routing': 'Cung cấp định tuyến',
diff --git a/shared/src/i18n/vi/map.ts b/shared/src/i18n/vi/map.ts
index e7bf7890e..e40f4e3d2 100644
--- a/shared/src/i18n/vi/map.ts
+++ b/shared/src/i18n/vi/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': 'Bảo tàng & văn hóa',
'poi.cat.nature': 'Thiên nhiên & công viên',
'poi.cat.activities': 'Các hoạt động',
+ 'poi.pluginCategories': 'Danh mục từ plugin',
'map.showAllConnections': 'Hiển thị tất cả lộ trình đặt chỗ',
'map.hideAllConnections': 'Ẩn tất cả lộ trình đặt chỗ',
'map.baseLayer.default': 'Bản đồ',
diff --git a/shared/src/i18n/zh-TW/admin.ts b/shared/src/i18n/zh-TW/admin.ts
index b21e52d2e..9e1172adc 100644
--- a/shared/src/i18n/zh-TW/admin.ts
+++ b/shared/src/i18n/zh-TW/admin.ts
@@ -397,6 +397,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:calendar-source': '為行事曆提供事件',
'admin.plugins.perm.hook:place-detail-provider': '為地點提供額外資訊(評論、評分、連結)',
'admin.plugins.perm.hook:search-provider': '從自有索引回答地點搜尋,與 TREK 自身的結果並列顯示',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ '在「在地圖上探索地點」加入自己的地點分類(選擇其中一個時,外掛會收到你正在檢視的地圖範圍)',
'admin.plugins.perm.hook:trip-warning-provider': '對行程發出驗證警告(顯示於規劃工具中)',
'admin.plugins.perm.hook:table-contributor': '向行程檢視(預訂、地點、日期)新增欄位與操作',
'admin.plugins.perm.hook:map-marker-provider': '向行程地圖新增標記(例如顯示預訂或興趣點)',
@@ -408,6 +410,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': '發布 AI 工具',
'admin.plugins.mcpToolsTitle': '發布的 AI 工具',
'admin.plugins.mcpToolsHint': '助理可以代用戶執行這些工具。每個工具都以上方授予的權限運作。',
+ 'admin.plugins.poiCategoriesTitle': '新增的地圖分類',
'admin.plugins.perm.mcp:tools':
'發布 AI 助理可以代你執行的工具(它以你在此處授予外掛的權限運作,而非助理自身的權限)',
'admin.plugins.perm.geolocation:read': '在其任一檢視開啟時查詢你的即時位置(由 TREK 使用本站台既有的位置權限讀取,不會另外為外掛詢問)',
@@ -541,6 +544,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': '提供行事曆事件',
'admin.plugins.cap.placeDetails': '豐富地點',
'admin.plugins.cap.search': '回答搜尋',
+ 'admin.plugins.cap.poiCategories': '新增地圖分類',
'admin.plugins.cap.warnings': '標記問題',
'admin.plugins.cap.mapLayers': '在地圖上繪製',
'admin.plugins.cap.routing': '提供路線規劃',
diff --git a/shared/src/i18n/zh-TW/map.ts b/shared/src/i18n/zh-TW/map.ts
index 43811c47b..e6e1abced 100644
--- a/shared/src/i18n/zh-TW/map.ts
+++ b/shared/src/i18n/zh-TW/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': '博物館與文化',
'poi.cat.nature': '自然與公園',
'poi.cat.activities': '活動',
+ 'poi.pluginCategories': '來自外掛的分類',
'map.showAllConnections': '顯示所有預訂路線',
'map.hideAllConnections': '隱藏所有預訂路線',
'map.baseLayer.default': '地圖',
diff --git a/shared/src/i18n/zh/admin.ts b/shared/src/i18n/zh/admin.ts
index 592849387..2873b3ea4 100644
--- a/shared/src/i18n/zh/admin.ts
+++ b/shared/src/i18n/zh/admin.ts
@@ -353,6 +353,8 @@ const admin: TranslationStrings = {
'admin.plugins.perm.hook:calendar-source': '为日历提供事件',
'admin.plugins.perm.hook:place-detail-provider': '为地点补充额外信息(评论、评分、链接)',
'admin.plugins.perm.hook:search-provider': '从自有索引回答地点搜索,与 TREK 自身的结果并列显示',
+ 'admin.plugins.perm.hook:poi-category-provider':
+ '向“在地图上探索地点”添加自己的地点分类(选择其中一个时,插件会收到你正在查看的地图区域)',
'admin.plugins.perm.hook:trip-warning-provider': '对行程发出校验警告(显示在规划器中)',
'admin.plugins.perm.hook:table-contributor': '向行程视图(预订、地点、日期)添加列和操作',
'admin.plugins.perm.hook:map-marker-provider': '向旅行地图添加标记(例如显示预订或兴趣点)',
@@ -363,6 +365,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.mcpTools': '发布 AI 工具',
'admin.plugins.mcpToolsTitle': '发布的 AI 工具',
'admin.plugins.mcpToolsHint': '助手可以代用户运行这些工具。每个工具都以上方授予的权限运行。',
+ 'admin.plugins.poiCategoriesTitle': '添加的地图分类',
'admin.plugins.perm.mcp:tools':
'发布 AI 助手可以代你运行的工具(它以你在此处授予插件的权限运行,而非助手自身的权限)',
'admin.plugins.perm.geolocation:read': '在其某个视图打开时请求你的实时位置(由 TREK 使用本站点已有的位置权限读取,不会单独为插件询问)',
@@ -498,6 +501,7 @@ const admin: TranslationStrings = {
'admin.plugins.cap.calendar': '提供日历事件',
'admin.plugins.cap.placeDetails': '丰富地点信息',
'admin.plugins.cap.search': '回答搜索',
+ 'admin.plugins.cap.poiCategories': '添加地图分类',
'admin.plugins.cap.warnings': '标记问题',
'admin.plugins.cap.mapLayers': '在地图上绘制',
'admin.plugins.cap.routing': '提供路线规划',
diff --git a/shared/src/i18n/zh/map.ts b/shared/src/i18n/zh/map.ts
index fb6f4bd80..3eeb7369b 100644
--- a/shared/src/i18n/zh/map.ts
+++ b/shared/src/i18n/zh/map.ts
@@ -13,6 +13,7 @@ const map: TranslationStrings = {
'poi.cat.museums': '博物馆与文化',
'poi.cat.nature': '自然与公园',
'poi.cat.activities': '活动',
+ 'poi.pluginCategories': '来自插件的分类',
'map.showAllConnections': '显示所有预订路线',
'map.hideAllConnections': '隐藏所有预订路线',
'map.baseLayer.default': '地图',
diff --git a/shared/src/index.ts b/shared/src/index.ts
index 7c4399645..ff3cce564 100644
--- a/shared/src/index.ts
+++ b/shared/src/index.ts
@@ -86,6 +86,9 @@ export * from './i18n/languages';
export * from './plugin-permissions';
// Plugin settings contracts: the settings-field descriptor + admin instance-config wire shapes.
export * from './plugins/plugins.schema';
+// Plugin POI categories (#1781): the declared category, the icon allow-list and GET /api/plugin-pois.
+export * from './plugins/plugin-poi-facts';
+export * from './plugins/plugin-poi.schema';
export * from './roadtrip/preferences.schema';
export * from './roadtrip/hazards.schema';
export * from './roadtrip/planning.schema';
diff --git a/shared/src/plugin-permissions.ts b/shared/src/plugin-permissions.ts
index 90196d967..8780a2b03 100644
--- a/shared/src/plugin-permissions.ts
+++ b/shared/src/plugin-permissions.ts
@@ -1,5 +1,6 @@
// GENERATED — do not edit by hand.
// Source: server/src/nest/plugins/protocol/envelope.ts + server/src/plugin-event-sink.ts
+// + shared/src/plugins/plugin-poi-facts.ts
// Regenerate: node --import tsx server/scripts/gen-plugin-facts.ts
/** Widened on purpose so client callers can .includes() with a plain string. */
@@ -48,6 +49,7 @@ export const PLUGIN_PERMISSIONS: readonly string[] = [
'hook:calendar-source',
'hook:place-detail-provider',
'hook:search-provider',
+ 'hook:poi-category-provider',
'hook:trip-warning-provider',
'hook:table-contributor',
'hook:map-marker-provider',
@@ -76,6 +78,7 @@ export const PLUGIN_HOOK_PERMISSION: Readonly<Record<string, string>> = {
calendarSource: 'hook:calendar-source',
placeDetailProvider: 'hook:place-detail-provider',
searchProvider: 'hook:search-provider',
+ poiCategoryProvider: 'hook:poi-category-provider',
warningProvider: 'hook:trip-warning-provider',
tableContributor: 'hook:table-contributor',
mapMarkerProvider: 'hook:map-marker-provider',
diff --git a/shared/src/plugins/plugin-poi-facts.ts b/shared/src/plugins/plugin-poi-facts.ts
new file mode 100644
index 000000000..50244ea05
--- /dev/null
+++ b/shared/src/plugins/plugin-poi-facts.ts
@@ -0,0 +1,49 @@
+/**
+ * The fixed facts behind a plugin POI category (#1781): which icons one may use and
+ * how many a plugin may declare.
+ *
+ * A file of plain constants with no imports on purpose. Besides the contract in
+ * plugin-poi.schema.ts, server/scripts/gen-plugin-facts.ts reads it and writes the
+ * same values into plugin-sdk/src/generated/host-facts.ts, so `trek-plugin validate`
+ * checks a manifest against the list the host enforces. That script runs in a CI job
+ * with only the server installed, which is why nothing here may pull in zod.
+ */
+
+/**
+ * Lucide icon names a plugin POI category may carry.
+ *
+ * A closed list rather than any lucide name, for two reasons. The pill and the
+ * marker builders resolve the name to a component or an SVG, and a closed list means
+ * a plugin can never make the host import something it did not plan to ship. And the
+ * choice is small on purpose: these are the shapes the use cases need (trails and
+ * trailheads, charging, accessibility, water and toilets, camping, community places).
+ * Lucide 0.344 has no toilet glyph, so Bath stands in for that one.
+ */
+export const PLUGIN_POI_ICONS = [
+ 'Footprints',
+ 'Mountain',
+ 'MountainSnow',
+ 'Signpost',
+ 'Trees',
+ 'TentTree',
+ 'Tent',
+ 'Accessibility',
+ 'Droplet',
+ 'Droplets',
+ 'PlugZap',
+ 'Zap',
+ 'Bath',
+ 'Bike',
+ 'Waves',
+ 'Landmark',
+ 'MapPin',
+ 'Star',
+ 'Heart',
+ 'Info',
+] as const;
+
+/** How many POI categories one plugin may add to the explore pill. */
+export const PLUGIN_POI_MAX_CATEGORIES = 4;
+
+/** Longest category label, in the fallback and in every per-language entry. */
+export const PLUGIN_POI_LABEL_MAX = 40;
diff --git a/shared/src/plugins/plugin-poi.schema.spec.ts b/shared/src/plugins/plugin-poi.schema.spec.ts
new file mode 100644
index 000000000..8f56abd6a
--- /dev/null
+++ b/shared/src/plugins/plugin-poi.schema.spec.ts
@@ -0,0 +1,166 @@
+import { PLUGIN_POI_ICONS } from './plugin-poi-facts';
+import {
+ isPluginPoiColor,
+ isPluginPoiIcon,
+ parsePluginPoiCategoryKey,
+ pluginPoiCategoryKey,
+ pluginPoiCategoryLabel,
+ pluginPoiCategorySchema,
+ pluginPoiQuerySchema,
+ pluginPoiResponseSchema,
+ pluginPoiSchema,
+} from './plugin-poi.schema';
+
+import { describe, expect, it } from 'vitest';
+
+/**
+ * Plugin POI categories (#1781). The declared category is what the explore pill
+ * renders from, and its colour and icon end up inside marker markup, so the spec
+ * pins exactly what gets through: nothing but `#rrggbb` and a name on the list.
+ */
+const category = { id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' };
+
+describe('pluginPoiCategorySchema', () => {
+ it('PLUGPOI-SH-001: accepts a declared category with per-language labels', () => {
+ const parsed = pluginPoiCategorySchema.parse({
+ ...category,
+ labels: { de: 'Wanderparkplätze', 'zh-TW': '登山口' },
+ });
+ expect(parsed.labels).toEqual({ de: 'Wanderparkplätze', 'zh-TW': '登山口' });
+ });
+
+ it('PLUGPOI-SH-002: refuses a colour that is not #rrggbb', () => {
+ for (const color of ['red', '#fff', '#2f855a;background:url(x)', 'url(https://x)', '#2F855AFF', '']) {
+ expect(pluginPoiCategorySchema.safeParse({ ...category, color }).success).toBe(false);
+ }
+ expect(pluginPoiCategorySchema.safeParse({ ...category, color: '#2F855A' }).success).toBe(true);
+ });
+
+ it('PLUGPOI-SH-003: refuses an icon off the allow-list and a malformed id or label', () => {
+ expect(pluginPoiCategorySchema.safeParse({ ...category, icon: 'Toilet' }).success).toBe(false);
+ expect(pluginPoiCategorySchema.safeParse({ ...category, icon: 'Blocks' }).success).toBe(false);
+ expect(pluginPoiCategorySchema.safeParse({ ...category, id: 'Trail' }).success).toBe(false);
+ expect(pluginPoiCategorySchema.safeParse({ ...category, id: 'a'.repeat(25) }).success).toBe(false);
+ expect(pluginPoiCategorySchema.safeParse({ ...category, label: ' ' }).success).toBe(false);
+ expect(pluginPoiCategorySchema.safeParse({ ...category, label: 'x'.repeat(41) }).success).toBe(false);
+ });
+
+ it('PLUGPOI-SH-004: refuses a label keyed by a language TREK does not have', () => {
+ expect(pluginPoiCategorySchema.safeParse({ ...category, labels: { xx: 'Nope' } }).success).toBe(false);
+ expect(pluginPoiCategorySchema.safeParse({ ...category, labels: { de: '' } }).success).toBe(false);
+ });
+});
+
+describe('plugin POI helpers', () => {
+ it('PLUGPOI-SH-005: the icon and colour guards agree with the schema', () => {
+ for (const icon of PLUGIN_POI_ICONS) expect(isPluginPoiIcon(icon)).toBe(true);
+ expect(isPluginPoiIcon('Toilet')).toBe(false);
+ expect(isPluginPoiIcon(42)).toBe(false);
+ expect(isPluginPoiColor('#00ff00')).toBe(true);
+ expect(isPluginPoiColor('#00ff00 ')).toBe(false);
+ expect(isPluginPoiColor(null)).toBe(false);
+ });
+
+ it('PLUGPOI-SH-006: the label follows the language and falls back to the default', () => {
+ const c = { label: 'Trailheads', labels: { de: 'Wanderparkplätze' } };
+ expect(pluginPoiCategoryLabel(c, 'de')).toBe('Wanderparkplätze');
+ expect(pluginPoiCategoryLabel(c, 'fr')).toBe('Trailheads');
+ expect(pluginPoiCategoryLabel({ label: 'Trailheads' }, 'de')).toBe('Trailheads');
+ // An inherited property is not a label.
+ expect(pluginPoiCategoryLabel(c, 'toString')).toBe('Trailheads');
+ });
+
+ it('PLUGPOI-SH-007: a category key round-trips and nothing else parses as one', () => {
+ const key = pluginPoiCategoryKey('trail-finder', 'trailheads');
+ expect(key).toBe('plugin:trail-finder/trailheads');
+ expect(parsePluginPoiCategoryKey(key)).toEqual({ pluginId: 'trail-finder', categoryId: 'trailheads' });
+ for (const bad of [
+ 'restaurant',
+ 'plugin:trail-finder',
+ 'plugin:trail-finder:x',
+ 'plugin:TF/x',
+ 'plugin:trail-finder/../x',
+ 'plugin:ab/x',
+ ]) {
+ expect(parsePluginPoiCategoryKey(bad)).toBeNull();
+ }
+ });
+});
+
+describe('pluginPoiQuerySchema', () => {
+ const query = {
+ pluginId: 'trail-finder',
+ category: 'trailheads',
+ south: '47.1',
+ west: '11.2',
+ north: '47.3',
+ east: '11.5',
+ };
+
+ it('PLUGPOI-SH-008: coerces the bbox and keeps an unwrapped longitude', () => {
+ expect(pluginPoiQuerySchema.parse(query)).toEqual({ ...query, south: 47.1, west: 11.2, north: 47.3, east: 11.5 });
+ expect(pluginPoiQuerySchema.parse({ ...query, west: '179.8', east: '180.3' }).east).toBe(180.3);
+ });
+
+ it('PLUGPOI-SH-009: refuses a blank, non-numeric, inverted or off-globe bbox', () => {
+ for (const over of [
+ { south: '' },
+ { north: 'abc' },
+ { south: '48', north: '47' },
+ { west: '12', east: '11' },
+ { north: '91' },
+ { east: 'Infinity' },
+ ]) {
+ expect(pluginPoiQuerySchema.safeParse({ ...query, ...over }).success).toBe(false);
+ }
+ });
+
+ it('PLUGPOI-SH-010: refuses a malformed plugin or category id and an overlong lang', () => {
+ expect(pluginPoiQuerySchema.safeParse({ ...query, pluginId: '../x' }).success).toBe(false);
+ expect(pluginPoiQuerySchema.safeParse({ ...query, category: 'Trail heads' }).success).toBe(false);
+ expect(pluginPoiQuerySchema.safeParse({ ...query, lang: 'x'.repeat(36) }).success).toBe(false);
+ expect(pluginPoiQuerySchema.safeParse({ ...query, lang: 'de' }).success).toBe(true);
+ });
+});
+
+describe('pluginPoiResponseSchema', () => {
+ const poi = {
+ osm_id: 'plugin:trail-finder:th-1',
+ name: 'Trailhead',
+ lat: 47.2,
+ lng: 11.3,
+ category: 'plugin:trail-finder/trailheads',
+ poi_type: 'plugin:trail-finder/trailheads',
+ address: null,
+ website: 'https://example.test/th-1',
+ phone: null,
+ opening_hours: null,
+ cuisine: null,
+ brand: null,
+ brand_wikidata: null,
+ charging: null,
+ source: 'plugin:trail-finder',
+ pluginId: 'trail-finder',
+ rating: 4.5,
+ details: [{ label: 'Length', value: '12 km' }],
+ icon: 'Signpost',
+ color: '#2f855a',
+ };
+
+ it('PLUGPOI-SH-011: accepts the row the server builds', () => {
+ expect(
+ pluginPoiResponseSchema.parse({ pois: [poi], source: 'plugin:trail-finder', truncated: false, clamped: true })
+ .pois,
+ ).toHaveLength(1);
+ });
+
+ it('PLUGPOI-SH-012: pins the caps: rating range, seven details, an off-list icon', () => {
+ expect(pluginPoiSchema.safeParse({ ...poi, rating: 6 }).success).toBe(false);
+ expect(
+ pluginPoiSchema.safeParse({ ...poi, details: Array.from({ length: 7 }, () => ({ label: 'a', value: 'b' })) })
+ .success,
+ ).toBe(false);
+ expect(pluginPoiSchema.safeParse({ ...poi, icon: 'Skull' }).success).toBe(false);
+ expect(pluginPoiSchema.safeParse({ ...poi, opening_hours: 'Mo-Fr 09:00-17:00' }).success).toBe(false);
+ });
+});
diff --git a/shared/src/plugins/plugin-poi.schema.ts b/shared/src/plugins/plugin-poi.schema.ts
new file mode 100644
index 000000000..ff11d32e0
--- /dev/null
+++ b/shared/src/plugins/plugin-poi.schema.ts
@@ -0,0 +1,188 @@
+import { SUPPORTED_LANGUAGE_CODES } from '../i18n/languages';
+import { PLUGIN_POI_ICONS, PLUGIN_POI_LABEL_MAX } from './plugin-poi-facts';
+
+import { z } from 'zod';
+
+/**
+ * Plugin POI categories (#1781): a plugin adds its own chips to the trip map's
+ * "Explore places" pill and answers the searches for them.
+ *
+ * Three wire shapes live here. The declared category is what GET /api/plugins hands
+ * the client for every active plugin holding `hook:poi-category-provider`. The query
+ * and the response are GET /api/plugin-pois, the route the client calls when one of
+ * those chips is active. The response POI is the same row /api/maps/pois returns, so
+ * the map draws a plugin POI through the code path a core one takes, plus the fields
+ * only a plugin answer has (its details list, the category's icon and colour).
+ */
+
+/** A category id as the manifest declares it. Same shape as a route profile id. */
+export const PLUGIN_POI_CATEGORY_ID_RE = /^[a-z][a-z0-9-]{0,23}$/;
+/** A plugin id, as the manifest parser accepts it. */
+export const PLUGIN_POI_PLUGIN_ID_RE = /^[a-z][a-z0-9-]{2,39}$/;
+/**
+ * A category colour. Only `#rrggbb`, because the client writes it into marker
+ * markup and a CSS background: anything looser (`url(...)`, a second declaration
+ * after a semicolon) would let a plugin restyle the map or turn every viewer into a
+ * beacon for its own server.
+ */
+export const PLUGIN_POI_COLOR_RE = /^#[0-9a-fA-F]{6}$/;
+
+/** Most POIs one plugin answer may carry, the same share a core category gets. */
+export const PLUGIN_POI_HIT_CAP = 60;
+/** Most detail rows one POI may carry, and the length of each half. */
+export const PLUGIN_POI_DETAILS_MAX = 6;
+export const PLUGIN_POI_DETAIL_LABEL_MAX = 40;
+export const PLUGIN_POI_DETAIL_VALUE_MAX = 120;
+
+export type PluginPoiIcon = (typeof PLUGIN_POI_ICONS)[number];
+
+const LANGUAGE_CODES: ReadonlySet<string> = new Set(SUPPORTED_LANGUAGE_CODES);
+const ICONS: ReadonlySet<string> = new Set(PLUGIN_POI_ICONS);
+
+export function isPluginPoiIcon(value: unknown): value is PluginPoiIcon {
+ return typeof value === 'string' && ICONS.has(value);
+}
+
+export function isPluginPoiColor(value: unknown): value is string {
+ return typeof value === 'string' && PLUGIN_POI_COLOR_RE.test(value);
+}
+
+const categoryLabel = z.string().trim().min(1).max(PLUGIN_POI_LABEL_MAX);
+
+/** One category a plugin declared, as the feed serves it after re-validation. */
+export const pluginPoiCategorySchema = z.object({
+ id: z.string().regex(PLUGIN_POI_CATEGORY_ID_RE),
+ /** Shown when `labels` has nothing for the user's language. Plain text, never a key. */
+ label: categoryLabel,
+ /** Per-language labels keyed by TREK language code (`de`, `zh-TW`, ...). */
+ labels: z
+ .record(
+ z.string().refine((code) => LANGUAGE_CODES.has(code)),
+ categoryLabel,
+ )
+ .optional(),
+ icon: z.enum(PLUGIN_POI_ICONS),
+ color: z.string().regex(PLUGIN_POI_COLOR_RE),
+});
+export type PluginPoiCategory = z.infer<typeof pluginPoiCategorySchema>;
+
+/** The label to show for `language`, falling back to the plugin's own default. */
+export function pluginPoiCategoryLabel(
+ category: Pick<PluginPoiCategory, 'label' | 'labels'>,
+ language: string,
+): string {
+ // Own keys only, so an inherited name such as `toString` never reads as a label.
+ // Object.entries rather than Object.hasOwn because the client compiles this file
+ // against an ES2020 lib, where Object.hasOwn does not exist.
+ const localized = Object.entries(category.labels ?? {}).find(([code]) => code === language)?.[1];
+ return localized ?? category.label;
+}
+
+/**
+ * The pill key of a plugin category. The `plugin:` prefix and the slash keep it apart
+ * from every core key and from every other plugin's, which matters because the key
+ * doubles as the marker cache key and the explore state key on the client.
+ */
+export function pluginPoiCategoryKey(pluginId: string, categoryId: string): string {
+ return `plugin:${pluginId}/${categoryId}`;
+}
+
+/** The inverse of pluginPoiCategoryKey; null for anything that is not one. */
+export function parsePluginPoiCategoryKey(key: string): { pluginId: string; categoryId: string } | null {
+ if (!key.startsWith('plugin:')) return null;
+ const rest = key.slice('plugin:'.length);
+ const slash = rest.indexOf('/');
+ if (slash < 0) return null;
+ const pluginId = rest.slice(0, slash);
+ const categoryId = rest.slice(slash + 1);
+ if (!PLUGIN_POI_PLUGIN_ID_RE.test(pluginId) || !PLUGIN_POI_CATEGORY_ID_RE.test(categoryId)) return null;
+ return { pluginId, categoryId };
+}
+
+/**
+ * A bbox whose edges are the right way round. Shared by the query schema and the
+ * MCP tool, which takes the same box as numbers.
+ */
+export function isOrderedPoiBbox(b: { south: number; west: number; north: number; east: number }): boolean {
+ return b.south <= b.north && b.west <= b.east;
+}
+
+// Query values arrive as strings. A blank one is missing, not zero: Number('') is 0,
+// and a bbox edge silently read as the equator would search the wrong continent.
+const queryNumber = z.string().trim().min(1).pipe(z.coerce.number());
+
+/**
+ * GET /api/plugin-pois query. Latitudes must be real ones; longitudes may run past
+ * the antimeridian, because a map that has been panned round the globe reports its
+ * edges unwrapped and the server folds the window back itself.
+ */
+export const pluginPoiQuerySchema = z
+ .object({
+ pluginId: z.string().regex(PLUGIN_POI_PLUGIN_ID_RE),
+ category: z.string().regex(PLUGIN_POI_CATEGORY_ID_RE),
+ south: queryNumber.pipe(z.number().min(-90).max(90)),
+ west: queryNumber,
+ north: queryNumber.pipe(z.number().min(-90).max(90)),
+ east: queryNumber,
+ lang: z.string().max(35).optional(),
+ })
+ // The edges are picked out rather than the object handed over whole: the client
+ // compiles this file without strict mode, where zod types the piped edges as
+ // optional keys and the whole object would not fit isOrderedPoiBbox's parameter.
+ .refine(({ south, west, north, east }) => isOrderedPoiBbox({ south, west, north, east }), {
+ message: 'Invalid bbox',
+ path: ['bbox'],
+ });
+export type PluginPoiQueryInput = z.input<typeof pluginPoiQuerySchema>;
+export type PluginPoiQuery = z.output<typeof pluginPoiQuerySchema>;
+
+/** One row of what a plugin knows that open data does not (trail length, step-free). */
+export const pluginPoiDetailSchema = z.object({
+ label: z.string().min(1).max(PLUGIN_POI_DETAIL_LABEL_MAX),
+ value: z.string().min(1).max(PLUGIN_POI_DETAIL_VALUE_MAX),
+});
+export type PluginPoiDetail = z.infer<typeof pluginPoiDetailSchema>;
+
+/**
+ * One POI a plugin answered, in the row shape of GET /api/maps/pois. The OSM-only
+ * fields are always null: a plugin answer has no opening-hours tag or brand id, and
+ * saying so keeps the client from reading a plugin row as a thin OSM one.
+ */
+export const pluginPoiSchema = z.object({
+ /** `plugin:<pluginId>:<id>`, so it can never collide with an OSM or index id. */
+ osm_id: z.string(),
+ name: z.string(),
+ lat: z.number(),
+ lng: z.number(),
+ /** The pill key, `plugin:<pluginId>/<categoryId>`. */
+ category: z.string(),
+ poi_type: z.string(),
+ address: z.string().nullable(),
+ website: z.string().nullable(),
+ phone: z.string().nullable(),
+ opening_hours: z.null(),
+ cuisine: z.null(),
+ brand: z.null(),
+ brand_wikidata: z.null(),
+ charging: z.null(),
+ /** `plugin:<pluginId>`. */
+ source: z.string(),
+ pluginId: z.string(),
+ rating: z.number().min(0).max(5).nullable(),
+ details: z.array(pluginPoiDetailSchema).max(PLUGIN_POI_DETAILS_MAX),
+ /** The declaring category's icon and colour, already checked against the allow-list. */
+ icon: z.enum(PLUGIN_POI_ICONS),
+ color: z.string().regex(PLUGIN_POI_COLOR_RE),
+});
+export type PluginPoi = z.infer<typeof pluginPoiSchema>;
+
+export const pluginPoiResponseSchema = z.object({
+ pois: z.array(pluginPoiSchema).max(PLUGIN_POI_HIT_CAP),
+ /** `plugin:<pluginId>`, the attribution the core route reports as `openstreetmap`. */
+ source: z.string(),
+ /** The plugin answered more than the cap, or more than the host would read. */
+ truncated: z.boolean(),
+ /** The viewport was larger than a search window and was narrowed to its centre. */
+ clamped: z.boolean(),
+});
+export type PluginPoiResponse = z.infer<typeof pluginPoiResponseSchema>;
diff --git a/wiki/Admin-Plugins.md b/wiki/Admin-Plugins.md
index d94717968..5773d108b 100644
--- a/wiki/Admin-Plugins.md
+++ b/wiki/Admin-Plugins.md
@@ -38,6 +38,7 @@ A newly installed plugin is **off**. Nothing runs until you enable it.
Before installing, read these sections:
- **What it can access** — a plain-language summary of what the plugin's permissions let it do ("Reads your trips", "Edits places", "Provides photos"), plus a line for its own isolated database. It is a summary, not the raw permission list: permissions TREK has no summary line for — `notify:send`, `ai:invoke`, `jobs:run`, `db:write:members` and others — do not appear here at all, and a plugin that asks only for those still reads *Needs no special access.* For the complete list, read the manifest in the plugin's source repository. Only the consent dialog for an update renders permissions code by code, unknown codes verbatim.
+- **Map categories it adds**: for a plugin that asks for `hook:poi-category-provider`, each button it would add to the category row on the trip map (see [Places and Search](Places-and-Search#categories-from-plugins)), with its icon on its colour and its name in your language. The access list above reads *Adds map categories* for the same permission, and so does a chip on the plugin's row once it is installed. A plugin that declares categories without asking for the permission shows no list, because its buttons would never appear. The consent dialog of an update that adds the permission spells out what it shares: *Add its own place categories to Explore places on the map; picking one sends the plugin the map area you are viewing.*
- **Connects to** — every host the manifest declares it may reach, as monospace chips.
- **Setup** — settings the plugin will ask you (or each user) to fill in, tagged **Instance-wide** or **Per user**, and **Required** where applicable.
- **Details** — version, size, the TREK version range it requires, when it was reviewed, and total downloads.
diff --git a/wiki/Display-Settings.md b/wiki/Display-Settings.md
index 026bdc497..a00ff987d 100644
--- a/wiki/Display-Settings.md
+++ b/wiki/Display-Settings.md
@@ -113,7 +113,7 @@ Shows or hides station / airport names on the endpoint markers of booking routes
## Explore places on the map
-Shows a row of category buttons on the trip map for finding nearby restaurants, accommodation, sights and more. TREK's own place index answers first and OpenStreetMap fills in; see [Exploring the map by category](Places-and-Search#exploring-the-map-by-category). Set to **On** or **Off**.
+Shows a row of category buttons on the trip map for finding nearby restaurants, accommodation, sights and more. TREK's own place index answers first and OpenStreetMap fills in, and installed plugins can add buttons of their own; see [Exploring the map by category](Places-and-Search#exploring-the-map-by-category). Set to **On** or **Off**.
## Always show booking routes
diff --git a/wiki/MCP-Tools-and-Resources.md b/wiki/MCP-Tools-and-Resources.md
index 27ae8bcd0..95bea775e 100644
--- a/wiki/MCP-Tools-and-Resources.md
+++ b/wiki/MCP-Tools-and-Resources.md
@@ -182,6 +182,8 @@ Requires `places:read` or `places:write` scope.
| `reverse_geocode` | `geo:read` | Get a human-readable address for given coordinates. |
| `resolve_maps_url` | `geo:read` | Resolve a Google Maps or Amap (高德地图) share URL to coordinates and place name. |
| `search_pois` | `geo:read` | List places of one or more categories inside a map rectangle, the MCP side of the category buttons on the trip map. Answers from TREK's place index where it can and from OpenStreetMap (Overpass) otherwise, names the source of each result, and never calls Google. |
+| `list_plugin_poi_categories` | `geo:read` | List the extra categories installed plugins add to the category buttons on the trip map (trailheads, EV chargers, step-free places, drinking water, campsites and the like), each with the `pluginId` and category `id` that `search_plugin_pois` takes and its label in the requested `lang`. Empty when no plugin adds categories, which is the normal case. |
+| `search_plugin_pois` | `geo:read` | List the places of one plugin category inside a map rectangle, the MCP side of a plugin's category button. Takes `pluginId`, `category`, a `bbox` (narrowed to a centred 0.5 degree window when larger, reported as `clamped`) and an optional `lang`. Results have the `search_pois` shape plus the answering `pluginId`, a `rating` where the plugin has one and up to six `details` rows (label and value) only that plugin knows. An unknown category or a failing plugin is an error result. Never calls Google. |
| `search_airports` | `geo:read` | Search for airports by name, city, or IATA code. Returns IATA code, name, city, country, timezone. |
| `get_airport` | `geo:read` | Look up an airport by IATA code (e.g. `"ZRH"`, `"CDG"`). |
| `get_weather` | `weather:read` | Get a weather forecast for a location and date. |
diff --git a/wiki/Places-and-Search.md b/wiki/Places-and-Search.md
index c3d7e7ad5..87afefedf 100644
--- a/wiki/Places-and-Search.md
+++ b/wiki/Places-and-Search.md
@@ -141,6 +141,28 @@ With **Explore places on the map** switched on in [Display Settings](Display-Set
The TREK API answers these first, from the map centre out to a radius that covers the view, at most 20 km. When it has nothing for the area, or cannot be reached, the public Overpass mirrors of OpenStreetMap answer instead, narrowed to a window of half a degree around the centre; `OVERPASS_URL` and `OVERPASS_TIMEOUT_MS` on [Environment Variables](Environment-Variables) steer those. Results from the TREK API come with address, website, phone and opening hours where the index has them, under the names used on the spot rather than translations. The [Road trip](Road-Trip#search-along-the-route) search along the drive asks the same two sources.
+### Categories from plugins
+
+An installed [plugin](Plugins) can add up to four buttons of its own to the row: trailheads, EV chargers, step-free places, public toilets and drinking water, campsites, or a community's own list of places. They come after the built-in buttons, behind a thin divider. When the row holds more buttons than it has room for, it scrolls sideways instead of shrinking them, on the phone as on the desktop.
+
+A plugin's buttons are there while the plugin is switched on and the admin has granted it the permission to add map categories (`hook:poi-category-provider`, see [Plugin Permissions](Plugin-Permissions)). Like the built-in ones they show only an icon, and a picked one fills with the plugin's colour. Rest the pointer on one for its name: in your language when the plugin ships a name for it, otherwise in the plugin's own wording.
+
+A plugin button works like a built-in one: one category at a time, and **Search this area** after you move the map. Only the plugin that added the button is asked, for the part of the map you are looking at, narrowed to the same half-degree window as OpenStreetMap, and at most 60 of its places are shown. The request carries that area, the category and your language, and names no trip. The plugin answers as you, so it can follow your own settings for it, and TREK keeps no copy of the answer. A plugin that takes longer than eight seconds, or fails, gets a red dot on its button and a **Search this area** to try again. The built-in buttons never wait for it.
+
+Plugin categories need a connection. Offline, or with **Force offline mode** on, TREK does not ask the plugin at all: a picked button shows the red dot, and **Search this area** tries again once you are back online. See [Offline Mode and PWA](Offline-Mode-and-PWA).
+
+The markers carry the icon and colour the plugin chose for the category. On the desktop, resting the pointer on a marker shows the place's name and, where the plugin sends them, up to six rows only it knows, such as a trail's length or a step-free entrance. They are always shown as plain text. The phone has no hover, so it does not show these rows.
+
+Clicking or tapping a marker opens the place form with the name, address, website, phone and coordinates filled in, the same as for a marker from a built-in button, for anyone allowed to edit places. A website only comes along when it is an http or https address. Once saved it is an ordinary place of the trip, and it stays when the plugin goes.
+
+When the admin switches a plugin off, uninstalls it or takes the permission away, its buttons disappear, and their markers with them: for the admin straight away, for everyone else the next time TREK loads, or as soon as they press one.
+
+> **Admin:** the Plugins panel marks a plugin that asks for the permission with an **Adds map categories** chip, and a registry plugin's detail lists the categories it would add, with their icons, colours and names, before you install it. See [Admin-Plugins](Admin-Plugins#the-pre-install-review-dialog).
+
+> **AI / MCP:** `list_plugin_poi_categories` names the categories plugins add, and `search_plugin_pois` asks the plugin behind one of them for its places in a map rectangle; see [MCP-Tools-and-Resources](MCP-Tools-and-Resources).
+
+To build such a plugin, see [Plugin Cookbook](Plugin-Cookbook#add-your-own-place-categories-to-the-map).
+
## Searching offline
When a trip is kept for offline use, TREK also downloads the places around it from the TREK API: one request of up to 3000 places, in a box around the trip's places with some margin, at most 1.5 degrees a side (a trip spread wider gets its centre). For a city the size of Rostock that is about a megabyte. The download is repeated only when the trip's area changes, and it happens whether or not **Store map tiles offline** is on: the tiles are the big part, the places are not.
diff --git a/wiki/Plugin-Cookbook.md b/wiki/Plugin-Cookbook.md
index 2b60176c8..d2900a8b1 100644
--- a/wiki/Plugin-Cookbook.md
+++ b/wiki/Plugin-Cookbook.md
@@ -148,6 +148,72 @@ outside `bounds` are dropped, and so is a hit whose own `category` names a diffe
of those seven kinds. Both fields are absent on ordinary searches, so read them as
optional.
+## Add your own place categories to the map
+
+**Needs:** `hook:poi-category-provider` and `capabilities.poiCategories` (+
+`http:outbound:<host>` and a matching `egress` when the data lives on somebody else's
+server)
+
+The trip map has a row of category buttons (restaurants, sights, museums and so on).
+Declare up to four of your own and they appear after the built-in ones, behind a thin
+divider: trailheads, EV chargers, step-free places, drinking water, campsites, a
+community's own list. When somebody picks one, TREK asks your plugin, and only yours,
+for the places in the part of the map they are looking at.
+
+```json
+"permissions": ["hook:poi-category-provider", "http:outbound:api.example-trails.org"],
+"egress": ["api.example-trails.org"],
+"capabilities": {
+ "poiCategories": [
+ { "id": "trailheads", "label": "Trailheads",
+ "labels": { "de": "Wanderparkplätze", "fr": "Départs de randonnée" },
+ "icon": "Signpost", "color": "#2f855a" }
+ ]
+}
+```
+
+```js
+hooks: {
+ poiCategoryProvider: {
+ async getPois({ category, bounds, lang, limit }, ctx) {
+ // category is one of your declared ids, bounds is { south, west, north, east }
+ const { south, west, north, east } = bounds
+ const res = await fetch(
+ `https://api.example-trails.org/${category}?bbox=${west},${south},${east},${north}&n=${limit}&lang=${lang ?? 'en'}`,
+ )
+ const { items } = await res.json()
+ return items.map(t => ({
+ id: t.ref, // namespaced host-side to plugin:<yourId>:<ref>
+ name: t.name,
+ lat: t.lat,
+ lng: t.lon,
+ website: t.url, // http/https only
+ details: [ // at most 6 rows, label 40 and value 120 characters
+ { label: 'Length', value: `${t.km} km` },
+ { label: 'Surface', value: t.surface },
+ ],
+ }))
+ },
+ },
+},
+```
+
+`icon` is one of a fixed list of lucide names (`POI_CATEGORY_ICONS` in the SDK) and
+`color` is `#rrggbb` only. The button and every marker use exactly those, whatever your
+answer says. The button is named `labels[<user's language>]` when you ship one, `label`
+otherwise.
+
+`bounds` is the viewport, narrowed to at most 0.5 degrees a side. The host keeps at most
+60 places inside it, caps every string and gives you 8 seconds; a timeout or a throw
+puts an error dot on your button only, and the built-in buttons never wait for it. You
+are called when somebody picks the button or presses **Search this area**, never on a
+pan. The hook runs as that user, so `ctx.settings.get(key)` reads their own settings (a
+wheelchair profile, say), and nothing is cached. The `details` rows show in the marker's
+hover card on the desktop, and a click on a marker opens the place form filled in from
+your answer. A declaration without the permission still installs, but no button ever
+appears; `trek-plugin validate` tells you. The full contract is under
+[Provider hooks](Plugin-Development#provider-hooks).
+
## Raise validation warnings on a trip
**Needs:** `hook:trip-warning-provider`
diff --git a/wiki/Plugin-Development.md b/wiki/Plugin-Development.md
index 0bc7fb1a5..526a3706d 100644
--- a/wiki/Plugin-Development.md
+++ b/wiki/Plugin-Development.md
@@ -810,6 +810,7 @@ module.exports = definePlugin({
|---|---|---|
| `placeDetailProvider.getDetails(placeId, ctx)` → `{ label, value?, url? }[]` | `hook:place-detail-provider` | **live** — shown in the place-detail panel; also `GET /api/place-details/:placeId` |
| `searchProvider.search(request, ctx)` → `SearchResultPlace[]` | `hook:search-provider` | **live** — answers place searches from an index TREK does not ship, drawn into the app's own search list beside the core results (#2221). `request` is `{query, limit, lang?, near?, category?, bounds?}`; each place is `{id?, name, lat, lng, address?, rating?, website?, phone?, category?, description?}`. `rating` is the field open data cannot answer — OpenStreetMap carries none — so it is what makes "the best rated one around here" answerable at all; it is clamped to 0..5. Coordinates are range-checked, strings capped, `website` must be http/https, and ids are namespaced to `plugin:<yourId>:<id>` so they can never collide with an OSM one. Called for an explicit search, **not** per keystroke. The Road trip search along the route calls it too, once per kind the person picked, with `category` (`fuel`, `charging`, `rest_area`, `campsite`, `restaurant`, `sights` or `hotel`) and `bounds` (`{south, west, north, east}`, with `near` at its centre); `query` is then a fixed English phrase for that kind such as `fuel station` or `EV charging station`. The host drops every hit outside `bounds`, and a hit whose own `category` names a different one of those seven kinds; the rest count as the requested kind. Both fields are absent on ordinary searches. Also `GET /api/plugin-search`, and to a connected assistant as the `search_places_via_plugins` MCP tool; the corridor search is `POST /api/roadtrip/search-area` and the `search_roadtrip_corridor` MCP tool |
+| `poiCategoryProvider.getPois(request, ctx)` → `PoiCategoryPlace[]` | `hook:poi-category-provider` | **live**: answers the chips your plugin adds to the trip map's **Explore places** pill (#1781): trailheads, EV chargers, step-free places, toilets and drinking water, campsites, community places. Declare up to four in [`capabilities.poiCategories`](#manifest-reference-trek-pluginjson). `request` is `{category, bounds, lang?, limit}`: `category` is one of your own declared ids (the host never sends another), `bounds` is `{south, west, north, east}`, the viewport narrowed to a centred window of at most 0.5 degrees a side (the same window the OpenStreetMap categories use) and folded onto -180..180, `limit` is 60. Each place is `{id?, name, lat, lng, address?, website?, phone?, rating?, details?}` where `details` is up to 6 `{label, value}` rows only your index knows (a trail length, a step-free entrance), label ≤40 and value ≤120 chars, flattened to one line and emoji-stripped. The rows show as plain text in the marker's hover card on the desktop; `rating` (0..5) is not drawn on the map and reaches a connected assistant only. A click on a marker opens the place form with the name, address, website, phone and coordinates filled in, and the saved place keeps `plugin:<yourId>:<id>` as its `osm_id`, which TREK never mistakes for a Google place id. The host keeps places inside `bounds` only, at most 60 (a longer answer is reported as `truncated`), namespaces ids to `plugin:<yourId>:<id>`, checks `website` like the search provider does, and draws every place with **your declared** icon and colour, whatever the answer says. **Targeted, not a fan-out**: TREK asks exactly the plugin whose chip the user picked, as that user (so `ctx.settings.get()` is theirs), with an 8 s timeout; a timeout, a thrown error or an answer that is not an array turns into a `502` for that chip only, and the core categories never wait on it. Called when the user picks the chip or asks to search the area again, not on every pan. Nothing is cached. Also `GET /api/plugin-pois?pluginId=&category=&south=&west=&north=&east=&lang=`, and to a connected assistant as the `list_plugin_poi_categories` and `search_plugin_pois` MCP tools |
| `warningProvider.getWarnings(tripId, ctx)` → `{ level, message, dayId?, placeId? }[]` | `hook:trip-warning-provider` | **live** — validation warnings shown as a non-blocking banner in the trip planner; also `GET /api/trip-warnings/:tripId`, and to a connected assistant as the `get_trip_warnings` MCP tool (≤20 warnings per provider, message ≤300 chars) — that path needs only the trips read scope, not `plugins:use` |
| `tableContributor.getContributions(view, tripId, ctx)` → `TableContribution[]` | `hook:table-contributor` | **live** — host-rendered **columns/actions** keyed by `entityId` in the reservations, transports, places, day, costs, packing, files and todos views. A `column` is `{kind:'column', entityId, id, label, value?, url?, icon?, tone?}` (url is http/https/mailto only); an `action` is `{kind:'action', entityId, id, label, icon?, target}` where `target` opens your sandboxed frame (`{kind:'frame', sub}`) or calls a route (`{kind:'route', method, sub}`). All fields are bounded + normalized host-side; also `GET /api/view-contributions/:view/:tripId` |
| `mapMarkerProvider.getMarkers(tripId, ctx)` → `MapMarkerContribution[]` | `hook:map-marker-provider` | **live** — bounded markers overlaid on the trip map (#587). Each is `{id, lat, lng, label?, popupText?, url?, icon?, tone?}`; coordinates are range-checked (−90..90 / −180..180), text length-capped, url http/https/mailto-only, count capped (≤200/plugin). Declarative only — plugin JS never runs on the map canvas. Also `GET /api/map-markers/:tripId` |
@@ -1412,6 +1413,7 @@ both scopes get the acting-user ctx, exactly as the host gives both the clicker'
| `operatorEgress` | boolean | The plugin talks to a **self-hosted** service whose hostname only the operator knows. The admin adds the real hosts after install (Admin → Plugins → Allowed hosts) and the runtime unions them into the egress allow-list. Requires an `http:outbound` permission, and is the only way to declare one with an empty `egress[]`. See [Operator-supplied egress hosts](#operator-supplied-egress-hosts-operatoregress). |
| `capabilities.notificationChannel` | object | `{ title?, events? }` for a plugin implementing the `notificationChannel` hook — `title` names the column in the notification preferences matrix (default: the plugin's `name`), `events` **narrows** which events the channel carries (default: all ten plugin-deliverable events; `events` may only narrow that set). Requires the `hook:notification-channel` permission. See [Notification channels](#notification-channels). |
| `capabilities.routeProfiles` | array | up to 3 `{ id, label, icon? }` entries for a plugin implementing the `routeProvider` hook — each becomes a selectable mode in the planner's route toggle (next to Driving/Walking). `id` is lowercase `[a-z][a-z0-9-]` (max 24 chars) and is what `getRoute` receives as `request.profile`; `label` (≤40 chars) is shown to the user. Requires the `hook:route-provider` permission. |
+| `capabilities.poiCategories` | array | up to **4** `{ id, label, labels?, icon, color }` entries for a plugin implementing the `poiCategoryProvider` hook; each becomes a chip in the trip map's **Explore places** pill, after the built-in ones. `id` is lowercase `^[a-z][a-z0-9-]{0,23}$`, unique, and is what `getPois` receives as `request.category`. `label` (≤40 chars, plain text, emoji and control characters stripped) is shown when `labels` has nothing for the user's language; `labels` maps TREK language codes (`de`, `fr`, `zh-TW`…) to labels with the same rules, and a code TREK does not ship is ignored. `icon` is one of `Footprints`, `Mountain`, `MountainSnow`, `Signpost`, `Trees`, `TentTree`, `Tent`, `Accessibility`, `Droplet`, `Droplets`, `PlugZap`, `Zap`, `Bath`, `Bike`, `Waves`, `Landmark`, `MapPin`, `Star`, `Heart`, `Info` (exported by the SDK as `POI_CATEGORY_ICONS`; lucide has no toilet glyph, use `Bath`). `color` is `#rrggbb` only, because it lands inside marker markup. Anything else fails the install. Requires the `hook:poi-category-provider` permission: a declaration installs without it, but the chips only appear while the grant is held (`trek-plugin validate` refuses the combination). Needs a TREK that knows the permission, so raise your `trek` floor to the release that ships it. |
| `capabilities.mcpTools` | array | up to **8** MCP tools for a plugin implementing the `mcpToolProvider` hook — each `{ name, description, title?, inputSchema?, annotations? }` (`name` lowercase `^[a-z0-9_]{1,48}$`, unique; `description` required; `inputSchema` a JSON Schema with root `type: "object"` built from a small enforced keyword set — an unsupported keyword fails the install). Requires the `mcp:tools` permission. See [MCP tools](#mcp-tools). |
| `capabilities.provides` | string[] | function names this plugin exposes to its dependents via `ctx.plugins.call` (see [Talking to other plugins](#talking-to-other-plugins)). |
| `capabilities.emits` | string[] | event names this plugin publishes to its dependents via `ctx.events.emit`. |
@@ -1482,6 +1484,7 @@ install (and by `trek-plugin validate` and registry CI, which check against the
| `http:outbound` or `http:outbound:<host>` | outbound HTTP to `egress[]` hosts |
| `hook:place-detail-provider` | `hooks.placeDetailProvider` — extra place rows TREK renders (see [Provider hooks](#provider-hooks)) |
| `hook:search-provider` | `hooks.searchProvider` — answers place searches from your own index (see [Provider hooks](#provider-hooks)) |
+| `hook:poi-category-provider` | `hooks.poiCategoryProvider`: answers your own chips in the map's Explore places pill, and is sent the viewport of the user who picks one (declared in `capabilities.poiCategories`) |
| `hook:trip-warning-provider` | `hooks.warningProvider` — validation warnings in the planner (see [Provider hooks](#provider-hooks)) |
| `hook:table-contributor` | `hooks.tableContributor` — host-rendered columns/actions in the reservations, transports, places, day, costs, packing, files and todos views (see [Provider hooks](#provider-hooks)) |
| `hook:map-marker-provider` | `hooks.mapMarkerProvider` — bounded markers on the trip map |
diff --git a/wiki/Plugin-Permissions.md b/wiki/Plugin-Permissions.md
index 8729bfebc..b187d738f 100644
--- a/wiki/Plugin-Permissions.md
+++ b/wiki/Plugin-Permissions.md
@@ -59,6 +59,7 @@ ungranted capability is physically unreachable**, not just disallowed. See
| `hook:calendar-source` | Register as a calendar source | Implement the `CalendarSource` interface. |
| `hook:place-detail-provider` | Contribute extra details (reviews, ratings, links) to a place via the `hooks.placeDetailProvider` provider hook | Implement `PlaceDetailProvider` in `hooks` on the plugin definition (not on `ctx`) — shown in the place-detail panel; also exposed at `GET /api/place-details/:placeId`. |
| `hook:search-provider` | Answer place searches from an index TREK does not ship, beside its own results | Implement `SearchProvider` in `hooks` on the plugin definition — hits are drawn into the app’s search list; also exposed at `GET /api/plugin-search` and as the `search_places_via_plugins` MCP tool. Only these results can carry a `rating`: open data has none. The Road trip search along the route calls the same hook once per kind, with `category` and `bounds` added to the request and a fixed category phrase as `query`; hits outside `bounds`, or of a different road trip kind, are dropped. |
+| `hook:poi-category-provider` | Add its own place categories to the trip map's **Explore places** pill and answer them for the map area the user is viewing | Declare up to 4 chips in `capabilities.poiCategories` (each `{id, label, labels?, icon, color}`: the icon from a fixed list of lucide names, the colour `#rrggbb` only) and implement `PoiCategoryProvider` in `hooks`. When a user picks one of the chips, TREK calls `getPois({category, bounds, lang?, limit})` on exactly that plugin, **as that user**, with the viewport narrowed to at most 0.5 degrees a side, so granting this means the plugin learns which map area each user who uses its chips is looking at. Its own permission for that reason, rather than a reuse of `hook:search-provider`: that hook is asked about a search somebody ran, this one about the map area somebody is looking at. The host keeps at most 60 places inside `bounds`, caps every string and the up-to-6 `details` rows, allows only http/https websites, namespaces ids as `plugin:<id>:<ref>`, and styles every marker with the declared icon and colour rather than anything the answer carries. 8 s timeout; a slow or failing plugin costs only its own chip. Nothing is cached, because the answer may depend on the user's own settings. Without the grant a declaration still installs but its chips never appear. Exposed at `GET /api/plugin-pois` and as the `list_plugin_poi_categories` and `search_plugin_pois` MCP tools. |
| `hook:trip-warning-provider` | Raise validation warnings on a trip via the `hooks.warningProvider` provider hook | Implement `WarningProvider` in `hooks` on the plugin definition (not on `ctx`) — shown as a non-blocking banner in the planner; also exposed at `GET /api/trip-warnings/:tripId`, and to a connected assistant as the `get_trip_warnings` MCP tool (≤20 warnings per provider, message ≤300 chars) — that path needs only the trips read scope, not `plugins:use`. |
| `hook:map-marker-provider` | Overlay bounded **markers** on the trip map via the `hooks.mapMarkerProvider` provider hook | Implement `MapMarkerProvider` in `hooks` — returns `{id, lat, lng, label?, popupText?, url?, icon?, tone?}[]` (#587 "show bookings on map"). **Declarative only** — plugin JS never runs on the map canvas. The host range-checks coordinates (−90..90 / −180..180), String-coerces + length-caps text, allowlists the popup url (http/https/mailto), and caps the marker count (≤200) per plugin; a failing provider is skipped. Exposed at `GET /api/map-markers/:tripId`. |
| `hook:map-layer-provider` | Overlay bounded **vector layers** (polylines, polygons, metric circles) on the trip map via the `hooks.mapLayerProvider` provider hook | Implement `MapLayerProvider` in `hooks` — returns `{id, name?, features}[]` where a feature is `{type, points?/center?+radiusM?, tone?, width?, dash?, opacity?, fill?, label?}`. **Declarative only** — the host draws everything; styling is the tone palette plus clamped numerics (width 1–8, opacity 0.05–1, radius ≤2000 km) and a dash enum, so a layer can't impersonate core UI. Budgets per plugin: ≤4 layers / ≤150 features / ≤8000 vertices / ≤2000 vertices per shape; invalid or oversized shapes are dropped whole (never truncated); a failing provider is skipped. Drawn beneath TREK's own routes. Exposed at `GET /api/map-layers/:tripId`. |
diff --git a/wiki/Plugins.md b/wiki/Plugins.md
index 895aab2eb..cf39f7bde 100644
--- a/wiki/Plugins.md
+++ b/wiki/Plugins.md
@@ -176,6 +176,9 @@ for manually-uploaded plugins (see [Installing](#installing-a-plugin)), and
"Reads your costs" / "Adds costs", "Dashboard widget", "Real-time updates",
"Provides photos", outbound hosts, and so on — so a plugin's real reach is
legible without opening anything.
+A plugin that adds its own buttons to the category row on the trip map (see
+[Places and Search](Places-and-Search#categories-from-plugins)) carries an
+"Adds map categories" chip.
## Reviewing a plugin before install
@@ -190,6 +193,10 @@ manifest (at the reviewed commit) and lays out:
- **AI tools it publishes** — for a plugin declaring `capabilities.mcpTools`: each tool's
name, title and the assistant-facing description, so you read what a connected assistant
will be told about the plugin *before* you grant it.
+- **Map categories it adds**: for a plugin declaring `capabilities.poiCategories` and
+ asking for `hook:poi-category-provider`, each button it would add to the category
+ row on the trip map, with its icon, colour and name in your language, so you see
+ what your users will get before you grant it.
- **Details** — version, download size, minimum TREK version, review date, plus
links to the source repo and homepage.
- **Versions** — every published version (listed once a plugin has more than one) with its