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.

20.0 KB
Raw Blame
import { createSignal, Show, For, createMemo, createEffect, onCleanup } from 'solid-js';
import { useBeforeLeave } from '@solidjs/router';
import type { JSX } from 'solid-js';

import { useLocation, useNavigate } from '@solidjs/router';
import { logger } from '@/utils/logger';
import { t } from '@/i18n';
import { Card } from '@/components/shared/Card';
import { Button } from '@/components/shared/Button';
import { PageHeader } from '@/components/shared/PageHeader';
import { useActiveHorizontalRailItemVisibility } from '@/components/shared/useActiveHorizontalRailItemVisibility';

import { notificationStore } from '@/stores/notifications';
import Calendar from 'lucide-solid/icons/calendar';

import { useWebSocket } from '@/contexts/appRuntime';
import { useResources } from '@/hooks/useResources';
import {
  getAlertActivationFailure,
  getAlertActivationPresentation,
  getAlertActivationSuccess,
  getAlertDeactivationFailure,
  getAlertDeactivationSuccess,
} from '@/utils/alertActivationPresentation';
import {
  getAlertsTabGroups,
  getAlertsMobileTabClass,
  getAlertsSidebarTabClass,
  getAlertsTabTitle,
  isAlertsConfigurationTab,
} from '@/utils/alertTabsPresentation';
import {
  getAlertOverviewHydrationState,
  getAlertsPageHeaderMeta,
} from '@/utils/alertOverviewPresentation';
import {
  getAlertConfigLeaveConfirmation,
  shouldConfirmAlertsLeave,
} from '@/utils/alertConfigPresentation';
import { useAlertsActivation } from '@/stores/alertsActivation';
import LayoutDashboard from 'lucide-solid/icons/layout-dashboard';
import History from 'lucide-solid/icons/history';
import Gauge from 'lucide-solid/icons/gauge';
import Send from 'lucide-solid/icons/send';
import { presentationPolicyIsReadOnly } from '@/stores/sessionPresentationPolicy';
import type { SecurityStatus } from '@/types/config';
import { getOrgID } from '@/utils/apiClient';
import { eventBus } from '@/stores/events';
import { AlertsConfigurationSurface } from '@/features/alerts/AlertsConfigurationSurface';
import { OverviewTab } from '@/features/alerts/OverviewTab';
import { HistoryTab } from '@/features/alerts/tabs/HistoryTab';
import { pathForTab, tabFromPath, type AlertTab, type Override } from '@/features/alerts/types';

