diff --git a/VERSION b/VERSION index e5f8af27..3a41d7db 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.11.40 +1.11.41 diff --git a/backend/app/api/dashboards.py b/backend/app/api/dashboards.py index 07fd70c9..88389002 100644 --- a/backend/app/api/dashboards.py +++ b/backend/app/api/dashboards.py @@ -15,12 +15,13 @@ would be a broken dashboard the user cannot fix without an API call. """ import logging -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, request from flask_jwt_extended import jwt_required, get_jwt_identity from app.services import dashboard_service -from app.services.dashboard_service import GRID_COLS, MAX_WIDGETS_PER_BOARD +from app.services.dashboard_service import ENTITY_SCOPES, GRID_COLS, MAX_WIDGETS_PER_BOARD from app.api._request import json_object +from app.exceptions import ValidationError logger = logging.getLogger(__name__) @@ -126,8 +127,17 @@ def _validate_icon(value): @dashboards_bp.route('/', methods=['GET']) @jwt_required() def list_boards(): - """This user's boards, seeding the shipped defaults on the first call.""" + """This user's dashboard tabs, seeding the shipped defaults on the first + call. With ``?scope=entity:`` it returns instead the overview layout + the user saved for that kind of detail page: a list of one, or empty while + they are still on the shipped layout.""" user_id = get_jwt_identity() + scope = request.args.get('scope') + if scope is not None: + if scope not in ENTITY_SCOPES: + raise ValidationError('Unknown board scope') + board = dashboard_service.get_entity_board(user_id, scope) + return jsonify({'boards': [board.to_dict()] if board else []}) boards = dashboard_service.get_boards_for_user(user_id) return jsonify({'boards': [b.to_dict() for b in boards]}) @@ -137,10 +147,18 @@ def list_boards(): @jwt_required() def create_board(): """Add a board for this user. ``widgets`` is optional — a new tab usually - starts empty and gets filled from the widget library.""" + starts empty and gets filled from the widget library. + + With ``scope: 'entity:'`` the board is the user's overview layout for + that kind of detail page rather than a dashboard tab. A user has one per + kind, so posting again replaces it (200 instead of 201).""" user_id = get_jwt_identity() body = json_object(optional=True) + scope = body.get('scope') + if scope is not None and scope not in ENTITY_SCOPES: + raise ValidationError('Unknown board scope') + name, err = _validate_name(body.get('name')) if err: return jsonify({'error': err}), 400 @@ -157,6 +175,10 @@ def create_board(): if err: return jsonify({'error': err}), 400 + if scope is not None: + board, created = dashboard_service.save_entity_board(user_id, scope, name, widgets) + return jsonify(board.to_dict()), 201 if created else 200 + board = dashboard_service.create_board(user_id, name, icon=icon, widgets=widgets) return jsonify(board.to_dict()), 201 diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py index f05bffe4..ff51cb0c 100644 --- a/backend/app/api/servers.py +++ b/backend/app/api/servers.py @@ -15,6 +15,7 @@ from sqlalchemy.orm import joinedload from app import db, limiter from app.services import permission_levels from app.services.server_metrics_service import latest_metrics_by_server +from app.services.server_workload_service import workload_counts_by_server from app.api._query import apply_query, QueryParseError from app.api._request import json_object from app.models.server import Server, ServerGroup, ServerMetrics, ServerCommand, AgentSession @@ -357,6 +358,13 @@ def list_servers(): (server.id for server in servers), order_by='id', ) + # What each server carries, when the caller wants it. Two queries for the + # whole list, scoped to the services this caller may see. + count_keys = [key for key in ('services_count', 'domains_count') + if fields is None or key in fields] + workload = (workload_counts_by_server((server.id for server in servers), user, ws_id) + if count_keys else {}) + result = [] for server in servers: server_dict = server.to_dict(fields=fields) @@ -364,6 +372,10 @@ def list_servers(): metrics = metrics_by_server.get(server.id) if metrics: server_dict['metrics'] = metrics.to_dict() + counts = workload.get(server.id) + if counts: + for key in count_keys: + server_dict[key] = counts[key] result.append(server_dict) return jsonify(result) diff --git a/backend/app/models/server.py b/backend/app/models/server.py index 7b011715..428d7b94 100644 --- a/backend/app/models/server.py +++ b/backend/app/models/server.py @@ -476,7 +476,10 @@ class Server(TimestampMixin, JsonColumnMixin, db.Model): # Emitted by to_dict but not mapped columns: each costs a relationship load # or a JSON walk, so `$select` has to know they exist in order to decline # them. Kept next to to_dict so the two cannot drift. - DERIVED_FIELDS = ('group_name', 'onboarding_progress', 'latest_metrics') + # `services_count` / `domains_count` are added by the list route (they + # need the caller's access scope), not by to_dict. + DERIVED_FIELDS = ('group_name', 'onboarding_progress', 'latest_metrics', + 'services_count', 'domains_count') def to_dict(self, include_metrics=False, fields=None): """Serialize the server. diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.py index 0844ed12..fb2949b5 100644 --- a/backend/app/services/dashboard_service.py +++ b/backend/app/services/dashboard_service.py @@ -49,6 +49,18 @@ GRID_COLS = 12 # JSON per board. MAX_WIDGETS_PER_BOARD = 100 +# A board can also hold the Overview layout a user saved for a page: one kind +# of detail page (every server page shares the user's server layout, the +# page's own server being the board's variable) or a single overview page +# (Monitoring, Backups). It is an ordinary board row whose slug names the +# page, so it reuses the same storage, validation and ownership rules; it is +# just never listed among the dashboard tabs. +ENTITY_SCOPE_PREFIX = 'entity:' +ENTITY_SCOPES = ( + 'entity:server', 'entity:service', + 'entity:monitoring', 'entity:backups', +) + DEFAULT_BOARDS = [ { @@ -257,14 +269,21 @@ def _repair_board(board): return True +def _dashboard_tabs(user_id): + """This user's dashboard tabs: every board except saved overview layouts.""" + return (DashboardBoard.query + .filter_by(user_id=user_id) + .filter(db.or_(DashboardBoard.slug.is_(None), + ~DashboardBoard.slug.like(f'{ENTITY_SCOPE_PREFIX}%'))) + .order_by(DashboardBoard.position, DashboardBoard.id) + .all()) + + def get_boards_for_user(user_id): - """Every board owned by this user, seeding the shipped defaults on the - first read for a user who has none, and repairing configs that predate the - current renderer contract.""" - boards = (DashboardBoard.query - .filter_by(user_id=user_id) - .order_by(DashboardBoard.position, DashboardBoard.id) - .all()) + """Every dashboard tab owned by this user, seeding the shipped defaults on + the first read for a user who has none, and repairing configs that predate + the current renderer contract.""" + boards = _dashboard_tabs(user_id) if boards: # Not `any(...)`: it short-circuits, so only the first repairable board # would ever be fixed. @@ -272,10 +291,28 @@ def get_boards_for_user(user_id): db.session.commit() return boards seed_defaults(user_id) - return (DashboardBoard.query - .filter_by(user_id=user_id) - .order_by(DashboardBoard.position, DashboardBoard.id) - .all()) + return _dashboard_tabs(user_id) + + +def get_entity_board(user_id, scope): + """The overview layout this user saved for one kind of detail page, or + None when they are still on the shipped layout.""" + return DashboardBoard.query.filter_by(user_id=user_id, slug=scope).first() + + +def save_entity_board(user_id, scope, name, widgets): + """Store a user's overview layout for one kind of detail page. There is at + most one per user and kind, so a second save replaces the first. Returns + ``(board, created)``.""" + board = get_entity_board(user_id, scope) + created = board is None + if created: + board = DashboardBoard(user_id=user_id, slug=scope, icon='grid', position=0) + db.session.add(board) + board.name = name + board.widgets = list(widgets or []) + db.session.commit() + return board, created def get_board_for_user(user_id, board_id): diff --git a/backend/app/services/server_workload_service.py b/backend/app/services/server_workload_service.py new file mode 100644 index 00000000..f6ebabf8 --- /dev/null +++ b/backend/app/services/server_workload_service.py @@ -0,0 +1,48 @@ +"""What each server carries: its services and the domains pointing at them. + +The server list shows these as columns, so they are computed for the whole +list at once (two queries, however many servers) rather than per row. +""" +from collections import Counter + +from app.models import Application +from app.models.domain import Domain +from app.services.workspace_service import WorkspaceService + + +def workload_counts_by_server(server_ids, user, workspace_id=None): + """Return ``{server_id: {'services_count': n, 'domains_count': n}}``. + + Only services the caller may see are counted, by the same scoping the + service list applies: a count must not reveal that a server runs something + the caller has no access to. A service with no ``server_id`` runs on the + panel host itself and belongs to no row here. + """ + ids = list(server_ids) + if not ids or user is None: + return {} + + services = WorkspaceService.scope_query( + Application.query_active(), Application, user, + workspace_id=workspace_id, owner_attr='user_id', + grant_resource_type='application', + ).filter(Application.server_id.in_(ids)) + server_of = dict(services.with_entities(Application.id, Application.server_id).all()) + + service_counts = Counter(server_of.values()) + domain_counts = Counter() + if server_of: + domain_rows = (Domain.query_active() + .filter(Domain.application_id.in_(list(server_of))) + .with_entities(Domain.application_id) + .all()) + for (application_id,) in domain_rows: + domain_counts[server_of[application_id]] += 1 + + return { + server_id: { + 'services_count': service_counts.get(server_id, 0), + 'domains_count': domain_counts.get(server_id, 0), + } + for server_id in ids + } diff --git a/backend/tests/test_dashboards.py b/backend/tests/test_dashboards.py index 564eceeb..6cc9ba81 100644 --- a/backend/tests/test_dashboards.py +++ b/backend/tests/test_dashboards.py @@ -464,3 +464,81 @@ def test_repair_leaves_a_current_board_untouched(app, client, auth_headers): boards = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards'] current = next(b for b in boards if b['name'] == 'Current') assert current['widgets'][0]['cfg'] == cfg + + +# --- saved overview layouts (entity-scoped boards) --------------------------- + +def test_overview_layout_is_stored_but_is_not_a_dashboard_tab(client, auth_headers): + saved = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Server overview', 'scope': 'entity:server', 'widgets': [_widget()], + }) + assert saved.status_code == 201 + assert saved.get_json()['slug'] == 'entity:server' + + tabs = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards'] + assert 'entity:server' not in [board['slug'] for board in tabs] + # Saving an overview first must not stop the shipped tabs from seeding. + assert [board['slug'] for board in tabs] == ['overview', 'infra', 'apps'] + + scoped = client.get('/api/v1/dashboards?scope=entity:server', headers=auth_headers).get_json()['boards'] + assert [board['id'] for board in scoped] == [saved.get_json()['id']] + assert scoped[0]['widgets'] == [_widget()] + + +@pytest.mark.parametrize('scope', [ + 'entity:server', 'entity:service', 'entity:monitoring', 'entity:backups', +]) +def test_overview_layout_is_empty_until_saved(client, auth_headers, scope): + resp = client.get(f'/api/v1/dashboards?scope={scope}', headers=auth_headers) + assert resp.status_code == 200 + assert resp.get_json()['boards'] == [] + + saved = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Overview', 'scope': scope, 'widgets': [_widget()], + }) + assert saved.status_code == 201 + again = client.get(f'/api/v1/dashboards?scope={scope}', headers=auth_headers).get_json()['boards'] + assert [board['slug'] for board in again] == [scope] + + +def test_saving_an_overview_layout_again_replaces_it(client, auth_headers): + first = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Server overview', 'scope': 'entity:server', 'widgets': [_widget()], + }) + second = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Server overview', 'scope': 'entity:server', + 'widgets': [_widget(i='w1'), _widget(i='w2', x=3)], + }) + assert second.status_code == 200 + assert second.get_json()['id'] == first.get_json()['id'] + + scoped = client.get('/api/v1/dashboards?scope=entity:server', headers=auth_headers).get_json()['boards'] + assert len(scoped) == 1 + assert [widget['i'] for widget in scoped[0]['widgets']] == ['w1', 'w2'] + + +def test_deleting_an_overview_layout_returns_to_the_shipped_one(client, auth_headers): + saved = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Service overview', 'scope': 'entity:service', 'widgets': [_widget()], + }).get_json() + assert client.delete(f"/api/v1/dashboards/{saved['id']}", headers=auth_headers).status_code == 200 + scoped = client.get('/api/v1/dashboards?scope=entity:service', headers=auth_headers).get_json()['boards'] + assert scoped == [] + + +def test_overview_layouts_are_scoped_per_user(client, auth_headers, other_headers): + client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Server overview', 'scope': 'entity:server', 'widgets': [_widget()], + }) + theirs = client.get('/api/v1/dashboards?scope=entity:server', headers=other_headers).get_json()['boards'] + assert theirs == [] + + +@pytest.mark.parametrize('scope', ['entity:database', 'overview', '', 7]) +def test_unknown_board_scope_is_rejected(client, auth_headers, scope): + resp = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Nope', 'scope': scope, 'widgets': [], + }) + assert resp.status_code == 400 + assert client.get('/api/v1/dashboards?scope=entity:database', headers=auth_headers).status_code == 400 + diff --git a/backend/tests/test_server_workload_counts.py b/backend/tests/test_server_workload_counts.py new file mode 100644 index 00000000..679fde88 --- /dev/null +++ b/backend/tests/test_server_workload_counts.py @@ -0,0 +1,101 @@ +"""The server list reports how many services and domains each server carries.""" +from app import db +from app.models.domain import Domain + +from tests.factories import headers_for, make_application, make_server, make_user + + +def _rows(client, headers, query=''): + resp = client.get(f'/api/v1/servers{query}', headers=headers) + assert resp.status_code == 200 + return {row['name']: row for row in resp.get_json()} + + +def test_list_counts_services_and_domains_per_server(app, client): + with app.app_context(): + admin = make_user(db, role='admin') + busy = make_server(db, name='busy') + make_server(db, name='idle') + web = make_application(db, name='web', user_id=admin.id, server_id=busy.id) + make_application(db, name='api', user_id=admin.id, server_id=busy.id) + # Runs on the panel host: belongs to no server row. + make_application(db, name='local', user_id=admin.id, server_id=None) + db.session.add_all([ + Domain(name='a.example.test', application_id=web.id), + Domain(name='b.example.test', application_id=web.id), + ]) + db.session.commit() + headers = headers_for(admin) + + rows = _rows(client, headers) + assert (rows['busy']['services_count'], rows['busy']['domains_count']) == (2, 2) + assert (rows['idle']['services_count'], rows['idle']['domains_count']) == (0, 0) + + +def test_deleted_services_and_domains_are_not_counted(app, client): + with app.app_context(): + admin = make_user(db, role='admin') + box = make_server(db, name='box') + kept = make_application(db, name='kept', user_id=admin.id, server_id=box.id) + gone = make_application(db, name='gone', user_id=admin.id, server_id=box.id) + live = Domain(name='live.example.test', application_id=kept.id) + dead = Domain(name='dead.example.test', application_id=kept.id) + db.session.add_all([live, dead]) + db.session.commit() + gone.soft_delete() + dead.soft_delete() + db.session.commit() + headers = headers_for(admin) + + row = _rows(client, headers)['box'] + assert (row['services_count'], row['domains_count']) == (1, 1) + + +def test_counts_only_include_services_the_caller_can_see(app): + """Asked at the service: a non-admin's count covers their own services + only, while an admin's covers everything on the server.""" + from app.services.server_workload_service import workload_counts_by_server + + with app.app_context(): + admin = make_user(db, role='admin') + owner = make_user(db, role='developer') + other = make_user(db, role='developer') + box = make_server(db, name='shared') + mine = make_application(db, name='mine', user_id=owner.id, server_id=box.id) + theirs = make_application(db, name='theirs', user_id=other.id, server_id=box.id) + db.session.add_all([ + Domain(name='mine.example.test', application_id=mine.id), + Domain(name='theirs.example.test', application_id=theirs.id), + ]) + db.session.commit() + + assert workload_counts_by_server([box.id], owner)[box.id] == { + 'services_count': 1, 'domains_count': 1} + assert workload_counts_by_server([box.id], admin)[box.id] == { + 'services_count': 2, 'domains_count': 2} + assert workload_counts_by_server([box.id], None) == {} + assert workload_counts_by_server([], admin) == {} + + +def test_select_can_ask_for_just_the_counts(app, client): + with app.app_context(): + admin = make_user(db, role='admin') + box = make_server(db, name='box') + make_application(db, name='web', user_id=admin.id, server_id=box.id) + headers = headers_for(admin) + + resp = client.get('/api/v1/servers?$select=name,services_count', headers=headers) + assert resp.status_code == 200 + row = resp.get_json()[0] + assert row['services_count'] == 1 + assert 'domains_count' not in row + + +def test_narrow_select_skips_the_counts(app, client): + with app.app_context(): + admin = make_user(db, role='admin') + make_server(db, name='box') + headers = headers_for(admin) + + row = client.get('/api/v1/servers?$select=name', headers=headers).get_json()[0] + assert 'services_count' not in row and 'domains_count' not in row diff --git a/frontend/src/components/backups/BackupsOverview.jsx b/frontend/src/components/backups/BackupsOverview.jsx index 92a36172..b1ba0e59 100644 --- a/frontend/src/components/backups/BackupsOverview.jsx +++ b/frontend/src/components/backups/BackupsOverview.jsx @@ -10,6 +10,7 @@ import { formatBytes } from '@/utils/formatBytes'; import { KpiBand, MetricCard, Pill, DataTable, DataTableFooter } from '@/components/ds'; import EmptyState from '../EmptyState'; import InfoTip from '../InfoTip'; +import { OverviewBoard, OverviewSection } from '@/components/detail/OverviewBoard'; import { useTranslation } from 'react-i18next'; import { formatDuration, formatNumber } from '@/utils/intl'; @@ -100,6 +101,9 @@ const LATEST_COLUMNS = [ // reliably it has been running, where the bytes live, and what happened lately. // The archive table lives on its own Snapshots section — this page answers // "is my data safe?", not "show me every file". +// Dashboard widget types the Backups overview can carry besides its blocks. +const BACKUPS_WIDGET_TYPES = ['note']; + export default function BackupsOverview({ stats, storageConfig, costSummary, schedules = [], backups = [], onGo, storageWarning = false, }) { @@ -254,6 +258,8 @@ export default function BackupsOverview({ return (
+ + + -
+
@@ -342,7 +349,9 @@ export default function BackupsOverview({ ))}
+
+

