Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Convert Alerts history to FilterBar with URL-backed filter state

rcourtman94757c7539a7
diff --git a/frontend-modern/src/features/alerts/AlertHistoryFiltersCard.tsx b/frontend-modern/src/features/alerts/AlertHistoryFiltersCard.tsx
index 0671849bba..be956ad014 100644
--- a/frontend-modern/src/features/alerts/AlertHistoryFiltersCard.tsx
+++ b/frontend-modern/src/features/alerts/AlertHistoryFiltersCard.tsx
@@ -1,70 +1,77 @@
-import { Card } from '@/components/shared/Card';
-import { LabeledFilterSelect } from '@/components/shared/FilterToolbar';
-import { PageControls } from '@/components/shared/PageControls';
-import { SearchInput } from '@/components/shared/SearchInput';
+import { FilterBar, type FilterDef } from '@/components/shared/FilterBar';
+import { STORAGE_KEYS } from '@/utils/localStorage';
import {
ALERT_HISTORY_ALL_TIME_FILTER_LABEL,
getAlertHistorySearchPlaceholder,
} from '@/utils/alertOverviewPresentation';
-
+import type { AlertHistoryRange, AlertSeverityFilter } from './alertHistoryModel';
import type { AlertHistoryState } from './useAlertHistoryState';
+const severityDot = (className: string) => <span class={`h-2 w-2 rounded-full ${className}`} />;
+
interface AlertHistoryFiltersCardProps {
state: AlertHistoryState;
isMobile: boolean;
}
export function AlertHistoryFiltersCard(props: AlertHistoryFiltersCardProps) {
+ const buildFilters = (): FilterDef[] => [
+ {
+ id: 'alert-period',
+ label: 'Period',
+ group: 'scope',
+ inline: true,
+ value: props.state.timeFilter,
+ setValue: (value: string) => props.state.setTimeFilter(value as AlertHistoryRange),
+ defaultValue: '7d',
+ options: () => [
+ { value: '24h', label: 'Last 24h' },
+ { value: '7d', label: 'Last 7d' },
+ { value: '30d', label: 'Last 30d' },
+ { value: 'all', label: ALERT_HISTORY_ALL_TIME_FILTER_LABEL },
+ ],
+ },
+ {
+ id: 'alert-severity',
+ label: 'Severity',
+ group: 'status',
+ inline: true,
+ value: props.state.severityFilter,
+ setValue: (value: string) =>
+ props.state.setSeverityFilter(value as AlertSeverityFilter),
+ defaultValue: 'all',
+ options: () => [
+ { value: 'all', label: 'All' },
+ {
+ value: 'critical',
+ label: 'Critical',
+ leading: severityDot('bg-red-500'),
+ tone: 'danger',
+ },
+ {
+ value: 'warning',
+ label: 'Warning',
+ leading: severityDot('bg-amber-500'),
+ tone: 'warning',
+ },
+ ],
+ },
+ ];
+
return (
- <Card padding="sm" class="mb-4">
- <PageControls
- search={
- <SearchInput
- value={props.state.searchTerm}
- onChange={props.state.setSearchTerm}
- placeholder={getAlertHistorySearchPlaceholder()}
- class="w-full"
- clearOnEscape
- history={{ storageKey: props.state.STORAGE_KEYS.ALERTS_SEARCH_HISTORY }}
- />
- }
- mobileFilters={{
- enabled: props.isMobile,
- onToggle: () => props.state.setFiltersOpen((open) => !open),
- count: props.state.activeFilterCount(),
- }}
- showFilters={!props.isMobile || props.state.filtersOpen()}
- >
- <LabeledFilterSelect
- id="alert-time-filter"
- label="Period"
- value={props.state.timeFilter()}
- onChange={(event) =>
- props.state.setTimeFilter(event.currentTarget.value as '24h' | '7d' | '30d' | 'all')
- }
- selectClass="min-w-[7rem]"
- >
- <option value="24h">Last 24h</option>
- <option value="7d">Last 7d</option>
- <option value="30d">Last 30d</option>
- <option value="all">{ALERT_HISTORY_ALL_TIME_FILTER_LABEL}</option>
- </LabeledFilterSelect>
- <LabeledFilterSelect
- id="alert-severity-filter"
- label="Severity"
- value={props.state.severityFilter()}
- onChange={(event) =>
- props.state.setSeverityFilter(
- event.currentTarget.value as 'warning' | 'critical' | 'all',
- )
- }
- selectClass="min-w-[7rem]"
- >
- <option value="all">All</option>
- <option value="critical">Critical</option>
- <option value="warning">Warning</option>
- </LabeledFilterSelect>
- </PageControls>
- </Card>
+ <FilterBar
+ role="group"
+ ariaLabel="Alert history filters"
+ isMobile={() => props.isMobile}
+ savedViewsKey="alerts-history"
+ search={{
+ value: props.state.searchTerm,
+ setValue: props.state.setSearchTerm,
+ placeholder: getAlertHistorySearchPlaceholder(),
+ historyKey: STORAGE_KEYS.ALERTS_SEARCH_HISTORY,
+ clearOnEscape: true,
+ }}
+ filters={buildFilters()}
+ />
);
}
diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertHistoryState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertHistoryState.test.tsx
index c289f0f0f0..5ea8dddbd0 100644
--- a/frontend-modern/src/features/alerts/__tests__/useAlertHistoryState.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/useAlertHistoryState.test.tsx
@@ -7,6 +7,41 @@ import { eventBus } from '@/stores/events';
import { useAlertHistoryState } from '../useAlertHistoryState';
+const mockRouterPathname = '/alerts/history';
+const [mockRouterSearch, setMockRouterSearch] = createSignal('');
+
+const setMockLocation = (search: string) => {
+ setMockRouterSearch(search);
+ if (typeof window !== 'undefined') {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: {
+ ...window.location,
+ pathname: mockRouterPathname,
+ search,
+ },
+ });
+ }
+};
+
+const navigateSpy = vi.fn((path: string) => {
+ const queryIndex = path.indexOf('?');
+ setMockLocation(queryIndex >= 0 ? path.slice(queryIndex) : '');
+});
+
+vi.mock('@solidjs/router', () => ({
+ useLocation: () => ({
+ get pathname() {
+ return mockRouterPathname;
+ },
+ get search() {
+ return mockRouterSearch();
+ },
+ }),
+ useNavigate: () => navigateSpy,
+}));
+
vi.mock('@/api/alerts', () => ({
AlertsAPI: {
addIncidentNote: vi.fn(),
@@ -42,6 +77,8 @@ describe('useAlertHistoryState', () => {
vi.mocked(AlertsAPI.getIncidentsForResource).mockReset();
vi.mocked(AlertsAPI.clearHistory).mockReset();
vi.mocked(eventBus.on).mockClear();
+ navigateSpy.mockClear();
+ setMockLocation('');
vi.stubGlobal('confirm', vi.fn(() => true));
localStorage.clear();
});
diff --git a/frontend-modern/src/features/alerts/useAlertHistoryState.ts b/frontend-modern/src/features/alerts/useAlertHistoryState.ts
index 6ded3c401c..892cda1fef 100644
--- a/frontend-modern/src/features/alerts/useAlertHistoryState.ts
+++ b/frontend-modern/src/features/alerts/useAlertHistoryState.ts
@@ -1,8 +1,8 @@
import { createEffect, createMemo, createSignal, onCleanup, onMount } from 'solid-js';
import type { Accessor } from 'solid-js';
+import { useLocation, useNavigate } from '@solidjs/router';
import { AlertsAPI } from '@/api/alerts';
-import { usePersistentSignal } from '@/hooks/usePersistentSignal';
import { eventBus } from '@/stores/events';
import { notificationStore } from '@/stores/notifications';
import type { Alert } from '@/types/api';
@@ -40,27 +40,68 @@ export interface UseAlertHistoryStateProps {
allResources: () => Resource[];
}
+const DEFAULT_TIME_FILTER: AlertHistoryRange = '7d';
+const DEFAULT_SEVERITY_FILTER: AlertSeverityFilter = 'all';
+
+const parsePeriod = (raw: string | null | undefined): AlertHistoryRange =>
+ raw === '24h' || raw === '7d' || raw === '30d' || raw === 'all' ? raw : DEFAULT_TIME_FILTER;
+
+const parseSeverity = (raw: string | null | undefined): AlertSeverityFilter =>
+ raw === 'warning' || raw === 'critical' ? raw : DEFAULT_SEVERITY_FILTER;
+
export function useAlertHistoryState(props: UseAlertHistoryStateProps) {
- const [timeFilter, setTimeFilter] = usePersistentSignal<AlertHistoryRange>(
- 'alertHistoryTimeFilter',
- '7d',
- {
- deserialize: (raw) =>
- raw === '24h' || raw === '7d' || raw === '30d' || raw === 'all' ? raw : '7d',
- },
- );
- const [severityFilter, setSeverityFilter] = usePersistentSignal<AlertSeverityFilter>(
- 'alertHistorySeverityFilter',
- 'all',
- {
- deserialize: (raw) => (raw === 'warning' || raw === 'critical' ? raw : 'all'),
- },
- );
- const [searchTerm, setSearchTerm] = createSignal('');
+ const location = useLocation();
+ const navigate = useNavigate();
+
+ const timeFilter: Accessor<AlertHistoryRange> = () =>
+ parsePeriod(new URLSearchParams(location.search).get('period'));
+ const severityFilter: Accessor<AlertSeverityFilter> = () =>
+ parseSeverity(new URLSearchParams(location.search).get('severity'));
+ const searchTerm: Accessor<string> = () =>
+ new URLSearchParams(location.search).get('q') ?? '';
+
+ const updateSearchParam = (
+ mutate: (params: URLSearchParams) => void,
+ ): void => {
+ const params = new URLSearchParams(location.search);
+ mutate(params);
+ const query = params.toString();
+ navigate(`${location.pathname}${query ? `?${query}` : ''}`, { replace: true });
+ };
+
+ const setTimeFilter = (value: AlertHistoryRange): void => {
+ updateSearchParam((params) => {
+ if (value === DEFAULT_TIME_FILTER) {
+ params.delete('period');
+ } else {
+ params.set('period', value);
+ }
+ });
+ };
+
+ const setSeverityFilter = (value: AlertSeverityFilter): void => {
+ updateSearchParam((params) => {
+ if (value === DEFAULT_SEVERITY_FILTER) {
+ params.delete('severity');
+ } else {
+ params.set('severity', value);
+ }
+ });
+ };
+
+ const setSearchTerm = (value: string): void => {
+ updateSearchParam((params) => {
+ if (value === '') {
+ params.delete('q');
+ } else {
+ params.set('q', value);
+ }
+ });
+ };
+
const [alertHistory, setAlertHistory] = createSignal<Alert[]>([]);
const [loading, setLoading] = createSignal(true);
const [selectedBarIndex, setSelectedBarIndex] = createSignal<number | null>(null);
- const [filtersOpen, setFiltersOpen] = createSignal(false);
const resourceIncidentsState = useAlertResourceIncidentsState();
const {
@@ -131,6 +172,36 @@ export function useAlertHistoryState(props: UseAlertHistoryStateProps) {
});
onMount(() => {
+ // Migrate legacy localStorage-backed filter prefs into the URL on first
+ // visit after upgrade. Keeps the dead localStorage keys in place rather
+ // than evicting them; harmless and avoids an eviction migration.
+ if (typeof window !== 'undefined') {
+ const params = new URLSearchParams(window.location.search);
+ let mutated = false;
+
+ if (!params.has('period')) {
+ const legacy = window.localStorage.getItem('alertHistoryTimeFilter');
+ const parsed = parsePeriod(legacy);
+ if (parsed !== DEFAULT_TIME_FILTER && legacy === parsed) {
+ params.set('period', parsed);
+ mutated = true;
+ }
+ }
+
+ if (!params.has('severity')) {
+ const legacy = window.localStorage.getItem('alertHistorySeverityFilter');
+ const parsed = parseSeverity(legacy);
+ if (parsed !== DEFAULT_SEVERITY_FILTER && legacy === parsed) {
+ params.set('severity', parsed);
+ mutated = true;
+ }
+ }
+
+ if (mutated) {
+ navigate(`${location.pathname}?${params.toString()}`, { replace: true });
+ }
+ }
+
void fetchHistory(timeFilter());
const unsubscribeOrgSwitched = eventBus.on('org_switched', () => {
@@ -232,8 +303,6 @@ export function useAlertHistoryState(props: UseAlertHistoryStateProps) {
expandedResourceIncidentIds: resourceIncidentsState.expandedResourceIncidentIds,
resourceIncidentEventFilters: resourceIncidentsState.resourceIncidentEventFilters,
setResourceIncidentEventFilters: resourceIncidentsState.setResourceIncidentEventFilters,
- filtersOpen,
- setFiltersOpen,
activeFilterCount,
incidentTimelines,
incidentLoading,