export function Alerts(props: { securityStatus?: SecurityStatus | null }) {
  const {
    activeAlerts,
    activeAlertsHydrationStatus,
    refreshActiveAlerts,
    updateAlert,
    removeAlerts,
    alertAcknowledgementRequests,
  } = useWebSocket();
  const { get: getResource, resources: allResources, byType, children } = useResources();
  const navigate = useNavigate();
  const location = useLocation();
  const alertsActivation = useAlertsActivation();
  const [isSwitchingActivation, setIsSwitchingActivation] = createSignal(false);
  const readOnlySession = createMemo(() => presentationPolicyIsReadOnly());
  const [workspaceRevision, setWorkspaceRevision] = createSignal(0);
  const unsubscribeWorkspace = eventBus.on('org_switched', () => {
    setWorkspaceRevision((revision) => revision + 1);
  });
  onCleanup(unsubscribeWorkspace);
  // A copied status with the same facts must preserve drafts and focus. A new
  // reader must never inherit destination credentials or an in-flight editor.
  const configurationReader = createMemo(() => {
    const status = props.securityStatus;
    // requiresAuth describes the install's login configuration, not whether
    // this request authenticated. Signed-in installs still return true.
    const readerKnown =
      status?.requiresAuth === false ||
      status?.detailLevel === 'authenticated' ||
      status?.detailLevel === 'privileged';
    if (!status || !readerKnown || readOnlySession()) return undefined;
    return JSON.stringify([
      workspaceRevision(),
      getOrgID() || 'default',
      status.currentUsername ??
        status.proxyAuthUsername ??
        status.ssoSessionUsername ??
        status.authUsername,
      status.apiTokenHint,
      status.tokenScopes?.slice().sort(),
      status.proxyAuthIsAdmin,
      Object.entries(status.settingsCapabilities ?? {}).sort(([a], [b]) => a.localeCompare(b)),
    ]);
  });
  const isNotificationDeliveryActive = alertsActivation.notificationDeliveryEnabled;
  const alertActivationPresentation = createMemo(() =>
    getAlertActivationPresentation({
      isActive: isNotificationDeliveryActive(),
      isBusy: alertsActivation.isLoading() || isSwitchingActivation(),
    }),
  );

  const handleActivateAlerts = async () => {
    if (alertsActivation.isLoading() || isSwitchingActivation()) {
      return;
    }
    setIsSwitchingActivation(true);
    try {
      const success = await alertsActivation.activate();
      if (success) {
        notificationStore.success(getAlertActivationSuccess());
        try {
          await alertsActivation.refreshActiveAlerts();
        } catch (error) {
          logger.error('Failed to refresh alerts after activation', error);
        }
      } else {
        notificationStore.error(getAlertActivationFailure());
      }
    } finally {
      setIsSwitchingActivation(false);
    }
  };

  const handleDeactivateAlerts = async () => {
    if (isSwitchingActivation()) {
      return;
    }
    setIsSwitchingActivation(true);
    try {
      const success = await alertsActivation.deactivate();
      if (success) {
        notificationStore.success(getAlertDeactivationSuccess());
        try {
          await alertsActivation.refreshActiveAlerts();
        } catch (error) {
          logger.error('Failed to refresh alerts after deactivation', error);
        }
      } else {
        notificationStore.error(getAlertDeactivationFailure());
      }
    } catch (error) {
      logger.error('Deactivate alerts failed', error);
      notificationStore.error(getAlertDeactivationFailure());
    } finally {
      setIsSwitchingActivation(false);
    }
  };

  const [activeTab, setActiveTab] = createSignal<AlertTab>(tabFromPath(location.pathname));
  const [overviewOverrides, setOverviewOverrides] = createSignal<Override[]>([]);
  const alertsPageHeaderMeta = createMemo(() => getAlertsPageHeaderMeta());
  const alertHydrationPresentation = createMemo(() =>
    getAlertOverviewHydrationState(activeAlertsHydrationStatus()),
  );
  const canRenderActiveAlertTruth = createMemo(
    () => !alertsActivation.detectionEnabled() || activeAlertsHydrationStatus() === 'ready',
  );

  const headerMeta = () => alertsPageHeaderMeta()[activeTab()] ?? alertsPageHeaderMeta().default;

  createEffect(() => {
    const currentPath = location.pathname;
    const requestedTab = tabFromPath(currentPath);
    const tab =
      readOnlySession() && isAlertsConfigurationTab(requestedTab) ? 'overview' : requestedTab;

    if (tab !== activeTab()) {
      setActiveTab(tab);
    }

    const expectedPath = pathForTab(tab);

    // Allow sub-paths for thresholds tab (e.g., /alerts/thresholds/infrastructure)
    const isThresholdsSubPath =
      tab === 'thresholds' && currentPath.startsWith('/alerts/thresholds/');

    if (currentPath !== expectedPath && !isThresholdsSubPath) {
      navigate(expectedPath, { replace: true });
    }
  });

  const handleTabChange = (tab: AlertTab) => {
    const targetPath = pathForTab(tab);
    if (location.pathname !== targetPath) {
      navigate(targetPath);
    }
  };

  const [hasUnsavedChanges, setHasUnsavedChanges] = createSignal(false);
  createEffect(() => {
    configurationReader();
    setHasUnsavedChanges(false);
    setOverviewOverrides([]);
  });
  const [showAcknowledged, setShowAcknowledged] = createSignal(true);
  // Quick tip visibility state
  const [showQuickTip, setShowQuickTip] = createSignal(
    localStorage.getItem('hideAlertsQuickTip') !== 'true',
  );

  const dismissQuickTip = () => {
    setShowQuickTip(false);
    localStorage.setItem('hideAlertsQuickTip', 'true');
  };

  // Add beforeunload listener to warn about unsaved changes
  createEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (hasUnsavedChanges()) {
        e.preventDefault();
        e.returnValue = ''; // Standard way to show confirmation dialog
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    onCleanup(() => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    });
  });

  // Warn when navigating within the app. Narrowing the same page (the
  // thresholds search lives in `?q=`, sections in `#`) keeps the edits, so it
  // must not ask on every keystroke.
  useBeforeLeave((e) => {
    if (!shouldConfirmAlertsLeave(e.to, e.from.pathname, hasUnsavedChanges())) return;
    if (!confirm(getAlertConfigLeaveConfirmation())) {
      e.preventDefault();
    }
  });

  const tabGroups = createMemo<
    {
      id: 'status' | 'configuration';
      label: string;
      items: { id: AlertTab; label: string; icon: JSX.Element }[];
    }[]
  >(() =>
    getAlertsTabGroups({ readOnly: readOnlySession() }).map((group) => ({
      ...group,
      items: group.items.map((item) => ({
        ...item,
        icon:
          item.id === 'overview' ? (
            <LayoutDashboard class="w-4 h-4" strokeWidth={2} />
          ) : item.id === 'history' ? (
            <History class="w-4 h-4" strokeWidth={2} />
          ) : item.id === 'thresholds' ? (
            <Gauge class="w-4 h-4" strokeWidth={2} />
          ) : item.id === 'destinations' ? (
            <Send class="w-4 h-4" strokeWidth={2} />
          ) : (
            <Calendar class="w-4 h-4" strokeWidth={2} />
          ),
      })),
    })),
  );

  const flatTabs = createMemo(() => tabGroups().flatMap((group) => group.items));
  let mobileTabListRef: HTMLElement | undefined;
  useActiveHorizontalRailItemVisibility({
    active: activeTab,
    rail: () => mobileTabListRef,
  });
  // Sidebar always starts expanded for discoverability (consistent with Settings)
  // Users can collapse during session but it resets on page reload
  const [sidebarCollapsed, setSidebarCollapsed] = createSignal(false);

  return (
    <div class="space-y-6">
      <PageHeader
        title={headerMeta().title}
        description={headerMeta().description}
        actions={
          <Show when={activeTab() === 'overview' && !readOnlySession()}>
            <label class="flex cursor-pointer items-center gap-3">
              <span class="text-sm font-medium text-base-content">
                {alertActivationPresentation().label}
              </span>
              <span class="relative inline-flex items-center">
                <input
                  type="checkbox"
                  class="sr-only peer"
                  checked={isNotificationDeliveryActive()}
                  disabled={alertsActivation.isLoading() || isSwitchingActivation()}
                  onChange={(event) => {
                    if (event.currentTarget.checked) {
                      void handleActivateAlerts();
                    } else {
                      void handleDeactivateAlerts();
                    }
                  }}
                />
                <span class={alertActivationPresentation().trackClass}>
                  <span class={alertActivationPresentation().thumbClass} />
                </span>
              </span>
            </label>
          </Show>
        }
      />

      <Card padding="none" class="relative lg:flex overflow-hidden">
        <nav
          class={`hidden lg:flex lg:flex-col ${sidebarCollapsed() ? 'w-16' : 'w-72'} ${sidebarCollapsed() ? 'lg:min-w-16 lg:max-w-16 lg:basis-16' : 'lg:min-w-[18rem] lg:max-w-[18rem] lg:basis-[18rem]'} relative border-b border-border lg:border-b-0 lg:border-r lg:align-top shrink-0 transition-all duration-200`}
          aria-label={t('alerts.nav.ariaLabel')}
        >
          <div
            class={`sticky top-0 ${sidebarCollapsed() ? 'px-2' : 'px-4'} py-5 space-y-5 transition-all duration-200`}
          >
            <Show when={!sidebarCollapsed()}>
              <div class="flex items-center justify-between pb-2 border-b border-border">
                <h2 class="text-sm font-semibold text-base-content">{t('alerts.nav.title')}</h2>
                <button
                  type="button"
                  onClick={() => setSidebarCollapsed(true)}
                  class="p-1 rounded-md hover:bg-surface-hover transition-colors"
                  aria-label={t('alerts.nav.collapseSidebar')}
                  aria-controls="alerts-sidebar-menu"
                  aria-expanded="true"
                >
                  <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
                    />
                  </svg>
                </button>
              </div>
            </Show>
            <Show when={sidebarCollapsed()}>
              <button
                type="button"
                onClick={() => setSidebarCollapsed(false)}
                class="w-full p-2 rounded-md hover:bg-surface-hover transition-colors"
                aria-label={t('alerts.nav.expandSidebar')}
                aria-controls="alerts-sidebar-menu"
                aria-expanded="false"
              >
                <svg class="w-5 h-5 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M13 5l7 7-7 7M5 5l7 7-7 7"
                  />
                </svg>
              </button>
            </Show>
            <div id="alerts-sidebar-menu" class="space-y-5">
              <For each={tabGroups()}>
                {(group) => (
                  <div class="space-y-2">
                    <Show when={!sidebarCollapsed()}>
                      <p class="text-xs font-semibold uppercase tracking-wide text-muted">
                        {group.label}
                      </p>
                    </Show>
                    <div class="space-y-1.5">
                      <For each={group.items}>
                        {(item) => (
                          <button
                            type="button"
                            aria-current={activeTab() === item.id ? 'page' : undefined}
                            class={getAlertsSidebarTabClass({
                              isActive: activeTab() === item.id,
                              isDisabled: false,
                              collapsed: sidebarCollapsed(),
                            })}
                            onClick={() => handleTabChange(item.id)}
                            title={getAlertsTabTitle({
                              isDisabled: false,
                              collapsed: sidebarCollapsed(),
                              label: item.label,
                            })}
                          >
                            {item.icon}
                            <Show when={!sidebarCollapsed()}>
                              <span class="truncate">{item.label}</span>
                            </Show>
                          </button>
                        )}
                      </For>
                    </div>
                  </div>
                )}
              </For>
            </div>
          </div>
        </nav>

        <div class="flex-1 overflow-hidden">
          <Show when={flatTabs().length > 0}>
            <div class="lg:hidden border-b border-border">
              <div class="p-1">
                <nav
                  ref={(element) => {
                    mobileTabListRef = element;
                  }}
                  aria-label={t('alerts.nav.ariaLabel')}
                  class="flex w-full overflow-x-auto rounded-md bg-surface-hover p-0.5 touch-scroll scrollbar-hide"
                >
                  <For each={flatTabs()}>
                    {(tab) => (
                      <button
                        type="button"
                        aria-current={activeTab() === tab.id ? 'page' : undefined}
                        class={getAlertsMobileTabClass({
                          isActive: activeTab() === tab.id,
                          isDisabled: false,
                        })}
                        onClick={() => handleTabChange(tab.id)}
                        title={getAlertsTabTitle({
                          isDisabled: false,
                          label: tab.label,
                        })}
                      >
                        <span class="w-full text-center truncate block">{tab.label}</span>
                      </button>
                    )}
                  </For>
                </nav>
              </div>
            </div>
          </Show>

          <div class="p-2 sm:p-6">
            <Show when={activeTab() === 'overview'}>
              <Show
                when={canRenderActiveAlertTruth()}
                fallback={
                  <div
                    class="rounded-lg border border-border bg-surface p-6 sm:p-8"
                    role={activeAlertsHydrationStatus() === 'unavailable' ? 'alert' : 'status'}
                    aria-live="polite"
                  >
                    <div class="max-w-2xl space-y-3">
                      <h2 class="text-lg font-semibold text-base-content">
                        {alertHydrationPresentation().title}
                      </h2>
                      <p class="text-sm leading-6 text-muted">
                        {alertHydrationPresentation().description}
                      </p>
                      <Show when={activeAlertsHydrationStatus() === 'unavailable'}>
                        <Button
                          variant="secondary"
                          size="sm"
                          onClick={() => void refreshActiveAlerts()}
                        >
                          {alertHydrationPresentation().retryLabel}
                        </Button>
                      </Show>
                    </div>
                  </div>
                }
              >
                <OverviewTab
                  overrides={overviewOverrides()}
                  activeAlerts={activeAlerts}
                  updateAlert={updateAlert}
                  acknowledgementRequests={alertAcknowledgementRequests}
                  showQuickTip={showQuickTip}
                  dismissQuickTip={dismissQuickTip}
                  showAcknowledged={showAcknowledged}
                  setShowAcknowledged={setShowAcknowledged}
                  alertsDisabled={() => !alertsActivation.detectionEnabled()}
                />
              </Show>
            </Show>

            <Show when={!readOnlySession()}>
              <Show
                when={configurationReader()}
                keyed
                fallback={
                  <Show when={isAlertsConfigurationTab(activeTab())}>
                    <p role="status" class="text-sm text-muted">
                      Alert settings access is unavailable. Reload Pulse to check access before
                      editing.
                    </p>
                  </Show>
                }
              >
                {(acceptedReader) => (
                  <AlertsConfigurationSurface
                    isCurrentReader={() => configurationReader() === acceptedReader}
                    activeTab={activeTab}
                    allResources={allResources}
                    byType={byType}
                    children={children}
                    activeAlerts={activeAlerts}
                    removeAlerts={removeAlerts}
                    setOverviewOverrides={setOverviewOverrides}
                    hasUnsavedChanges={hasUnsavedChanges}
                    setHasUnsavedChanges={setHasUnsavedChanges}
                    alertsActivationState={alertsActivation.activationState}
                    alertsActivationConfig={alertsActivation.config}
                  />
                )}
              </Show>
            </Show>

            <Show when={activeTab() === 'history'}>
              <HistoryTab getResource={getResource} allResources={allResources} />
            </Show>
          </div>
        </div>
      </Card>
    </div>
  );
}

// Overview Tab - Shows current alert status
// Thresholds Tab - Improved design