{t('app.backupsOverview.recentActivity', 'Recent activity')}

@@ -378,9 +387,9 @@ export default function BackupsOverview({
)}
-
+ -
+

{t('app.backupsOverview.storageDestinations', 'Storage destinations')}

@@ -420,7 +429,9 @@ export default function BackupsOverview({

)}
+
+

{t('app.backupsOverview.latestSnapshots', 'Latest backups')}

@@ -447,7 +458,8 @@ export default function BackupsOverview({ /> )}
-
+ +
); } diff --git a/frontend/src/components/dashboard/SetupHealthWidget.jsx b/frontend/src/components/dashboard/SetupHealthWidget.jsx deleted file mode 100644 index 3aef002a..00000000 --- a/frontend/src/components/dashboard/SetupHealthWidget.jsx +++ /dev/null @@ -1,116 +0,0 @@ -import { useEffect, useState } from 'react'; -import { useNavigate } from 'react-router-dom'; -import api from '../../services/api'; -import { ShieldAlert, ShieldCheck, ChevronRight, X } from 'lucide-react'; -import { useTranslation } from 'react-i18next'; -import { Button } from '@/components/ui/button'; - -// Compact "how set-up is this panel" card for the dashboard (admin-only). -// Reads GET /setup-health and shows the score + the top open items, each -// deep-linking to its fix. Collapses to a slim "all set" line when clean — -// no dead card. - -const DISMISS_KEY = 'serverkit.setupHealth.dismissed'; - -const SetupHealthWidget = () => { - const { t } = useTranslation(); - const navigate = useNavigate(); - const [data, setData] = useState(null); - const [loading, setLoading] = useState(true); - const [dismissed, setDismissed] = useState(() => { - try { return localStorage.getItem(DISMISS_KEY) === '1'; } catch { return false; } - }); - - useEffect(() => { - let cancelled = false; - api.getSetupHealth() - .then((res) => { if (!cancelled) setData(res); }) - .catch(() => { /* non-admin or error — widget stays quiet */ }) - .finally(() => { if (!cancelled) setLoading(false); }); - return () => { cancelled = true; }; - }, []); - - if (dismissed) return null; - - if (loading || !data || !data.summary) { - return ( -
- - {t('app.setupHealthWidget.setupHealth', 'Setup health')} - - {loading - ? t('common.checking', 'Checking…') - : t('app.setupHealthWidget.unavailable', 'Unavailable')} - -
- ); - } - - const { summary } = data; - const openCount = Number(summary.critical_open || 0) + Number(summary.recommended_open || 0); - - const dismiss = () => { - setDismissed(true); - try { localStorage.setItem(DISMISS_KEY, '1'); } catch { /* ignore */ } - }; - - // Clean → slim "all set" line, not a big empty card. - if (openCount === 0) { - return ( - - ); - } - - return ( -
- - {t('app.setupHealthWidget.setupHealth', 'Setup health')} - {summary.score}% - - - {summary.critical_open > 0 && t( - 'app.setupHealthWidget.criticalCount', - '{{count}} critical', - { count: summary.critical_open }, - )} - {summary.critical_open > 0 && summary.recommended_open > 0 && ' · '} - {summary.recommended_open > 0 && t( - 'app.setupHealthWidget.recommendedCount', - '{{count}} recommended', - { count: summary.recommended_open }, - )} - - - - -
- ); -}; - -export default SetupHealthWidget; diff --git a/frontend/src/components/dashboard/grid/DashGrid.jsx b/frontend/src/components/dashboard/grid/DashGrid.jsx index 1ab51d26..a40e21c6 100644 --- a/frontend/src/components/dashboard/grid/DashGrid.jsx +++ b/frontend/src/components/dashboard/grid/DashGrid.jsx @@ -36,6 +36,9 @@ export function DashGrid({ onChange, ctx, onWidgetMenu, + // Height of one grid row. The home dashboard uses the default; a host can + // pass a finer row for layouts that need smaller height steps. + rowHeight = GRID_ROW, }) { const { t } = useTranslation(); const hostRef = useRef(null); @@ -44,7 +47,10 @@ export function DashGrid({ // Detach function for the in-flight pointer gesture, so a mid-drag unmount // (or a pointer released outside the viewport) never leaves listeners behind. const detachRef = useRef(null); - const types = useWidgetTypes(); + // A host with its own widget types (an entity overview's page blocks) + // passes them through ctx; the home dashboard uses the registry. + const registeredTypes = useWidgetTypes(); + const types = ctx?.types || registeredTypes; useEffect(() => { const element = hostRef.current; @@ -68,7 +74,7 @@ export function DashGrid({ ? (hostWidth - GRID_GAP * (GRID_COLS - 1)) / GRID_COLS : 0; const stepX = cell + GRID_GAP; - const stepY = GRID_ROW + GRID_GAP; + const stepY = rowHeight + GRID_GAP; // While dragging we paint the previewed layout instead of the committed one. const list = drag ? drag.preview : widgets; @@ -142,9 +148,9 @@ export function DashGrid({ left: widget.x * stepX, top: widget.y * stepY, width: widget.w * cell + (widget.w - 1) * GRID_GAP, - height: widget.h * GRID_ROW + (widget.h - 1) * GRID_GAP, + height: widget.h * rowHeight + (widget.h - 1) * GRID_GAP, zIndex: drag?.id === widget.i ? 5 : 1, - }), [drag, cell, stepX, stepY]); + }), [drag, cell, stepX, stepY, rowHeight]); const hostClassName = useMemo(() => [ 'skw-grid', @@ -156,7 +162,7 @@ export function DashGrid({
{ if (edit && event.target === event.currentTarget) onSelect?.(null); }} diff --git a/frontend/src/components/detail/DetailPage.jsx b/frontend/src/components/detail/DetailPage.jsx new file mode 100644 index 00000000..196fd4aa --- /dev/null +++ b/frontend/src/components/detail/DetailPage.jsx @@ -0,0 +1,77 @@ +import { Link } from 'react-router-dom'; +import PageLayout from '@/layouts/PageLayout'; +import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; +import { cn } from '@/lib/utils'; + +// One anatomy for entity detail pages (services, servers): +// +// top bar Parent / Name [star] [actions] +// identity [tile] Name [status] [badges] +// meta line · meta line +// tabs [Overview] [Logs] … [Settings] +// content +// +// Feature pages own their data, actions and tab bodies; this module owns the +// frame so the two pages cannot drift apart again. +export function DetailPage({ className, topbarClassName, icon, parentTo, parentLabel, name, favorite, actions, children }) { + return ( + + {parentLabel} + + {name} + + )} + meta={favorite} + actions={actions} + > + {children} + + ); +} + +// The entity's name, state and key facts, directly under the top bar. +export function DetailIdentity({ avatar, name, badges, meta, description }) { + return ( +
+ {avatar} +
+
+

{name}

+ {badges} +
+ {meta &&
{meta}
} + {description &&

{description}

} +
+
+ ); +} + +// Separator between facts on the identity meta line. +export function DetailMetaSep() { + return ; +} + +// The tab strip under the identity. `items`: [{ id, label, icon, badge }]. +// Settings always sits at the far end of the strip. +export function DetailTabs({ items, value, onValueChange, ariaLabel, children }) { + return ( + + + {items.map(({ id, label, icon: Icon, badge }) => ( + + {Icon && + ))} + +
{children}
+
+ ); +} diff --git a/frontend/src/components/detail/DetailSettings.jsx b/frontend/src/components/detail/DetailSettings.jsx new file mode 100644 index 00000000..45dafd05 --- /dev/null +++ b/frontend/src/components/detail/DetailSettings.jsx @@ -0,0 +1,44 @@ +import { Button } from '@/components/ui/button'; + +// The settings shell every entity detail page shares (services, servers): +// a grouped section nav on the left, the active section's panels on the right. +// Pages keep their own sections, URL state, permissions and mutation handlers. +// +// groups: [{ label, items: [{ id, label, icon }] }] +export function DetailSettings({ groups, value, onValueChange, ariaLabel, children }) { + return ( +
+ +
{children}
+
+ ); +} + +// One section of the content column: a quiet title above its panel(s). +export function DetailSettingsSection({ title, children }) { + return ( +
+

