From 133ab2e82cde2af5b56f904b661eafd111be9ce4 Mon Sep 17 00:00:00 2001 From: Lukas Date: Thu, 19 Mar 2026 19:10:44 +0100 Subject: [PATCH] Add hover tooltip to WorldMap and update task list --- Docs/Tasks.md | 234 ++++++++++++++---- frontend/src/components/WorldMap.tsx | 84 ++++++- .../components/__tests__/WorldMap.test.tsx | 51 ++++ frontend/src/pages/MapPage.tsx | 1 + frontend/src/pages/__tests__/MapPage.test.tsx | 11 +- 5 files changed, 323 insertions(+), 58 deletions(-) create mode 100644 frontend/src/components/__tests__/WorldMap.test.tsx diff --git a/Docs/Tasks.md b/Docs/Tasks.md index c061a96..d35afa5 100644 --- a/Docs/Tasks.md +++ b/Docs/Tasks.md @@ -12,81 +12,205 @@ This document breaks the entire BanGUI project into development stages, ordered --- -### Task 1 — Blocklist-import jail ban time must be 24 hours +## Feature: Worldmap Country Tooltip -**Status:** ✅ Done - -**Context** - -When the blocklist importer bans an IP it calls `jail_service.ban_ip(socket_path, BLOCKLIST_JAIL, ip)` (see `backend/app/services/blocklist_service.py`, constant `BLOCKLIST_JAIL = "blocklist-import"`). That call sends `set blocklist-import banip ` to fail2ban, which applies the jail's configured `bantime`. There is currently no guarantee that the `blocklist-import` jail's `bantime` is 86 400 s (24 h), so imported IPs may be released too early or held indefinitely depending on the jail template. - -**What to do** - -1. Locate every place the `blocklist-import` jail is defined or provisioned — check `Docker/fail2ban-dev-config/`, `Docker/Dockerfile.backend`, any jail template files, and the `setup_service.py` / `SetupPage.tsx` flow. -2. Ensure the `blocklist-import` jail is created with `bantime = 86400` (24 h). If the jail is created at runtime by the setup service, add or update the `bantime` parameter there. If it is defined in a static config file, set `bantime = 86400` in that file. -3. Verify that the existing `jail_service.ban_ip` call in `blocklist_service.import_source` does not need a per-call duration override; the jail-level default of 86 400 s is sufficient. -4. Add or update the relevant unit/integration test in `backend/tests/` to assert that the blocklist-import jail is set up with a 24-hour bantime. +> **2026-03-17** +> The world map on the Map page colours each country by ban count but provides no immediate information on hover — the user must click a country to see its name in the filter bar below, and must read the small SVG count label to learn the number of bans. +> +> Goal: show a lightweight floating tooltip whenever the pointer enters a country, displaying the country's display name and its current ban count, so the information is accessible without a click. --- -### Task 2 — Clicking a jail in Jail Overview navigates to Configuration → Jails +### Task WM-1 — Show country name and ban count tooltip on map hover -**Status:** ✅ Done +**Scope:** `frontend/src/components/WorldMap.tsx`, `frontend/src/pages/MapPage.tsx` -**Context** +`countryNames` (ISO alpha-2 → display name) is already available in `MapPage` from `useMapData` but is not forwarded to `WorldMap`. The map component itself tracks no hover state. This task adds pointer-event handlers to each country `` element, tracks the hovered country in local state together with the last known mouse coordinates, and renders a positionned HTML tooltip `
` on top of the SVG. -`JailsPage.tsx` renders a "Jail Overview" data grid with one row per jail (see `frontend/src/pages/JailsPage.tsx`). Clicking a row currently does nothing. `ConfigPage.tsx` hosts a tab bar with a "Jails" tab that renders `JailsTab`, which already uses a list/detail layout where a jail can be selected from the left pane. +**Implementation steps:** -**What to do** +1. **Extend `WorldMapProps` and `GeoLayerProps`** in `WorldMap.tsx`: + - Add `countryNames?: Record` to `WorldMapProps` (optional — falls back to the ISO alpha-2 code when absent). + - Thread it through `GeoLayer` the same way the threshold props are already threaded. -1. In `JailsPage.tsx`, make each jail name cell (or the entire row) a clickable element that navigates to `/config` with state `{ tab: "jails", jail: "" }`. Use `useNavigate` from `react-router-dom`; the existing `Link` import can be used or replaced with a programmatic navigate. -2. In `ConfigPage.tsx`, read the location state on mount. If `state.tab` is `"jails"`, set the active tab to `"jails"`. Pass `state.jail` down to ``. -3. In `JailsTab.tsx`, accept an optional `initialJail?: string` prop. When it is provided, pre-select that jail in the left-pane list on first render (i.e. set the selected jail state to the jail whose name matches `initialJail`). This should scroll the item into view if the list is long. -4. Add a frontend unit test in `frontend/src/pages/__tests__/` that mounts `JailsPage` with a mocked jail list, clicks a jail row, and asserts that `useNavigate` was called with the correct path and state. +2. **Add hover state to `GeoLayer`** — declare: + ```ts + const [tooltip, setTooltip] = useState<{ + cc: string; + count: number; + name: string; + x: number; + y: number; + } | null>(null); + ``` + On each country `` element add: + - `onMouseEnter` — set `tooltip` with the country code, count, display name (from `countryNames`, falling back to the alpha-2 code), and mouse page coordinates (`e.clientX`, `e.clientY`). + - `onMouseMove` — update only the `x`/`y` in the existing tooltip (keep name/count stable). + - `onMouseLeave` — set `tooltip` to `null`. + + Skip setting the tooltip for countries where `cc === null` (no ISO mapping available) but keep `onMouseLeave` so re-entering after leaving from an unmapped border still clears the state. + +3. **Render the tooltip inside `GeoLayer`** — because `GeoLayer` is rendered inside `ComposableMap` which is inside `mapWrapper`, the tooltip div cannot be positioned relative to the map wrapper from here (the SVG clip/transform would offset it). Instead, use a React **portal** (`ReactDOM.createPortal`) to mount the tooltip directly on `document.body` so it sits in the root stacking context and can be positioned with `position: fixed` using the raw `clientX`/`clientY` coordinates. + + Tooltip structure (styled with a new `makeStyles` class `tooltip` in `WorldMap.tsx`): + ```tsx + {tooltip && + createPortal( +
+ {tooltip.name} + + {tooltip.count.toLocaleString()} ban{tooltip.count !== 1 ? "s" : ""} + +
, + document.body, + )} + ``` + +4. **Tooltip styles** — add three new classes to the `makeStyles` call in `WorldMap.tsx`: + ```ts + tooltip: { + position: "fixed", + zIndex: 9999, + pointerEvents: "none", + backgroundColor: tokens.colorNeutralBackground1, + border: `1px solid ${tokens.colorNeutralStroke2}`, + borderRadius: tokens.borderRadiusSmall, + padding: `${tokens.spacingVerticalXS} ${tokens.spacingHorizontalS}`, + display: "flex", + flexDirection: "column", + gap: tokens.spacingVerticalXXS, + boxShadow: tokens.shadow4, + }, + tooltipCountry: { + fontSize: tokens.fontSizeBase200, + fontWeight: tokens.fontWeightSemibold, + color: tokens.colorNeutralForeground1, + }, + tooltipCount: { + fontSize: tokens.fontSizeBase200, + color: tokens.colorNeutralForeground2, + }, + ``` + +5. **Pass `countryNames` from `MapPage`** — in `MapPage.tsx`, add the `countryNames` prop to the existing `` JSX: + ```tsx + + ``` + +6. **Countries with zero bans** — the tooltip should still appear when the user hovers over a country with `0` bans (showing the name and "0 bans"), so users know the country is tracked but has no bans. Do not suppress the tooltip for zero-count countries. + +**Acceptance criteria:** +- Moving the pointer over any mapped country on the Map page shows a floating tooltip within 0 ms (synchronous state update) containing the country's full display name (e.g. `Germany`) on the first line and the ban count (e.g. `42 bans` or `0 bans`) on the second line. +- Moving the pointer off a country hides the tooltip immediately. +- The tooltip follows the pointer as it moves within a country's borders. +- Clicking a country still selects/deselects it exactly as before; the tooltip does not interfere with the click handler. +- The tooltip is not interactive (`pointerEvents: none`) and does not steal focus from the map. +- `tsc --noEmit` produces no new errors. + +**Status:** ✅ Completed (2026-03-19) --- -### Task 3 — Setting bantime / findtime throws 400 error due to unsupported `backend` set command +## Feature: Global Unique BanGUI Version -**Status:** ✅ Done - -**Context** - -Editing ban time or find time in Configuration → Jails triggers an auto-save that sends the full `JailConfigUpdate` payload including the `backend` field. `config_service.update_jail_config` then calls `set backend ` on the fail2ban socket, which returns error code 1 with the message `Invalid command 'backend' (no set action or not yet implemented)`. Fail2ban does not support changing a jail's backend at runtime; it must be set before the jail starts. - -**What to do** - -**Backend** (`backend/app/services/config_service.py`): - -1. Remove the `if update.backend is not None: await _set("backend", update.backend)` block from `update_jail_config`. Setting `backend` via the socket is not supported by fail2ban and will always fail. -2. `log_encoding` has the same constraint — verify whether `set logencoding` is supported at runtime. If it is not, remove it too. If it is supported, leave it. -3. Ensure the function still accepts and stores the `backend` value in the Pydantic model for read purposes; do not remove it from `JailConfigUpdate` or the response model. - -**Frontend** (`frontend/src/components/config/JailsTab.tsx`): - -4. Remove `backend` (and `log_encoding` if step 2 confirms it is unsupported) from the `autoSavePayload` memo so the field is never sent in the PATCH/PUT body. The displayed value should remain read-only — show them as plain text or a disabled select so the user can see the current value without being able to trigger the broken set command. - -**Tests**: - -5. Add or update the backend test for `update_jail_config` to assert that no `set … backend` command is issued, and that a payload containing a `backend` field does not cause an error. +> **2026-03-17** +> The BanGUI application version is currently scattered across three independent files that are not kept in sync: +> - `Docker/VERSION` — `v0.9.8` (release artifact, written by the release script) +> - `frontend/package.json` — `0.9.8` +> - `backend/pyproject.toml` — `0.9.4` ← **out of sync** +> +> Additionally the BanGUI version is only shown in the sidebar footer (`MainLayout.tsx`). Neither the Dashboard nor the Configuration → Server view exposes the BanGUI application version, only the fail2ban daemon version. +> +> Goal: one authoritative version string, propagated automatically to all layers, and displayed consistently on both the Dashboard and the Configuration → Server page. --- -### Task 4 — Unify filter bar: use `DashboardFilterBar` in World Map and History pages +### Task GV-1 — Establish a single source of truth for the BanGUI version -**Status:** ✅ Done +**Scope:** `Docker/VERSION`, `backend/pyproject.toml`, `frontend/package.json`, `backend/app/__init__.py` -**Context** +`Docker/VERSION` is already the file written by the release script (`Docker/release.sh`) and is therefore the natural single source of truth. -`DashboardPage.tsx` uses the shared `` component for its time-range and origin-filter controls. `MapPage.tsx` and `HistoryPage.tsx` each implement their own ad-hoc filter UI: `MapPage` uses a Fluent UI `` for time range with no origin filter toggle. The `DashboardFilterBar` already supports both `TimeRange` and `BanOriginFilter` with the exact toggle-button style shown in the design reference. All three pages should share the same filter appearance and interaction patterns. +1. Sync the two package manifests to the current release version: + - Set `version` in `backend/pyproject.toml` to `0.9.8` (strip the leading `v` that `Docker/VERSION` contains). + - `frontend/package.json` is already `0.9.8` — no change needed. +2. Make the backend read its version **directly from `Docker/VERSION`** at import time instead of from `pyproject.toml`, so a future release-script bump of `Docker/VERSION` is sufficient. Update `_read_pyproject_version()` in `backend/app/__init__.py`: + - Add a new helper `_read_docker_version() -> str` that resolves `Docker/VERSION` relative to the repository root (two `parents` above `backend/app/`), strips the leading `v` and whitespace, and returns the bare semver string. + - Change `_read_version()` to try `_read_docker_version()` first, then fall back to `_read_pyproject_version()`, then `importlib.metadata`. +3. Make the frontend read its version from `Docker/VERSION` at build time. In `frontend/vite.config.ts`, replace the `pkg.version` import with a `fs.readFileSync('../Docker/VERSION', 'utf-8').trim().replace(/^v/, '')` call so both the dev server and production build always reflect the file. + - Update `declare const __APP_VERSION__: string;` in `frontend/src/vite-env.d.ts` if the type declaration needs adjustment (it should not). -**What to do** - -1. **`MapPage.tsx`**: Replace the custom time-range `` with ``. Add an `originFilter` state (`BanOriginFilter`, default `"all"`) and wire it through ``. Pass the origin filter into the `useHistory` query so the backend receives it. If `useHistory` / `HistoryQuery` does not yet accept `origin_filter`, add the parameter to the type and the hook's fetch call. -3. Remove any local `filterBar` style definitions from `MapPage.tsx` and `HistoryPage.tsx` that duplicate what `DashboardFilterBar` already provides. -4. Ensure the `DashboardFilterBar` component's props interface (`DashboardFilterBarProps` in `frontend/src/components/DashboardFilterBar.tsx`) is not changed in a breaking way; only the call sites change. -5. Update or add component tests for `MapPage` and `HistoryPage` to assert that `DashboardFilterBar` is rendered and that changing the time range or origin filter updates the displayed data. +**Acceptance criteria:** +- `backend/app/__version__` equals the content of `Docker/VERSION` (without `v` prefix) at runtime. +- `frontend` build constant `__APP_VERSION__` equals the same value. +- Bumping only `Docker/VERSION` (e.g. `v0.9.9`) causes both layers to pick up the new version without touching any other file. +- All existing tests pass (`pytest backend/`). --- +### Task GV-2 — Expose the BanGUI version through the API + +**Scope:** `backend/app/models/server.py`, `backend/app/models/config.py`, `backend/app/routers/dashboard.py`, `backend/app/routers/config.py` + +Add a `bangui_version` field to every API response that already carries the fail2ban daemon `version`, so the frontend can display the BanGUI application version next to it. + +1. **`backend/app/models/server.py`** — Add to `ServerStatusResponse`: + ```python + bangui_version: str = Field(..., description="BanGUI application version.") + ``` +2. **`backend/app/models/config.py`** — Add to `ServiceStatusResponse`: + ```python + bangui_version: str = Field(..., description="BanGUI application version.") + ``` +3. **`backend/app/routers/dashboard.py`** — In `get_server_status`, import `__version__` from `app` and populate the new field: + ```python + return ServerStatusResponse(status=cached, bangui_version=__version__) + ``` +4. **`backend/app/routers/config.py`** — Do the same for the `GET /api/config/service-status` endpoint. + +**Do not** change the existing `version` field (fail2ban daemon version) — keep it exactly as-is so nothing downstream breaks. + +**Acceptance criteria:** +- `GET /api/dashboard/status` response JSON contains `"bangui_version": "0.9.8"`. +- `GET /api/config/service-status` response JSON contains `"bangui_version": "0.9.8"`. +- All existing backend tests pass. +- Add one test per endpoint asserting that `bangui_version` matches `app.__version__`. + +--- + +### Task GV-3 — Display the BanGUI version on Dashboard and Configuration → Server + +**Scope:** `frontend/src/components/ServerStatusBar.tsx`, `frontend/src/components/config/ServerHealthSection.tsx`, `frontend/src/types/server.ts`, `frontend/src/types/config.ts` + +After GV-2 the API delivers `bangui_version`; this task makes the frontend show it. + +1. **Type definitions** + - `frontend/src/types/server.ts` — Add `bangui_version: string` to the `ServerStatusResponse` interface. + - `frontend/src/types/config.ts` — Add `bangui_version: string` to the `ServiceStatusResponse` interface. + +2. **Dashboard — `ServerStatusBar.tsx`** + The status bar already renders `v{status.version}` (fail2ban version with a tooltip). Add a second badge directly adjacent to it that reads `BanGUI v{status.bangui_version}` with the tooltip `"BanGUI version"`. Match the existing badge style. + +3. **Configuration → Server — `ServerHealthSection.tsx`** + The health section already renders a `Version` row with the fail2ban version. Add a new row below it labelled `BanGUI` (or `BanGUI Version`) that renders `{status.bangui_version}`. Apply the same `statLabel` / `statValue` CSS classes used by the adjacent rows. + +4. **Remove the duplicate from the sidebar** — Once the version is visible on the relevant pages, the sidebar footer in `frontend/src/layouts/MainLayout.tsx` can drop `v{__APP_VERSION__}` to avoid showing the version in three places. Replace it with the plain product name `BanGUI` — **only do this if the design document (`Docs/Web-Design.md`) does not mandate showing the version there**; otherwise leave it and note the decision in a comment. + +**Acceptance criteria:** +- Dashboard status bar shows `BanGUI v0.9.8` with an appropriate tooltip. +- Configuration → Server health section shows a `BanGUI` version row reading `0.9.8`. +- No TypeScript compile errors (`tsc --noEmit`). +- Both values originate from the same API field (`bangui_version`) and therefore always match the backend version. + +--- diff --git a/frontend/src/components/WorldMap.tsx b/frontend/src/components/WorldMap.tsx index 2293631..d29c049 100644 --- a/frontend/src/components/WorldMap.tsx +++ b/frontend/src/components/WorldMap.tsx @@ -7,6 +7,7 @@ * country filters the companion table. */ +import { createPortal } from "react-dom"; import { useCallback, useState } from "react"; import { ComposableMap, ZoomableGroup, Geography, useGeographies } from "react-simple-maps"; import { Button, makeStyles, tokens } from "@fluentui/react-components"; @@ -50,6 +51,28 @@ const useStyles = makeStyles({ gap: tokens.spacingVerticalXS, zIndex: 10, }, + tooltip: { + position: "fixed", + zIndex: 9999, + pointerEvents: "none", + backgroundColor: tokens.colorNeutralBackground1, + border: `1px solid ${tokens.colorNeutralStroke2}`, + borderRadius: tokens.borderRadiusSmall, + padding: `${tokens.spacingVerticalXS} ${tokens.spacingHorizontalS}`, + display: "flex", + flexDirection: "column", + gap: tokens.spacingVerticalXXS, + boxShadow: tokens.shadow4, + }, + tooltipCountry: { + fontSize: tokens.fontSizeBase200, + fontWeight: tokens.fontWeightSemibold, + color: tokens.colorNeutralForeground1, + }, + tooltipCount: { + fontSize: tokens.fontSizeBase200, + color: tokens.colorNeutralForeground2, + }, }); // --------------------------------------------------------------------------- @@ -58,6 +81,7 @@ const useStyles = makeStyles({ interface GeoLayerProps { countries: Record; + countryNames?: Record; selectedCountry: string | null; onSelectCountry: (cc: string | null) => void; thresholdLow: number; @@ -67,6 +91,7 @@ interface GeoLayerProps { function GeoLayer({ countries, + countryNames, selectedCountry, onSelectCountry, thresholdLow, @@ -76,6 +101,17 @@ function GeoLayer({ const styles = useStyles(); const { geographies, path } = useGeographies({ geography: GEO_URL }); + const [tooltip, setTooltip] = useState< + | { + cc: string; + count: number; + name: string; + x: number; + y: number; + } + | null + >(null); + const handleClick = useCallback( (cc: string | null): void => { onSelectCountry(selectedCountry === cc ? null : cc); @@ -98,7 +134,7 @@ function GeoLayer({ const cc: string | null = ISO_NUMERIC_TO_ALPHA2[numericId] ?? null; const count: number = cc !== null ? (countries[cc] ?? 0) : 0; const isSelected = cc !== null && selectedCountry === cc; - + // Compute the fill color based on ban count const fillColor = getBanCountColor( count, @@ -106,7 +142,7 @@ function GeoLayer({ thresholdMedium, thresholdHigh, ); - + // Only calculate centroid if path is available let cx: number | undefined; let cy: number | undefined; @@ -136,6 +172,30 @@ function GeoLayer({ handleClick(cc); } }} + onMouseEnter={(e): void => { + if (!cc) return; + setTooltip({ + cc, + count, + name: countryNames?.[cc] ?? cc, + x: e.clientX, + y: e.clientY, + }); + }} + onMouseMove={(e): void => { + setTooltip((current) => + current + ? { + ...current, + x: e.clientX, + y: e.clientY, + } + : current, + ); + }} + onMouseLeave={(): void => { + setTooltip(null); + }} > + {tooltip.name} + + {tooltip.count.toLocaleString()} ban{tooltip.count !== 1 ? "s" : ""} + +
, + document.body, + )} ); } @@ -190,6 +266,8 @@ function GeoLayer({ export interface WorldMapProps { /** ISO alpha-2 country code → ban count. */ countries: Record; + /** Optional mapping from country code to display name. */ + countryNames?: Record; /** Currently selected country filter (null means no filter). */ selectedCountry: string | null; /** Called when the user clicks a country or deselects. */ @@ -204,6 +282,7 @@ export interface WorldMapProps { export function WorldMap({ countries, + countryNames, selectedCountry, onSelectCountry, thresholdLow = 20, @@ -286,6 +365,7 @@ export function WorldMap({ > ({ + ComposableMap: ({ children }: { children: React.ReactNode }) =>
{children}
, + ZoomableGroup: ({ children }: { children: React.ReactNode }) =>
{children}
, + Geography: ({ children }: { children?: React.ReactNode }) => {children}, + useGeographies: () => ({ + geographies: [{ rsmKey: "geo-1", id: 840 }], + path: { centroid: () => [10, 10] }, + }), +})); + +import { WorldMap } from "../WorldMap"; + +describe("WorldMap", () => { + it("shows a tooltip with country name and ban count on hover", () => { + render( + + + , + ); + + // Tooltip should not be present initially + expect(screen.queryByRole("tooltip")).toBeNull(); + + const countryButton = screen.getByRole("button", { name: /US: 42 bans/i }); + fireEvent.mouseEnter(countryButton, { clientX: 10, clientY: 10 }); + + const tooltip = screen.getByRole("tooltip"); + expect(tooltip).toHaveTextContent("United States"); + expect(tooltip).toHaveTextContent("42 bans"); + expect(tooltip).toHaveStyle({ left: "22px", top: "22px" }); + + fireEvent.mouseLeave(countryButton); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); +}); diff --git a/frontend/src/pages/MapPage.tsx b/frontend/src/pages/MapPage.tsx index 8280894..ce55314 100644 --- a/frontend/src/pages/MapPage.tsx +++ b/frontend/src/pages/MapPage.tsx @@ -167,6 +167,7 @@ export function MapPage(): React.JSX.Element { {!loading && !error && ( ({ fetchMapColorThresholds: mockFetchMapColorThresholds, })); +const mockWorldMap = vi.fn((_props: unknown) =>
); vi.mock("../components/WorldMap", () => ({ - WorldMap: () =>
, + WorldMap: (props: unknown) => { + mockWorldMap(props); + return
; + }, })); describe("MapPage", () => { @@ -49,6 +53,11 @@ describe("MapPage", () => { // Initial load should call useMapData with default filters. expect(lastArgs).toEqual({ range: "24h", origin: "all" }); + // Map should receive country names from the hook so tooltips can show human-readable labels. + expect(mockWorldMap).toHaveBeenCalled(); + const firstCallArgs = mockWorldMap.mock.calls[0]?.[0]; + expect(firstCallArgs).toMatchObject({ countryNames: {} }); + await user.click(screen.getByRole("button", { name: /Last 7 days/i })); expect(lastArgs.range).toBe("7d");