{title}

+ {children} +
+ ); +} diff --git a/frontend/src/components/detail/OverviewBoard.jsx b/frontend/src/components/detail/OverviewBoard.jsx new file mode 100644 index 00000000..8867b875 --- /dev/null +++ b/frontend/src/components/detail/OverviewBoard.jsx @@ -0,0 +1,465 @@ +import { Children, isValidElement, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { createPortal } from 'react-dom'; +import { useNavigate, useSearchParams } from 'react-router-dom'; +import { Grid2x2, History, LayoutGrid, Plus, SlidersHorizontal } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import api from '@/services/api'; +import { useAuth } from '@/contexts/useAuth'; +import { useToast } from '@/contexts/useToast'; +import useEditingSession from '@/hooks/useEditingSession'; +import { useUnsavedChangesGuard } from '@/hooks/useUnsavedChangesGuard'; +import { usePolling } from '@/hooks/usePolling'; +import { Button } from '@/components/ui/button'; +import ChangeBar from '@/components/ds/ChangeBar'; +import { DashGrid } from '@/components/dashboard/grid/DashGrid'; +import { WidgetLibrary } from '@/components/dashboard/grid/WidgetLibrary'; +import { WidgetEditor } from '@/components/dashboard/grid/WidgetEditor'; +import { WidgetFullscreen } from '@/components/dashboard/grid/WidgetFullscreen'; +import { GRID_GAP, GRID_ROW, compact, findFreeSpot, nextWidgetId, pushDown } from '@/components/dashboard/grid/layout'; +import { useWidgetTypes, getWidgetType } from '@/components/dashboard/widgets/registry'; +import { toastError } from '@/utils/errorMessage'; + +// The Overview tab of an entity detail page, laid out on the dashboard's widget +// grid: the same frames, library, editor and fullscreen view, with the page's +// own cards available as blocks next to the dashboard's widgets. +// +// +// +// …the card… +// +// +// +// A user has one layout per kind (every server page shares their server +// layout; the page's own entity is the board's variable), stored on the server +// like a dashboard. Until they save one, the layout is the sections in the +// order the page declares them. + +// ?layout=edit puts the board in edit mode, so the page's menu can link to it. +const EDIT_PARAM = 'layout'; +const EDIT_VALUE = 'edit'; + +// How often dashboard widgets on the board re-read their data. +const REFRESH_MS = 15000; +// Time range the board's metric widgets read. Fixed for now: the page has no +// range picker of its own. +const BOARD_RANGE = '1h'; + +// The board's rows are half a dashboard row tall: page blocks vary a lot in +// height, and a full row (88px) is too coarse a step for them. Two half rows +// plus the gap between them are exactly one dashboard row, so a dashboard +// widget keeps its size here at twice its row count. +const ROWS_PER_DASHBOARD_ROW = 2; +const BOARD_ROW = (GRID_ROW - GRID_GAP) / ROWS_PER_DASHBOARD_ROW; + +const SECTION_TYPE_PREFIX = 'overview.'; +const sectionTypeId = (kind, id) => `${SECTION_TYPE_PREFIX}${kind}.${id}`; +const isSectionWidget = (widget) => String(widget?.type || '').startsWith(SECTION_TYPE_PREFIX); + +// Declares one block of the page. Renders nothing itself: OverviewBoard reads +// its props and mounts the children where the layout places the block. +// id, title, icon, w (of 12 columns), h (board rows, see BOARD_ROW) +// placed in the default layout unless false +// lead placed ahead of the board's leading dashboard widgets (a notice) +export function OverviewSection() { + return null; +} + +// A section's frame body. The section's content lives in a host element the +// board renders into once; the frame only adopts that element, so moving, +// resizing or opening a block fullscreen never remounts the card inside it. +function SectionWidget({ widget, ctx }) { + const slotRef = useRef(null); + const host = ctx.sectionHosts.get(widget.cfg?.section); + const { adoptVersion, releaseSection } = ctx; + + // Take the section's element whenever it is free to take (first mount, or + // after another frame showing the same section let go of it). + useEffect(() => { + const slot = slotRef.current; + if (slot && host && host.parentNode !== slot) slot.appendChild(host); + }, [host, adoptVersion]); + + // Hand it back only when this frame really goes away. + useEffect(() => { + if (!host) return undefined; + return () => releaseSection(host); + }, [host, releaseSection]); + + return
; +} + +const NO_WIDGET_TYPES = []; +const NO_LEADING_WIDGETS = []; + +// kind what the layout is for: 'server' / 'service' (one layout shared +// by every page of that kind) or a page such as 'monitoring' +// shared true when `kind` covers many pages, so editing says so +// serverVar what dashboard widgets bound to `$server` should read +// widgetTypes ids of dashboard widget types offered on this board +// leading dashboard widgets placed ahead of the sections in the default +// layout: [{ type, w, h, cfg }], h in board rows +// Pass both as module-level constants: they define the board, they are not state. +export function OverviewBoard({ + kind, entityId, entityLabel, shared = false, serverVar, + widgetTypes = NO_WIDGET_TYPES, leading = NO_LEADING_WIDGETS, children, +}) { + const sections = Children.toArray(children).filter(isValidElement).map((child) => child.props); + return ( + + ); +} + +function OverviewBoardInner({ kind, entityId, entityLabel, shared, serverVar, widgetTypeIds, leading, sections }) { + const { t } = useTranslation(); + const toast = useToast(); + const navigate = useNavigate(); + const { isAdmin } = useAuth(); + const [query, setQuery] = useSearchParams(); + const edit = query.get(EDIT_PARAM) === EDIT_VALUE; + + // ---- section hosts ------------------------------------------------------ + // One detached element per section, created once and kept for the life of + // the board. Sections that are not on the grid wait in the hidden park. + const hostsRef = useRef(new Map()); + const parkRef = useRef(null); + const sectionIds = sections.map((section) => section.id); + sectionIds.forEach((id) => { + if (!hostsRef.current.has(id)) { + const host = document.createElement('div'); + host.className = 'sk-overview-section__host'; + hostsRef.current.set(id, host); + } + }); + const sectionKey = sectionIds.join('|'); + // Everything about the sections that shapes the board (not their content, + // which re-renders through the portals below on every pass). + const sectionSignature = sections + .map((section) => [section.id, section.title, section.w, section.h, section.placed, section.lead].join(':')) + .join('|'); + // The same descriptors object for as long as the signature holds, so the + // memos below depend on a real value instead of re-running every render. + const metaRef = useRef({ signature: null, meta: [] }); + if (metaRef.current.signature !== sectionSignature) { + metaRef.current = { + signature: sectionSignature, + meta: sections.map(({ id, title, icon, w, h, placed, lead }) => ({ id, title, icon, w, h, placed, lead })), + }; + } + const sectionMeta = metaRef.current.meta; + + const [adoptVersion, setAdoptVersion] = useState(0); + const releaseSection = useCallback((host) => { + // Park the element, then let any frame that still wants it take it back + // (closing fullscreen returns the block to its frame on the grid). + if (parkRef.current && host.parentNode !== parkRef.current) parkRef.current.appendChild(host); + setAdoptVersion((version) => version + 1); + }, []); + + // Which sections currently render something. A card that hides itself (no + // traffic yet, feature not applicable) simply leaves the layout. + const [present, setPresent] = useState(() => new Set()); + useEffect(() => { + const park = parkRef.current; + const observers = []; + const measure = () => { + const next = new Set(); + hostsRef.current.forEach((host, id) => { if (host.childElementCount > 0) next.add(id); }); + setPresent((current) => ( + current.size === next.size && [...next].every((id) => current.has(id)) ? current : next + )); + }; + hostsRef.current.forEach((host) => { + if (!host.parentNode && park) park.appendChild(host); + const observer = new MutationObserver(measure); + observer.observe(host, { childList: true }); + observers.push(observer); + }); + measure(); + return () => observers.forEach((observer) => observer.disconnect()); + }, [sectionKey]); + + // ---- widget types ------------------------------------------------------- + const registered = useWidgetTypes(); + const types = useMemo(() => { + const sectionTypes = sectionMeta.map((section) => ({ + id: sectionTypeId(kind, section.id), + name: section.title, + icon: section.icon || LayoutGrid, + cat: 'Overview', + desc: section.title, + w: section.w || 6, + h: section.h || 3, + min: [3, 2], + defaultCfg: { section: section.id }, + component: SectionWidget, + section: section.id, + })); + // Dashboard widgets keep their size on the finer rows. + const shared = registered.filter((type) => widgetTypeIds.includes(type.id)).map((type) => ({ + ...type, + h: type.h * ROWS_PER_DASHBOARD_ROW, + min: [type.min?.[0] ?? 2, (type.min?.[1] ?? 1) * ROWS_PER_DASHBOARD_ROW], + })); + return [...sectionTypes, ...shared]; + }, [kind, sectionMeta, registered, widgetTypeIds]); + + const defaults = useMemo(() => { + const widgets = []; + const place = (type, w, h, cfg) => { + widgets.push({ i: nextWidgetId(widgets), type, ...findFreeSpot(widgets, w, h), w, h, cfg }); + }; + const placeSection = (section) => place( + sectionTypeId(kind, section.id), section.w || 6, section.h || 3, { section: section.id }, + ); + const placed = sectionMeta.filter((section) => section.placed !== false); + placed.filter((section) => section.lead).forEach(placeSection); + leading.forEach((item) => place(item.type, item.w, item.h, { ...item.cfg })); + placed.filter((section) => !section.lead).forEach(placeSection); + return widgets; + }, [kind, sectionMeta, leading]); + + // Drop anything a saved layout references that this page no longer offers. + const sanitize = useCallback( + (widgets) => widgets.filter((widget) => getWidgetType(types, widget.type)), + [types], + ); + + // ---- persistence -------------------------------------------------------- + // `board` is the saved row, null while the user is on the shipped layout, + // undefined until the first read returns. + const [board, setBoard] = useState(undefined); + useEffect(() => { + let cancelled = false; + api.getOverviewBoard(kind) + .then((saved) => { if (!cancelled) setBoard(saved); }) + // A failed read must not hide the page: fall back to the default layout. + .catch(() => { if (!cancelled) setBoard(null); }); + return () => { cancelled = true; }; + }, [kind]); + const saved = useMemo( + () => (board?.widgets ? sanitize(board.widgets) : defaults), + [board, defaults, sanitize], + ); + + // ---- editing ------------------------------------------------------------ + const editing = useEditingSession({ baseline: [] }); + const { draft, isDirty, reset: resetEditing, save: saveEditing, transaction } = editing; + const [selectedId, setSelectedId] = useState(null); + const [libraryOpen, setLibraryOpen] = useState(false); + const [fullscreen, setFullscreen] = useState(null); + const [tick, setTick] = useState(0); + usePolling(() => setTick((value) => value + 1), REFRESH_MS, { immediate: false }); + + // Entering edit mode starts a fresh draft from what is on screen. + const wasEditing = useRef(false); + useEffect(() => { + if (edit && !wasEditing.current && board !== undefined) resetEditing(saved); + wasEditing.current = edit && board !== undefined; + }, [edit, board, saved, resetEditing]); + + const setEditing = useCallback((on) => { + const next = new URLSearchParams(query); + if (on) next.set(EDIT_PARAM, EDIT_VALUE); + else next.delete(EDIT_PARAM); + setQuery(next, { replace: true }); + if (!on) { setSelectedId(null); setLibraryOpen(false); } + }, [query, setQuery]); + + const { requestLeave } = useUnsavedChangesGuard({ + isDirty: edit && isDirty, + confirmOptions: { + title: t('app.overviewBoard.discardTitle', 'Discard layout changes?'), + message: t('app.overviewBoard.discardMessage', 'Your saved overview layout stays as it was.'), + confirmText: t('common.actions.discard', 'Discard'), + }, + }); + + const discard = useCallback(async () => { + if (isDirty && !(await requestLeave())) return; + setEditing(false); + }, [isDirty, requestLeave, setEditing]); + + const save = useCallback(async () => { + try { + await saveEditing(async (widgets) => { + // Saving the shipped layout means "no layout of my own": drop + // the saved row so later changes to the default still reach + // this user, instead of pinning them to today's copy of it. + if (JSON.stringify(widgets) === JSON.stringify(defaults)) { + if (board?.id) await api.deleteDashboard(board.id); + setBoard(null); + return widgets; + } + const stored = await api.saveOverviewBoard(kind, widgets); + setBoard(stored); + return stored?.widgets || widgets; + }); + setEditing(false); + toast.success(t('app.overviewBoard.saved', 'Overview layout saved')); + } catch (err) { + toastError(toast, t('app.overviewBoard.couldNotSave', "Couldn't save the overview layout."), err); + } + }, [board, defaults, kind, saveEditing, setEditing, t, toast]); + + const restoreDefaults = useCallback(() => transaction(defaults), [defaults, transaction]); + + const widgets = edit ? draft : saved; + const selected = widgets.find((widget) => widget.i === selectedId) || null; + + // Out of edit mode, blocks with nothing to show leave the layout and the + // rest close the gap. In edit mode every block stays where it was put. + const shown = useMemo(() => { + if (edit) return widgets; + const visible = widgets.filter((widget) => !isSectionWidget(widget) || present.has(widget.cfg?.section)); + if (visible.length === widgets.length) return widgets; + // Re-place the remaining blocks in reading order, keeping their sizes: + // floating them straight up would leave a hole beside a block whose + // neighbour is the one that went away. + const placed = []; + [...visible].sort((a, b) => a.y - b.y || a.x - b.x).forEach((widget) => { + placed.push({ ...widget, ...findFreeSpot(placed, widget.w, widget.h) }); + }); + return placed; + }, [edit, widgets, present]); + + const startEditing = useCallback(() => { if (!edit) setEditing(true); }, [edit, setEditing]); + + const addWidget = (type) => { + const widget = { + i: nextWidgetId(widgets), + type: type.id, + ...findFreeSpot(widgets, type.w, type.h), + w: type.w, + h: type.h, + cfg: structuredClone(type.defaultCfg || {}), + }; + transaction(compact([...widgets, widget])); + setLibraryOpen(false); + setSelectedId(widget.i); + }; + const removeWidget = (widget) => { + transaction(compact(widgets.filter((item) => item.i !== widget.i))); + setSelectedId(null); + }; + const duplicateWidget = (widget) => { + // A page block exists once; only dashboard widgets can be duplicated. + if (isSectionWidget(widget)) return; + const copy = { ...structuredClone(widget), i: nextWidgetId(widgets), ...findFreeSpot(widgets, widget.w, widget.h) }; + transaction([...widgets, copy]); + setSelectedId(copy.i); + }; + const onWidgetMenu = (action, widget) => { + if (action === 'full') { setFullscreen(widget); return; } + // The other actions change the layout, so they open edit mode first. + // The draft is seeded from the saved layout on the next render, so only + // "configure" can be applied straight away; the rest are edit-mode only. + if (!edit) { startEditing(); if (action === 'config') setSelectedId(widget.i); return; } + if (action === 'config') setSelectedId(widget.i); + if (action === 'del') removeWidget(widget); + if (action === 'dup') duplicateWidget(widget); + }; + + const ctx = useMemo(() => ({ + range: BOARD_RANGE, + tick, + // What dashboard widgets bound to `$server` read on this page. + serverVar, + isAdmin, + navigate, + types, + entity: { kind, id: entityId }, + sectionHosts: hostsRef.current, + adoptVersion, + releaseSection, + emptyLabel: t('app.overviewBoard.nothingToShow', 'Nothing to show here right now.'), + }), [tick, kind, entityId, serverVar, isAdmin, navigate, types, adoptVersion, releaseSection, t]); + + // Page blocks already on the board are not offered again. + const placedSections = new Set(widgets.filter(isSectionWidget).map((widget) => widget.cfg?.section)); + const libraryTypes = types.filter((type) => !type.section || !placedSections.has(type.section)); + const resources = serverVar ? [{ id: serverVar, label: entityLabel || String(serverVar), kind: 'server' }] : []; + + return ( +
+ {/* Every section renders exactly once, into its own host element. */} + {sections.map((section) => createPortal(section.children, hostsRef.current.get(section.id), section.id))} + + ); +} diff --git a/frontend/src/components/ds/Drawer.jsx b/frontend/src/components/ds/Drawer.jsx index ecc1c431..afb4f840 100644 --- a/frontend/src/components/ds/Drawer.jsx +++ b/frontend/src/components/ds/Drawer.jsx @@ -23,6 +23,10 @@ import { cn } from '@/lib/utils'; //
…
// // +// +// Pass `headless` when the body opens with its own header (a tab switch, a +// toolbar) that already says what the drawer is: the title is then kept for +// assistive tech only, instead of stacking a heading above the real one. export function Drawer({ open, onOpenChange, @@ -36,24 +40,29 @@ export function Drawer({ className, bodyClassName, flush = false, + headless = false, children, }) { return ( -
- {icon && ( - - {icon} - - )} -
- {/* SheetTitle is required by Radix for a11y; keep it as the visible title. */} - {title} - {subtitle &&
{subtitle}
} + {headless ? ( + {title} + ) : ( +
+ {icon && ( + + {icon} + + )} +
+ {/* SheetTitle is required by Radix for a11y; keep it as the visible title. */} + {title} + {subtitle &&
{subtitle}
} +
+ {headerExtra}
- {headerExtra} -
+ )}
{children}
diff --git a/frontend/src/components/ds/grid/GridFilterDrawer.jsx b/frontend/src/components/ds/grid/GridFilterDrawer.jsx index 2853cf8d..0314b87d 100644 --- a/frontend/src/components/ds/grid/GridFilterDrawer.jsx +++ b/frontend/src/components/ds/grid/GridFilterDrawer.jsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { Filter, Layers, X, Plus, History, GripVertical } from 'lucide-react'; +import { Filter, Layers, X, Plus, History, GripVertical, Search } from 'lucide-react'; import { Drawer } from '../Drawer'; import { Button } from '@/components/ui/button'; import { Switch } from '@/components/ui/switch'; @@ -7,14 +7,21 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@ import { cn } from '@/lib/utils'; import { useTranslation } from 'react-i18next'; import { - OPS, byKey, columnLabel, coerceValue, emptyValueFor, - isFilterable, isSortable, optionsFor, + OPS, applyFilters, byKey, columnLabel, coerceValue, emptyValueFor, + isDecorative, isFilterable, isSortable, optionsFor, } from './fields'; +// A field search only earns its row once the list is long enough to scan. +const FIELD_SEARCH_MIN = 9; + // Two panes behind one drawer, because they are the two halves of "what am I // looking at": FILTERS decides which rows, FIELDS decides which columns (and in // what order, at what density, with which detail line). The header menu is the // fast path for one column; this is the whole picture at once. +// +// The pane switch IS the drawer's header: a title saying "Filters and fields" +// above tabs reading "Filters" and "Fields" only repeated them. The footer +// answers the question a filter always raises: how many rows are left. export function GridFilterDrawer({ open, onOpenChange, columns, rows, cfg, grid, noun = 'rows', // Hosts whose table auto-sizes its columns and has no sub-detail line @@ -26,10 +33,26 @@ export function GridFilterDrawer({ const { t } = useTranslation(); const [tab, setTab] = useState('filters'); const [dragging, setDragging] = useState(null); + const [fieldQuery, setFieldQuery] = useState(''); const map = byKey(columns); const rules = cfg.filters.rules; const filterable = columns.filter(isFilterable); + // A rule can outlive its column's filterability (a saved view from before + // a column changed shape); those are skipped everywhere below. + const liveRules = rules.filter((rule) => isFilterable(map.get(rule.field))); + const allRows = rows || []; + const total = allRows.length; + const matching = applyFilters(allRows, cfg.filters, columns).length; + const singular = noun.replace(/s$/, ''); + const nounFor = (count) => (count === 1 ? singular : noun); + // Action / chevron columns have no name and nothing to toggle, so they are + // neither listed nor counted. + const namedColumns = columns.filter((column) => !isDecorative(column)); + const shownCount = cfg.cols.filter((key) => !isDecorative(map.get(key))).length; + const hiddenCount = namedColumns.length - shownCount; + const fieldNeedle = fieldQuery.trim().toLowerCase(); + const fieldMatches = (column) => !fieldNeedle || columnLabel(column).toLowerCase().includes(fieldNeedle); const patchRule = (id, patch) => grid.setRules( rules.map((r) => (r.id === id ? { ...r, ...patch } : r)), @@ -99,145 +122,191 @@ export function GridFilterDrawer({ ); }; + const panes = [ + { key: 'filters', icon: Filter, label: t('app.gridFilterDrawer.filters', 'Filters'), count: liveRules.length || null }, + { + key: 'fields', + icon: Layers, + label: t('app.gridFilterDrawer.fieldsTab', 'Fields'), + // Only worth a badge when something is hidden. + count: hiddenCount > 0 ? `${shownCount}/${namedColumns.length}` : null, + }, + ]; + return ( } - iconColor="var(--accent-bright)" + headless width={470} flush className="sk-griddrawer" > -
- {[['filters', Filter, 'Filters', rules.length], ['fields', Layers, 'Fields', cfg.cols.length]] - .map(([key, Icon, text, n]) => ( +
+
+ {panes.map(({ key, icon: Icon, label, count }) => ( ))} +
{tab === 'filters' && (
-
-
{t('app.gridFilterDrawer.conditions', 'Conditions')}
- -
- -
- {t('app.gridFilterDrawer.match', 'Match')} -
- {['all', 'any'].map((value) => ( - - ))} -
- {t('app.gridFilterDrawer.ofTheFollowing', 'of the following')} -
- - {rules.length === 0 && ( -
- {t('app.gridFilterDrawer.noConditionsThisViewShowsEvery', 'No conditions. This view shows every')} {noun.replace(/s$/, '')}. -
- )} - - {rules.map((rule, i) => { - const column = map.get(rule.field); - // A rule can outlive its column's filterability — a - // saved view from before a column changed shape, or - // a column whose data went empty. Skip it rather - // than look up OPS[undefined] and crash the drawer. - if (!column || !isFilterable(column)) return null; - return ( -
- {i > 0 && ( -
- {cfg.filters.match === 'all' ? 'and' : 'or'} + {liveRules.length === 0 ? ( +
+

+ {t('app.gridFilterDrawer.nothingFiltered', { + count: total, + noun: nounFor(total), + defaultValue_one: 'The only {{noun}} is showing.', + defaultValue_other: 'All {{count}} {{noun}} are showing.', + })} +

+ {filterable.length > 0 && ( + <> +
{t('app.gridFilterDrawer.filterBy', 'Filter by')}
+
+ {filterable.map((column) => ( + + ))}
- )} -
- - - -
{valueEditor(rule)}
-
-
- ); - })} + + )} +
+ ) : ( + <> + {liveRules.map((rule, i) => { + const column = map.get(rule.field); + return ( +
+ {i > 0 && ( + // The word between two conditions is the switch for how + // they combine; it applies to the whole list. +
+
+ {[ + ['all', t('app.gridFilterDrawer.and', 'and')], + ['any', t('app.gridFilterDrawer.or', 'or')], + ].map(([value, text]) => ( + + ))} +
+
+ )} +
+ + + +
{valueEditor(rule)}
+
+
+ ); + })} + + + )}
)} {tab === 'fields' && ( <> + {namedColumns.length >= FIELD_SEARCH_MIN && ( +
+
+ )} + + {/* In the table, in table order: drag to reorder, switch off to remove. */}
-
{t('app.gridFilterDrawer.fields', 'Fields ·')} {cfg.cols.length} shown
+
{t('app.gridFilterDrawer.shown', 'In the table')}
+ {shownCount}
{ordered.map((key, i) => { const column = map.get(key); - if (!column) return null; - const on = cfg.cols.includes(key); + if (!column || isDecorative(column) || !cfg.cols.includes(key) || !fieldMatches(column)) return null; const locked = !!column.locked || column.hideable === false; return (
setDragging(i)} onDragEnd={() => setDragging(null)} onDragOver={(e) => { @@ -248,12 +317,12 @@ export function GridFilterDrawer({ {columnLabel(column)} {locked - ? pinned + ? {t('app.gridFilterDrawer.pinned', 'pinned')} : ( grid.toggleColumn(key, allKeys)} - aria-label={t('app.gridFilterDrawer.show', 'Show {{value}}', { value: columnLabel(column) })} + aria-label={t('app.gridFilterDrawer.hide', 'Hide {{value}}', { value: columnLabel(column) })} /> )}
@@ -261,6 +330,37 @@ export function GridFilterDrawer({ })}
+ {/* Everything else the table knows about each row. */} + {hiddenCount > 0 && ( +
+
+
{t('app.gridFilterDrawer.available', 'More fields')}
+ {hiddenCount} +
+
+ {namedColumns.filter((column) => !cfg.cols.includes(column.key) && fieldMatches(column)).map((column) => ( + + ))} +
+
+ )} + + {fieldNeedle && !namedColumns.some(fieldMatches) && ( +
+

+ {t('app.gridFilterDrawer.noFieldMatches', 'No field matches "{{query}}".', { query: fieldQuery.trim() })} +

+
+ )} + {(showRowDetail || showDensity) && (
{showRowDetail && ( @@ -313,10 +413,16 @@ export function GridFilterDrawer({
+ {/* What the filters leave: the number this drawer exists to change. */} + + {matching === total + ? t('app.gridFilterDrawer.countAll', '{{count}} {{noun}}', { count: total, noun: nounFor(total) }) + : t('app.gridFilterDrawer.countOf', '{{matching}} of {{total}} {{noun}}', { matching, total, noun: nounFor(total) })} + + -
diff --git a/frontend/src/components/ds/grid/GridToolsMenu.jsx b/frontend/src/components/ds/grid/GridToolsMenu.jsx index 5cf70cb8..79326989 100644 --- a/frontend/src/components/ds/grid/GridToolsMenu.jsx +++ b/frontend/src/components/ds/grid/GridToolsMenu.jsx @@ -1,25 +1,34 @@ import { useState } from 'react'; -import { MoreVertical, Download, RefreshCw, History, Check, Link2, Rows2, Rows3 } from 'lucide-react'; +import { MoreVertical, ChevronLeft, Download, RefreshCw, History, Check, Link2, Rows2, Rows3 } from 'lucide-react'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { cn } from '@/lib/utils'; import { byKey, exportRows } from './fields'; import { useTranslation } from 'react-i18next'; import { Button as SharedButton } from '@/components/ui/button'; -// The toolbar's "⋮" — everything that is neither a filter nor a per-column -// action: export, refresh, row density, and discarding unsaved view changes. -// One button instead of four keeps the top bar the same shape on every page, -// which is the whole point of putting search there. -export function GridToolsMenu({ +// Everything about a table that is neither a filter nor a per-column action: +// copying a link to the view, export, refresh, row density, and discarding +// unsaved view changes. +// +// GridToolsPanel is the content; it is shown either inside its own "⋮" +// popover (GridToolsMenu, below) or inside the view selector's menu +// (GridViewPicker `tools`), where it is `embedded` and reports which pane it +// is on so the host can step aside while the export options are open. +export function GridToolsPanel({ cfg, columns, rows, selectedRows = [], viewName, noun = 'rows', onRefresh, onReset, onDensity, onExported, onCopyLink, // Off for hosts whose table auto-sizes its rows () — showing a // density toggle that changes nothing is worse than not showing one. showDensity = true, + onClose, + embedded = false, + pane: paneProp, + onPaneChange, }) { const { t } = useTranslation(); - const [open, setOpen] = useState(false); - const [pane, setPane] = useState('root'); // root | export + const [ownPane, setOwnPane] = useState('root'); // root | export + const pane = paneProp ?? ownPane; + const setPane = onPaneChange ?? setOwnPane; const [scope, setScope] = useState('view'); const [copied, setCopied] = useState(null); const [allCols, setAllCols] = useState(false); @@ -28,7 +37,7 @@ export function GridToolsMenu({ const set = scope === 'picked' ? selectedRows : rows; const exportCols = allCols ? columns : cfg.cols.map((k) => map.get(k)).filter(Boolean); - const close = () => { setOpen(false); setPane('root'); }; + const close = () => { setPane('root'); onClose?.(); }; const go = (format) => { const n = exportRows( @@ -41,6 +50,115 @@ export function GridToolsMenu({ close(); }; + return pane === 'root' ? ( + <> + {onCopyLink && ( + { + const res = await onCopyLink(); + setCopied(res?.copied ? 'ok' : 'fail'); + setTimeout(() => setCopied(null), 1800); + }} + > + {copied === 'ok' ? : } + {copied === 'ok' ? t('app.gridToolsMenu.linkCopied', 'Link copied') + : copied === 'fail' ? t('app.gridToolsMenu.copyFailed', "Couldn't copy the link. Check clipboard permissions.") + : t('app.gridToolsMenu.copyLinkToThisView', 'Copy link to this view')} + + )} + setPane('export')}> + {t('app.gridToolsMenu.export', 'Export…')} + + {onRefresh && ( + { onRefresh(); close(); }} + > + {t('app.gridToolsMenu.refreshData', 'Refresh data')} + + )} + {showDensity && ( + <> +
+
{t('app.gridToolsMenu.rowDensity', 'Row density')}
+ {[['cozy', 'Cozy', Rows2], ['compact', 'Compact', Rows3]].map(([value, text, Icon]) => ( + onDensity(value)} + > + + {text} + + ))} + + )} +
+ { onReset(); close(); }} + > + {t('app.gridToolsMenu.resetViewChanges', 'Reset view changes')} + + + ) : ( + <> + {embedded ? ( + setPane('root')}> + {t('app.gridToolsMenu.export2', 'Export')} + + ) : ( +
{t('app.gridToolsMenu.export2', 'Export')}
+ )} + setScope('view')} + > + + {t('app.gridToolsMenu.rowsInThisView', 'Rows in this view')} + {rows.length} + + setScope('picked')} + > + + {t('app.gridToolsMenu.selectedRows', 'Selected rows')} + {selectedRows.length} + +
+ setAllCols((v) => !v)} + > + + {t('app.gridToolsMenu.includeHiddenFields', 'Include hidden fields')} + {exportCols.length} + +
+ go('json')}>JSON + go('csv')}>{t('app.gridToolsMenu.downloadCsv', 'Download CSV')} +
+ + ); +} + +// The standalone "⋮" for tables that keep their tools on their own button. +export function GridToolsMenu(props) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const [pane, setPane] = useState('root'); + return ( - {pane === 'root' ? ( - <> - {onCopyLink && ( - { - const res = await onCopyLink(); - setCopied(res?.copied ? 'ok' : 'fail'); - setTimeout(() => setCopied(null), 1800); - }} - > - {copied === 'ok' ? : } - {copied === 'ok' ? t('app.gridToolsMenu.linkCopied', 'Link copied') - : copied === 'fail' ? t('app.gridToolsMenu.copyFailed', "Couldn't copy the link. Check clipboard permissions.") - : t('app.gridToolsMenu.copyLinkToThisView', 'Copy link to this view')} - - )} - setPane('export')}> - {t('app.gridToolsMenu.export', 'Export…')} - - {onRefresh && ( - { onRefresh(); close(); }} - > - {t('app.gridToolsMenu.refreshData', 'Refresh data')} - - )} - {showDensity && ( - <> -
-
{t('app.gridToolsMenu.rowDensity', 'Row density')}
- {[['cozy', 'Cozy', Rows2], ['compact', 'Compact', Rows3]].map(([value, text, Icon]) => ( - onDensity(value)} - > - - {text} - - ))} - - )} -
- { onReset(); close(); }} - > - {t('app.gridToolsMenu.resetViewChanges', 'Reset view changes')} - - - ) : ( - <> -
{t('app.gridToolsMenu.export2', 'Export')}
- setScope('view')} - > - - {t('app.gridToolsMenu.rowsInThisView', 'Rows in this view')} - {rows.length} - - setScope('picked')} - > - - {t('app.gridToolsMenu.selectedRows', 'Selected rows')} - {selectedRows.length} - -
- setAllCols((v) => !v)} - > - - {t('app.gridToolsMenu.includeHiddenFields', 'Include hidden fields')} - {exportCols.length} - -
- go('json')}>JSON - go('csv')}>{t('app.gridToolsMenu.downloadCsv', 'Download CSV')} -
- - )} + setOpen(false)} /> ); diff --git a/frontend/src/components/ds/grid/GridViewPicker.jsx b/frontend/src/components/ds/grid/GridViewPicker.jsx index 84513692..af7445a3 100644 --- a/frontend/src/components/ds/grid/GridViewPicker.jsx +++ b/frontend/src/components/ds/grid/GridViewPicker.jsx @@ -1,11 +1,12 @@ import { useState } from 'react'; import { - ChevronDown, Star, Copy, Trash2, Plus, MoreVertical, Check, History, AlertTriangle, + ChevronDown, Star, Copy, Trash2, Plus, MoreVertical, Check, History, AlertTriangle, SlidersHorizontal, } from 'lucide-react'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { cn } from '@/lib/utils'; import { useTranslation } from 'react-i18next'; import { Button as SharedButton } from '@/components/ui/button'; +import { GridToolsPanel } from './GridToolsMenu'; // The saved-view selector, rendered as the page's own heading rather than yet // another toolbar button — the view IS what you are looking at, so its name is @@ -21,17 +22,30 @@ import { Button as SharedButton } from '@/components/ui/button'; // there instead (see useTopbarChrome) and passes nothing here; an inner or sub // table, which has no top bar of its own, passes it and keeps it inline. // +// A page can instead fold the table's controls INTO this menu, so the page has +// one place for "what am I looking at and what can I do with it" and its top +// bar keeps only the actions that create or reload things: +// +// filters { count, hidden, onOpen } opens the filters and fields drawer +// tools the GridToolsMenu props copy link, export, reset… +// extra [{ icon, label, onSelect }] page-specific entries (Manage groups) +// // There is deliberately no row count. It was rendered twice on every page that // also had a toolbar underneath — once next to the view name, once on the right // of the second bar — and the footer already says how many rows there are, // under the rows it is counting. -export function GridViewPicker({ views, counts, onCreate, label = 'items', actions }) { +export function GridViewPicker({ views, counts, onCreate, label = 'items', actions, filters, tools, extra }) { const { t } = useTranslation(); const [open, setOpen] = useState(false); const [menuFor, setMenuFor] = useState(null); const [creating, setCreating] = useState(false); const [name, setName] = useState(''); const [fromCurrent, setFromCurrent] = useState(true); + // While the tools section shows its export options, the rest of the menu + // steps aside so the options are not buried under the list of views. + const [toolsPane, setToolsPane] = useState('root'); + const exporting = toolsPane !== 'root'; + const closeMenu = () => { setOpen(false); setMenuFor(null); setToolsPane('root'); }; const active = views.activeView; const activeName = active?.name || `All ${label}`; @@ -101,7 +115,7 @@ export function GridViewPicker({ views, counts, onCreate, label = 'items', actio return (
- + { setOpen(o); if (!o) setToolsPane('root'); }}> {activeName} @@ -110,48 +124,102 @@ export function GridViewPicker({ views, counts, onCreate, label = 'items', actio - {!!builtins.length &&
{t('app.gridViewPicker.builtIn', 'Built in')}
} - {builtins.map(renderRow)} -
{t('app.gridViewPicker.myViews', 'My views')}
- {mine.length ? mine.map(renderRow) : ( -
- {t('app.gridViewPicker.noPersonalViewsYetTuneThe', 'No personal views yet. Tune the grid, then save it here.')} -
- )} -
- {creating ? ( + {!exporting && ( <> -
- setName(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter') submitNew(); - if (e.key === 'Escape') setCreating(false); - }} - /> -
+ {!!builtins.length &&
{t('app.gridViewPicker.builtIn', 'Built in')}
} + {builtins.map(renderRow)} +
{t('app.gridViewPicker.myViews', 'My views')}
+ {mine.length ? mine.map(renderRow) : ( +
+ {t('app.gridViewPicker.noPersonalViewsYetTuneThe', 'No personal views yet. Tune the grid, then save it here.')} +
+ )} +
+ {creating ? ( + <> +
+ setName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') submitNew(); + if (e.key === 'Escape') setCreating(false); + }} + /> +
+ setFromCurrent((v) => !v)} + > + + {t('app.gridViewPicker.startFromCurrentFiltersColumns', 'Start from current filters and columns')} + +
+ setCreating(false)}>{t('common.actions.cancel', 'Cancel')} + + {t('common.actions.create', 'Create')} + +
+ + ) : ( + setCreating(true)}> + {t('app.gridViewPicker.saveCurrentView', 'Save current view…')} + + )} + + )} + + {filters && !exporting && ( + <> +
setFromCurrent((v) => !v)} + className="sk-gridmenu__opt" + onClick={() => { closeMenu(); filters.onOpen(); }} > - - {t('app.gridViewPicker.startFromCurrentFiltersColumns', 'Start from current filters and columns')} + {t('app.gridViewPicker.filtersAndFields', 'Filters and fields')} + {(filters.count > 0 || filters.hidden > 0) && ( + + {[ + filters.count > 0 && t('app.gridViewPicker.filterCount', { count: filters.count, defaultValue_one: '1 filter', defaultValue_other: '{{count}} filters' }), + filters.hidden > 0 && t('app.gridViewPicker.moreFields', '{{count}} more fields', { count: filters.hidden }), + ].filter(Boolean).join(' \u00b7 ')} + + )} -
- setCreating(false)}>{t('common.actions.cancel', 'Cancel')} - - {t('common.actions.create', 'Create')} - -
- ) : ( - setCreating(true)}> - {t('app.gridViewPicker.saveCurrentView', 'Save current view…')} - + )} + + {tools && ( + <> + {!exporting &&
} + + + )} + + {!!extra?.length && !exporting && ( + <> +
+ {extra.map(({ icon: Icon, label: text, onSelect }) => ( + { closeMenu(); onSelect(); }} + > + {Icon && }{text} + + ))} + )} diff --git a/frontend/src/components/ds/grid/useTableChrome.js b/frontend/src/components/ds/grid/useTableChrome.js index ff8e6798..a969f186 100644 --- a/frontend/src/components/ds/grid/useTableChrome.js +++ b/frontend/src/components/ds/grid/useTableChrome.js @@ -31,6 +31,8 @@ const NO_FILTERS = { match: 'all', rules: [] }; * every page, which is what makes a saved view, a shareable link and a guard * one concept instead of eleven. */ +const NO_KEYS = []; + export function useTableChrome({ columns, rows = [], @@ -41,6 +43,10 @@ export function useTableChrome({ setSorts, hiddenKeys = [], setHiddenKeys, + // Columns a fresh table keeps out of sight. "Reset" goes back to THIS set, + // not to "show everything": a table that offers twenty fields does not want + // all twenty on screen the moment someone clears a filter. + defaultHiddenKeys = NO_KEYS, groupBy = null, setGroupBy, pageState, @@ -112,8 +118,8 @@ export function useTableChrome({ ), setSub: () => {}, setDensity: () => {}, - resetToView: () => { clearRules(); setHiddenKeys?.([]); setColumnOrder(null); }, - }), [setMatch, removeRule, clearRules, hiddenKeys, setHiddenKeys]); + resetToView: () => { clearRules(); setHiddenKeys?.([...defaultHiddenKeys]); setColumnOrder(null); }, + }), [setMatch, removeRule, clearRules, hiddenKeys, setHiddenKeys, defaultHiddenKeys]); // The envelope. The column rules are `columnFilters`, never `filters`: // three pages persist a `filters` key of their own meaning a SERVER-side diff --git a/frontend/src/components/file-manager/FileManagerToolbar.jsx b/frontend/src/components/file-manager/FileManagerToolbar.jsx index 06ea22e0..c6df8c5d 100644 --- a/frontend/src/components/file-manager/FileManagerToolbar.jsx +++ b/frontend/src/components/file-manager/FileManagerToolbar.jsx @@ -1,25 +1,22 @@ import { - File, + ArrowDown, ArrowLeft, ArrowRight, ArrowUp, - Search, - X, + Check, RefreshCw, - Eye, - EyeOff, HardDrive, PanelLeftClose, PanelLeftOpen, LayoutGrid, List, Home, - ArrowUpDown, + SlidersHorizontal, } from 'lucide-react'; import { Button } from '@/components/ui/button'; - -import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select'; +import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; +import { cn } from '@/lib/utils'; import { useTranslation } from 'react-i18next'; @@ -44,11 +41,8 @@ export default function FileManagerToolbar({ filterCounts, sortValue, handleSortChange, - searchQuery, - setSearchQuery, - handleSearch, - searchResults, - clearSearch, + // The search box, only when the page has no top bar to host it. + search, viewMode, setViewMode, showHidden, @@ -58,6 +52,18 @@ export default function FileManagerToolbar({ loading, }) { const { t } = useTranslation(); + const [sortKey, sortDir] = String(sortValue || 'name-asc').split('-'); + // What the listing can be sorted by, with the direction a fresh pick + // starts in (newest and largest first; names and types A to Z). + const sortKeys = [ + { key: 'name', label: t('common.labels.name', 'Name'), first: 'asc' }, + { key: 'modified', label: t('app.fileManager.modified', 'Modified'), first: 'desc' }, + { key: 'size', label: t('common.labels.size', 'Size'), first: 'desc' }, + { key: 'type', label: t('common.labels.type', 'Type'), first: 'asc' }, + ]; + // Anything other than "everything, hidden files off" is worth a mark on + // the button, since the menu is closed most of the time. + const viewIsNarrowed = activeFilter !== FILTER_OPTIONS[0]?.id || showHidden; return ( <>
@@ -122,7 +128,8 @@ export default function FileManagerToolbar({
{breadcrumbs.map((crumb, idx) => ( - {idx > 0 && /} + {/* The root crumb is itself "/", so the one after it needs no separator. */} + {idx > 0 && breadcrumbs[idx - 1].name !== '/' && /} - )} -
+ {search}
- + {/* One menu for how the listing is shown: which kinds, in what + order, hidden files or not. They were two selects and an + icon, each as wide as the control it sat beside. */} + + + + + +
{t('app.fileManager.show', 'Show')}
+ {FILTER_OPTIONS.map((option) => ( + + ))} + +
+
{t('app.fileManager.sortBy', 'Sort by')}
+ {sortKeys.map((option) => ( + + ))} + + +
+ + + + )} +
+ ); +} diff --git a/frontend/src/components/monitoring/MonitoringOverview.jsx b/frontend/src/components/monitoring/MonitoringOverview.jsx index 168ab1c5..d8564ca5 100644 --- a/frontend/src/components/monitoring/MonitoringOverview.jsx +++ b/frontend/src/components/monitoring/MonitoringOverview.jsx @@ -9,6 +9,7 @@ import { AreaChart, KpiBand, MetricCard, Pill, Sparkline } from '@/components/ds import { Button } from '@/components/ui/button'; import { Skeleton } from '../Skeleton'; import MonitorsSummary from './MonitorsSummary'; +import { OverviewBoard, OverviewSection } from '@/components/detail/OverviewBoard'; import DiskReclaimModal from './DiskReclaimModal'; import { HOST_SCOPE, useScopeMetrics, trendOf } from './useMonitorScope'; import { useTranslation } from 'react-i18next'; @@ -45,6 +46,9 @@ function last(series) { // the Host health grid below is how you switch between them. That grid is what // the standalone Fleet Monitor page used to be — a heatmap you had to leave // this page to read, for numbers that belong next to these ones. +// Dashboard widget types the Monitoring overview can carry besides its blocks. +const MONITORING_WIDGET_TYPES = ['stat', 'gauge', 'timeseries', 'specs', 'note']; + export default function MonitoringOverview({ scope, isHost, scopeLabel, status, activeAlerts = [], speedTest, speedTestRunning, onRunSpeedTest, @@ -195,16 +199,21 @@ export default function MonitoringOverview({ return (
+ {/* Monitors first: "is the site up" is the question this page is for, and everything below describes the machines ServerKit runs on rather than the things it is watching. */} - - -
-

{t('app.monitoringOverview.hostHealth', 'Host health')}

- {scopeLabel} -
+ + + + {/* The shared DS tile, not a monitoring-only copy of it — same geometry as every other KPI strip in the panel, plus the sparkline slot this page needed. */} @@ -258,8 +267,9 @@ export default function MonitoringOverview({ ); })} + -
+
@@ -283,7 +293,9 @@ export default function MonitoringOverview({
+
+
@@ -303,16 +315,13 @@ export default function MonitoringOverview({ />
-
+ {/* The fleet, inline. Clicking a card re-scopes everything above it, which is the whole reason this replaced a separate page. */} + {!fleetLoaded && (
-
-

{t('app.monitoringOverview.allHosts', 'All hosts')}

- -
@@ -320,12 +329,9 @@ export default function MonitoringOverview({ )} {fleet.length > 0 && ( <> -
-

{t('app.monitoringOverview.allHosts', 'All hosts')}

- - {online}/{fleet.length} {t('app.monitoringOverview.onlineClickACardToRe', 'online · click a card to re-scope')} - -
+

+ {online}/{fleet.length} {t('app.monitoringOverview.onlineClickACardToRe', 'online · click a card to re-scope')} +

{/* Always the panel host's own numbers, never the scoped ones — a card in this strip has to keep @@ -359,8 +365,9 @@ export default function MonitoringOverview({
)} + -
+

{t('app.monitoringOverview.activeAlerts', 'Active alerts')}

@@ -385,7 +392,9 @@ export default function MonitoringOverview({
)}
+
+

{t('app.monitoringOverview.speedTest', 'Speed test')}

@@ -429,7 +438,8 @@ export default function MonitoringOverview({

)}
-
+ + setReclaimOpen(false)} />
diff --git a/frontend/src/components/serverdetail/ServerHeaderMeta.jsx b/frontend/src/components/serverdetail/ServerHeaderMeta.jsx deleted file mode 100644 index 1ed9c32d..00000000 --- a/frontend/src/components/serverdetail/ServerHeaderMeta.jsx +++ /dev/null @@ -1,33 +0,0 @@ -import { useTranslation } from 'react-i18next'; -import FavoriteStar from '@/components/FavoriteStar'; -import InfoTip from '@/components/InfoTip'; -import CopyButton from '@/components/CopyButton'; -import { StatusDot } from '../ds'; -import { serverStatusKind } from './serverDetailData'; - -// Header meta: [status dot] [(i) with endpoint + ID] [star]. Everything the -// header used to spell out lives behind the (i). -export default function ServerHeaderMeta({ server }) { - const { t } = useTranslation(); - const status = server.status || 'pending'; - const endpoint = server.hostname || server.ip_address || t('app.serverDetail.noEndpointConfigured', 'No endpoint configured'); - return ( - <> - - -
-
{t('common.labels.status', 'Status')}
-
{status}
-
{t('app.serverDetail.endpoint', 'Endpoint')}
-
{endpoint}
-
{t('app.serverDetail.serverId', 'ID')}
-
- {server.id} - -
-
-
- - - ); -} diff --git a/frontend/src/components/serverdetail/ServerHealthCard.jsx b/frontend/src/components/serverdetail/ServerHealthCard.jsx index 9a97d277..2e2e3b63 100644 --- a/frontend/src/components/serverdetail/ServerHealthCard.jsx +++ b/frontend/src/components/serverdetail/ServerHealthCard.jsx @@ -15,19 +15,22 @@ const checkKind = (status) => { return 'gray'; }; +// Two overview cards that read the same agent report; `part` picks one: +// 'permission' (the agent's permission level) or 'health' (status + checks). // Read-only by design: the permission level is enforced by the agent and can // only be changed on the server itself, so there is deliberately no control. -const ServerHealthCard = ({ server }) => { +const ServerHealthCard = ({ server, part }) => { const { t } = useTranslation(); const [alerts, setAlerts] = useState([]); useEffect(() => { + if (part !== 'health') return undefined; let alive = true; api.getFleetAlerts({ server_id: server.id, status: 'active', limit: 20 }) .then((res) => { if (alive) setAlerts((Array.isArray(res) ? res : []).filter((a) => a.detail)); }) .catch(() => { if (alive) setAlerts([]); }); return () => { alive = false; }; - }, [server.id, server.status, server.last_report_at]); + }, [part, server.id, server.status, server.last_report_at]); const level = server.permission_level_effective || 'full'; const health = serverHealth(server); @@ -48,10 +51,10 @@ const ServerHealthCard = ({ server }) => { { key: 'checked', headerKey: 'app.serverHealthCard.lastChecked', header: 'Last checked', sortable: false, cellClassName: 'sk-cell-dim', render: (c) => (c.checked_at ? formatDateTime(c.checked_at) : '—') }, ]; - return ( - <> -
-

{t('app.serverHealthCard.permissionLevel', 'Permission level')}

+ if (part === 'permission') { + return ( +
+

{t('app.serverHealthCard.permissionLevel', 'Permission level')}

{levelName} @@ -74,28 +77,36 @@ const ServerHealthCard = ({ server }) => {

{SET_HINT}
+ ); + } -
-

{t('app.serverHealthCard.health', 'Health')} {health.code}

+ return ( +
+

{t('app.serverHealthCard.health', 'Health')}

+ + + {health.code} + {server.last_report_at && ( -

- {t('app.serverHealthCard.lastReport', 'Last report')}: {formatDateTime(server.last_report_at)} -

+ )} - {alerts.length > 0 && ( -
    - {alerts.map((a) =>
  • {a.detail}
  • )} -
- )} - -
- + + {alerts.length > 0 && ( +
    + {alerts.map((a) =>
  • {a.detail}
  • )} +
+ )} + +
); }; diff --git a/frontend/src/components/serverdetail/ServerOverviewTab.jsx b/frontend/src/components/serverdetail/ServerOverviewTab.jsx index 0dcba474..d8775652 100644 --- a/frontend/src/components/serverdetail/ServerOverviewTab.jsx +++ b/frontend/src/components/serverdetail/ServerOverviewTab.jsx @@ -1,34 +1,73 @@ import { serverStatusKind } from './serverDetailData'; -import { Pill, KpiBand } from '../ds'; +import { Pill, KpiBand, MetricCard, Gauge } from '../ds'; import OnboardingWizard from '../server/OnboardingWizard'; import SystemStatusCard from './SystemStatusCard'; +import { OverviewBoard, OverviewSection } from '@/components/detail/OverviewBoard'; import ServerHealthCard from './ServerHealthCard'; import { formatBytes } from '@/utils/formatBytes'; import { InfoList, InfoItem } from '../InfoList'; import { useTranslation } from 'react-i18next'; +import { Bot, Cpu, HeartPulse, ListChecks, Server as ServerGlyph, ShieldCheck } from 'lucide-react'; import { formatDateTime } from '@/utils/intl'; import { - KpiTile, - KpiGauge, PulseIcon, ClockIcon, CpuIcon, MemoryIcon, DiskIcon, OfflineIcon, - ServerIcon, HostIcon, NetworkIcon, FolderTinyIcon, - ChipIcon, OsIcon, ArchIcon, - AgentIcon, TagIcon, HashIcon, DockerMiniIcon, } from './serverDetailShared'; +// Dashboard widget types a server overview can carry besides its own blocks. +const SERVER_WIDGET_TYPES = ['stat', 'gauge', 'timeseries', 'specs', 'note']; + +// Dashboard widgets that open the default layout. `$server` is the board's +// variable: on this page it is always the server being viewed. Titles come +// from the metric, so nothing here needs translating. +const SERVER_LEADING_WIDGETS = [ + { type: 'stat', w: 3, h: 4, cfg: { metric: 'cpu', agg: 'last', resource: '$server', spark: true, thresholds: [70, 90] } }, + { type: 'stat', w: 3, h: 4, cfg: { metric: 'ram', agg: 'last', resource: '$server', spark: true, thresholds: [80, 92] } }, + { type: 'stat', w: 3, h: 4, cfg: { metric: 'disk', agg: 'last', resource: '$server', spark: true, thresholds: [75, 90] } }, + { type: 'stat', w: 3, h: 4, cfg: { metric: 'net_in', agg: 'last', resource: '$server', spark: true, thresholds: null } }, + { + type: 'timeseries', w: 8, h: 6, + cfg: { series: [{ resource: '$server', metric: 'cpu' }, { resource: '$server', metric: 'ram' }], legend: true, fill: true }, + }, +]; + +// Usage thresholds for the CPU / memory / disk tiles. +const USAGE_DANGER_PERCENT = 85; +const USAGE_WARN_PERCENT = 70; + +// A percent tile on the shared MetricCard: the value, a thin meter and the +// capacity line underneath. Same tile the service overview's KPI band uses. +const UsageTile = ({ icon, label, percent, color, sub }) => { + const has = Number.isFinite(percent); + const safe = has ? Math.min(Math.max(percent, 0), 100) : 0; + const danger = safe > USAGE_DANGER_PERCENT; + const warn = safe > USAGE_WARN_PERCENT && !danger; + return ( + + + {sub &&
{sub}
} +
+ ); +}; + const ServerOverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => { const { t } = useTranslation(); const formatUptime = (seconds) => { @@ -41,6 +80,7 @@ const ServerOverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => }; const isOnline = server.status === 'online'; + const statusLabel = server.status || 'pending'; const cpuCores = systemInfo?.cpu_cores || server.cpu_cores; const cpuModel = systemInfo?.cpu_model || server.cpu_model; const totalMemory = systemInfo?.total_memory || server.total_memory; @@ -71,59 +111,75 @@ const ServerOverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => />
)} - - } - label={t('common.labels.status', 'Status')} - value={server.status || 'pending'} - tone={isOnline ? 'success' : server.status === 'connecting' ? 'warning' : 'danger'} - /> - } - label={t('common.labels.uptime', 'Uptime')} - value={isOnline ? formatUptime(metrics?.uptime) : '—'} - sub={isOnline && metrics?.uptime ? 'since last boot' : null} - /> - } - label="CPU" - percent={isOnline ? metrics?.cpu_percent : null} - color="var(--accent-bright)" - sub={cpuCores ? `${cpuCores} cores` : null} - /> - } - label={t('common.labels.memory', 'Memory')} - percent={isOnline ? metrics?.memory_percent : null} - color="var(--cyan)" - sub={totalMemory ? formatBytes(totalMemory) : null} - /> - } - label={t('common.labels.disk', 'Disk')} - percent={isOnline ? metrics?.disk_percent : null} - color="var(--green)" - sub={totalDisk ? formatBytes(totalDisk) : null} - /> - + + {/* Only renders while the agent is unreachable, so it leaves + the layout on its own once the server is back. */} + + {!isOnline && ( +
+ +

{t('app.serverOverviewTab.serverOffline', 'Server offline')}

+

+ {server.status === 'pending' + ? t('app.serverOverviewTab.waitingForAgentInstall', 'Waiting for the agent to be installed…') + : t('app.serverOverviewTab.cantReachAgent', "Couldn't connect to the server agent.")} +

+
+ )} +
- {!isOnline && ( -
-
- -

{t('app.serverOverviewTab.serverOffline', 'Server offline')}

-

- {server.status === 'pending' - ? t('app.serverOverviewTab.waitingForAgentInstall', 'Waiting for the agent to be installed…') - : t('app.serverOverviewTab.cantReachAgent', "Couldn't connect to the server agent.")} -

-
-
- )} + {/* The agent's live readings (no history needed). Offered in + the block library; the default layout opens with the + dashboard's metric widgets instead. */} + + + } + tone={isOnline ? 'green' : server.status === 'connecting' ? 'amber' : 'red'} + value={statusLabel.charAt(0).toUpperCase() + statusLabel.slice(1)} + label={t('common.labels.status', 'Status')} + /> + } + tone="accent" + value={isOnline ? formatUptime(metrics?.uptime) : '—'} + label={t('common.labels.uptime', 'Uptime')} + > + {isOnline && metrics?.uptime ?
{t('app.serverOverviewTab.sinceLastBoot', 'since last boot')}
: null} +
+ } + label="CPU" + percent={isOnline ? metrics?.cpu_percent : null} + color="var(--accent-bright)" + sub={cpuCores ? `${cpuCores} cores` : null} + /> + } + label={t('common.labels.memory', 'Memory')} + percent={isOnline ? metrics?.memory_percent : null} + color="var(--cyan)" + sub={totalMemory ? formatBytes(totalMemory) : null} + /> + } + label={t('common.labels.disk', 'Disk')} + percent={isOnline ? metrics?.disk_percent : null} + color="var(--green)" + sub={totalDisk ? formatBytes(totalDisk) : null} + /> +
+
-
-
-

{t('app.serverOverviewTab.serverInformation', 'Server information')}

+ {t('common.labels.status', 'Status')}}> {server.status} @@ -136,10 +192,9 @@ const ServerOverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => value={server.last_seen ? formatDateTime(server.last_seen) : 'Never'} /> -
+ -
-

{t('app.serverOverviewTab.systemInformation', 'System information')}

+ {t('app.serverOverviewTab.operatingSystem', 'Operating system')}} value={osLabel} /> {t('app.serverOverviewTab.architecture', 'Architecture')}} value={systemInfo?.architecture || server.architecture || 'N/A'} /> @@ -152,24 +207,29 @@ const ServerOverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => {t('app.serverOverviewTab.totalMemory', 'Total memory')}} value={formatBytes(totalMemory, { defaultValue: 'N/A' })} /> {t('app.serverOverviewTab.totalDisk', 'Total disk')}} value={formatBytes(totalDisk, { defaultValue: 'N/A' })} /> -
+ -
-

{t('app.serverOverviewTab.agentInformation', 'Agent information')}

+ {t('app.serverOverviewTab.agentVersion', 'Agent version')}} value={server.agent_version || 'Not installed'} mono /> {t('app.serverOverviewTab.agentId', 'Agent ID')}} value={server.agent_id || 'N/A'} mono /> {t('app.serverOverviewTab.dockerVersion', 'Docker version')}} value={server.docker_version || systemInfo?.docker_version || 'N/A'} mono /> {t('common.labels.uptime', 'Uptime')}} value={formatUptime(metrics?.uptime)} /> -
+ - + + + -
+ + + + + -
-
+
+
); }; diff --git a/frontend/src/components/serverdetail/ServerSettingsTab.jsx b/frontend/src/components/serverdetail/ServerSettingsTab.jsx index d36fcce8..acdd8b9e 100644 --- a/frontend/src/components/serverdetail/ServerSettingsTab.jsx +++ b/frontend/src/components/serverdetail/ServerSettingsTab.jsx @@ -1,5 +1,7 @@ import { TOKEN_EXPIRY_OPTIONS } from './serverDetailData'; import { useCallback, useState, useEffect, useId } from 'react'; +import { useNavigate, useParams } from 'react-router-dom'; +import { Server, Tags, KeyRound, Shield, RefreshCw, Trash2 } from 'lucide-react'; import api from '../../services/api'; import { useToast } from '../../contexts/useToast.js'; import { useConfirm } from '../../hooks/useConfirm'; @@ -8,6 +10,8 @@ import { InfoList, InfoItem } from '../InfoList'; import InfoTip from '../InfoTip'; import { DangerZone } from '../DangerZone'; import { Button } from '@/components/ui/button'; +import { Card } from '@/components/ui/card'; +import { DetailSettings, DetailSettingsSection } from '@/components/detail/DetailSettings'; import { Input } from '@/components/ui/input'; import { Textarea } from '@/components/ui/textarea'; import { Pill } from '../ds'; @@ -22,48 +26,57 @@ import { } from '@/components/ui/select'; import TagsPanel from '../shared/TagsPanel'; import { useTranslation } from 'react-i18next'; -import { - KeyIcon, - ServerIcon, - NetworkIcon, - TrashIcon, - TagIcon, -} from './serverDetailShared'; +import { KeyIcon, TrashIcon } from './serverDetailShared'; import { toastError } from '@/utils/errorMessage'; import { formatDateTime } from '@/utils/intl'; // Radix Select items cannot carry an empty value; this stands for "no group". const NO_GROUP = '__none'; -const AgentRegistrationSection = ({ server, onRegenerateToken }) => { - const { t } = useTranslation(); +// The connection-string InfoTip depends on the server's state, so its copy is +// assembled here rather than inline in the section title. +const connectionStringHelp = (server, t) => { const expires = server.registration_expires; const isExpired = expires && new Date(expires) < new Date(); - const isOnline = server.status === 'online'; - - return ( -
-
- -
-

{t('app.serverSettingsTab.connectionString', 'Connection string')} - - {t('app.serverSettingsTab.generateAFreshConnectionStringTo', 'Generate a fresh connection string to pair (or re-pair) this server. Useful after reinstalling the agent: old credentials are gone, but a new string brings the agent right back to this row.')} - {isOnline && ` ${t('app.serverSettingsTab.onlineRegenerateNote', 'This server is online now; a new string only affects re-pairing.')}`} - {isExpired && ` ${t('app.serverSettingsTab.previousTokenExpired', 'The previous token has expired.')}`} -

-

{t('app.serverSettingsTab.pairOrRepair', 'Pair or re-pair this server.')}

-
-
- -
- ); + return [ + t('app.serverSettingsTab.generateAFreshConnectionStringTo', 'Generate a fresh connection string to pair (or re-pair) this server. Useful after reinstalling the agent: old credentials are gone, but a new string brings the agent right back to this row.'), + server.status === 'online' && t('app.serverSettingsTab.onlineRegenerateNote', 'This server is online now; a new string only affects re-pairing.'), + isExpired && t('app.serverSettingsTab.previousTokenExpired', 'The previous token has expired.'), + ].filter(Boolean).join(' '); }; const ServerSettingsTab = ({ server, onUpdate, onRegenerateToken, onDelete }) => { const { t } = useTranslation(); + const navigate = useNavigate(); + // Section lives in the URL (/servers/:id/settings/:section), same as the + // service detail page, so it is shareable and survives a refresh. + const { section: sectionParam } = useParams(); + const settingsGroups = [ + { + label: t('app.settingsTab.general', 'General'), + items: [ + { id: 'general', label: t('app.serverSettingsTab.basicInformation', 'Basic information'), icon: Server }, + { id: 'tags', label: t('app.serverSettingsTab.tags', 'Tags'), icon: Tags }, + ], + }, + { + label: t('app.serverSettingsTab.connection', 'Connection'), + items: [ + { id: 'connection', label: t('app.serverSettingsTab.connectionString', 'Connection string'), icon: KeyRound }, + { id: 'allowlist', label: t('app.serverSettingsTab.ipAllowlist', 'IP allowlist'), icon: Shield }, + { id: 'credentials', label: t('app.serverSettingsTab.apiKeyRotation', 'API key rotation'), icon: RefreshCw }, + ], + }, + { + label: t('app.settingsTab.advanced', 'Advanced'), + items: [ + { id: 'danger', label: t('app.serverSettingsTab.removeServer', 'Remove server'), icon: Trash2 }, + ], + }, + ]; + const settingsItems = settingsGroups.flatMap((group) => group.items); + const section = settingsItems.some((item) => item.id === sectionParam) ? sectionParam : 'general'; + const setSection = (next) => navigate(`/servers/${server.id}/settings/${next}`, { replace: true }); const fieldId = useId(); const { confirm: confirmSettings } = useConfirm(); const [formData, setFormData] = useState({ @@ -172,218 +185,233 @@ const ServerSettingsTab = ({ server, onUpdate, onRegenerateToken, onDelete }) => } return ( -
-
-
-
-
- -
-

{t('app.serverSettingsTab.basicInformation', 'Basic information')}

-

{t('app.serverSettingsTab.identityAndGroupingForThisServer', 'Identity and grouping for this server.')}

-
-
-
- - -
- -
- -