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.

23.3 KB
Raw Blame
import { For, Show, createEffect, createMemo } from 'solid-js';
import ChevronDown from 'lucide-solid/icons/chevron-down';
import Trash2 from 'lucide-solid/icons/trash-2';

import { ActionIconButton } from '@/components/shared/Button';
import { Card } from '@/components/shared/Card';
import { TogglePrimitive } from '@/components/shared/Toggle';
import { StatusBadge } from '@/components/shared/StatusBadge';
import {
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
} from '@/components/shared/Table';
import { SectionHeader } from '@/components/shared/SectionHeader';
import { HelpIcon } from '@/components/shared/HelpIcon';
import {
  getGroupedTableRowCellClass,
  getGroupedTableRowClass,
} from '@/components/shared/groupedTableRowPresentation';
import {
  getPlatformTableCellClassForKind,
  getPlatformTableHeadClassForKind,
} from '@/features/platformPage/sharedPlatformPage';
import { PlatformWindowedRows } from '@/features/platformPage/PlatformWindowedRows';
import { AlertResourceMetricEditor } from './AlertResourceMetricEditor';
import { AlertResourceTableRow } from './AlertResourceTableRow';
import { AlertResourceGroupHeader } from './AlertResourceGroupHeader';
import {
  getAlertResourceTableAlertDelayLabel,
  getAlertResourceTableCustomBadgeLabel,
  getAlertResourceTableEmptyState,
  getAlertResourceTableOfflineStateOrder,
  getAlertResourceTableOfflineStatePresentation,
  getAlertResourceTableResetFactoryDefaultsLabel,
  getAlertResourceTableNoResultsState,
} from '@/utils/alertResourceTablePresentation';
import {
  getAlertResourceColumnKind,
  getAlertResourceColumnHeaderTooltip,
  getAlertResourceMetricDelayOverride,
  normalizeAlertResourceMetricKey,
} from './alertResourceTableModel';
import type { OfflineState, Resource, ResourceTableProps } from './ResourceTable';

type AlertResourceRenderItem =
  { kind: 'group'; key: string } | { kind: 'resource'; key: string; resource: Resource };

const OFFLINE_ALERTS_TOOLTIP =
  'Toggle default behavior for powered-off or connectivity alerts for this resource type.';

interface AlertResourceTableDesktopProps {
  table: ResourceTableProps;
  hasRows: () => boolean;
  hasCustomGlobalDefaults: () => boolean;
  isActiveLayout: () => boolean;
  activeMetricInput: () => { resourceId: string; metric: string } | null;
  setActiveMetricInput: (value: { resourceId: string; metric: string } | null) => void;
  showDelayRow: () => boolean;
  setShowDelayRow: (value: boolean) => void;
  selectedIds: () => Set<string>;
  toggleSelection: (id: string, checked: boolean) => void;
  toggleAll: (checked: boolean) => void;
  allSelected: () => boolean;
  someSelected: () => boolean;
}

export function AlertResourceTableDesktop(props: AlertResourceTableDesktopProps) {
  const totalColumnCount = () =>
    props.table.columns.length +
    2 +
    (props.table.showAlertsColumn === false ? 0 : 1) +
    (props.table.showOfflineAlertsColumn ? 1 : 0) +
    (props.table.onBulkEdit ? 1 : 0);

  const nextOfflineState = (state: OfflineState): OfflineState => {
    const order = getAlertResourceTableOfflineStateOrder();
    const idx = order.indexOf(state);
    return order[(idx + 1) % order.length];
  };

  const renderOfflineStateButton = (
    state: OfflineState,
    disabled: boolean,
    onToggle: () => void,
    // What the button sets; its visible state word ends the accessible name.
    name: string,
  ) => {
    const config = getAlertResourceTableOfflineStatePresentation(state);

    return (
      <button
        type="button"
        class={`inline-flex items-center justify-center px-2 py-0.5 text-xs font-medium rounded-sm transition-colors duration-150 focus:outline-hidden focus-visible:ring-2 focus-visible:ring-blue-400 focus-visible:ring-offset-1 ${config.className} ${disabled ? 'opacity-60 cursor-not-allowed pointer-events-none' : ''}`.trim()}
        disabled={disabled}
        onClick={() => {
          if (disabled) return;
          onToggle();
        }}
        title={config.title}
        aria-label={`${name}: ${config.label}`}
      >
        {config.label}
      </button>
    );
  };

  const renderToggleBadge = (config: {
    isEnabled: boolean;
    disabled?: boolean;
    size?: 'sm' | 'md';
    onToggle?: () => void;
    labelEnabled?: string;
    labelDisabled?: string;
    titleEnabled?: string;
    titleDisabled?: string;
    titleWhenDisabled?: string;
    ariaLabel?: string;
  }) => <StatusBadge {...config} />;

  const resourceRows = createMemo<AlertResourceRenderItem[]>(() => {
    if (props.table.groupedResources) {
      const rows: AlertResourceRenderItem[] = [];
      for (const [groupKey, resources] of Object.entries(props.table.groupedResources).sort(
        ([left], [right]) => left.localeCompare(right),
      )) {
        rows.push({ kind: 'group', key: `group:${groupKey}` });
        for (const resource of resources) {
          rows.push({ kind: 'resource', key: `resource:${resource.id}`, resource });
        }
      }
      return rows;
    }
    return (props.table.resources ?? []).map((resource) => ({
      kind: 'resource' as const,
      key: `resource:${resource.id}`,
      resource,
    }));
  });

  const renderResourceRow = (resource: Resource) => (
    <AlertResourceTableRow
      resource={resource}
      columns={props.table.columns}
      editingId={props.table.editingId}
      editingThresholds={props.table.editingThresholds}
      setEditingThresholds={props.table.setEditingThresholds}
      formatMetricValue={props.table.formatMetricValue}
      hasActiveAlert={props.table.hasActiveAlert}
      onEdit={props.table.onEdit}
      onSaveEdit={props.table.onSaveEdit}
      onCancelEdit={props.table.onCancelEdit}
      onRemoveOverride={props.table.onRemoveOverride}
      showAlertsColumn={props.table.showAlertsColumn}
      onToggleDisabled={props.table.onToggleDisabled}
      onToggleNodeConnectivity={props.table.onToggleNodeConnectivity}
      showOfflineAlertsColumn={props.table.showOfflineAlertsColumn}
      globalOfflineSeverity={props.table.globalOfflineSeverity}
      onSetOfflineState={props.table.onSetOfflineState}
      onToggleBackup={props.table.onToggleBackup}
      onToggleSnapshot={props.table.onToggleSnapshot}
      onConfigureResourceIntent={props.table.onConfigureResourceIntent}
      globalDisableFlag={props.table.globalDisableFlag}
      globalDisableOfflineFlag={props.table.globalDisableOfflineFlag}
      editingNote={props.table.editingNote}
      setEditingNote={props.table.setEditingNote}
      activeMetricInput={props.activeMetricInput}
      isActiveLayout={props.isActiveLayout}
      setActiveMetricInput={props.setActiveMetricInput}
      showBulkSelection={Boolean(props.table.onBulkEdit)}
      selected={props.selectedIds().has(resource.id)}
      onToggleSelection={(checked) => props.toggleSelection(resource.id, checked)}
    />
  );

  return (
    <Card padding="none" class="overflow-hidden border border-border" border={false} tone="card">
      <div class="px-4 py-3 border-b border-border">
        <SectionHeader title={props.table.title} size="sm" />
      </div>
      <Table class="w-full whitespace-normal">
        <TableHeader>
          <TableRow class="text-muted">
            <Show when={props.table.onBulkEdit}>
              <TableHead
                class={`${getPlatformTableHeadClassForKind('badge')} w-10 border-r border-border`}
              >
                <input
                  type="checkbox"
                  checked={props.allSelected()}
                  ref={(el) => {
                    createEffect(() => {
                      el.indeterminate = props.someSelected();
                    });
                  }}
                  onChange={(e) => props.toggleAll(e.currentTarget.checked)}
                  class="rounded-sm text-sky-600 focus:ring-sky-500 transition-shadow cursor-pointer"
                  aria-label="Select all resources"
                />
              </TableHead>
            </Show>
            <Show when={props.table.showAlertsColumn !== false}>
              <TableHead class={`${getPlatformTableHeadClassForKind('badge')} w-16`}>
                Alerts
              </TableHead>
            </Show>
            <TableHead class={`${getPlatformTableHeadClassForKind('name')} w-1/4`}>
              Resource
            </TableHead>
            <For each={props.table.columns}>
              {(column) => (
                <TableHead
                  class={`${getPlatformTableHeadClassForKind(getAlertResourceColumnKind(column))} whitespace-normal wrap-break-word`}
                  title={
                    props.table.columnTooltips?.[column] ??
                    getAlertResourceColumnHeaderTooltip(column)
                  }
                >
                  {column}
                </TableHead>
              )}
            </For>
            <Show when={props.table.showOfflineAlertsColumn}>
              <TableHead
                class={getPlatformTableHeadClassForKind('badge')}
                title={OFFLINE_ALERTS_TOOLTIP}
              >
                Offline Alerts
              </TableHead>
            </Show>
            <TableHead class={getPlatformTableHeadClassForKind('badge')}>Actions</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody class="divide-y divide-border">
          <Show
            when={
              props.table.globalDefaults &&
              props.table.setGlobalDefaults &&
              props.table.setHasUnsavedChanges
            }
          >
            <TableRow
              class={`bg-surface-alt ${props.table.globalDisableFlag?.() ? 'opacity-40' : ''}`}
            >
              <Show when={props.table.onBulkEdit}>
                <TableCell
                  class={`${getPlatformTableCellClassForKind('badge')} border-r border-border`}
                />
              </Show>
              <Show when={props.table.showAlertsColumn !== false}>
                <TableCell class={`${getPlatformTableCellClassForKind('badge')} align-middle`}>
                  <Show
                    when={props.table.onToggleGlobalDisable}
                    fallback={
                      <span class="text-sm text-slate-400" aria-hidden="true">
                        -
                      </span>
                    }
                  >
                    <div class="flex items-center justify-center">
                      <TogglePrimitive
                        size="sm"
                        checked={!props.table.globalDisableFlag?.()}
                        onToggle={() => {
                          props.table.onToggleGlobalDisable?.();
                          props.table.setHasUnsavedChanges?.(true);
                        }}
                        class="-my-0.5"
                        title="Global alerts toggle - disable all alerts for this resource type"
                        ariaLabel="Global alerts toggle"
                      />
                    </div>
                  </Show>
                </TableCell>
              </Show>
              <TableCell class={getPlatformTableCellClassForKind('name')}>
                <div class="flex items-center gap-2">
                  <span class="text-sm font-semibold text-base-content">Global Defaults</span>
                  <Show when={props.hasCustomGlobalDefaults()}>
                    <span class="text-xs px-1.5 py-0.5 bg-blue-100 dark:bg-blue-900/25 text-blue-700 dark:text-blue-300 rounded-sm">
                      {getAlertResourceTableCustomBadgeLabel()}
                    </span>
                  </Show>
                </div>
              </TableCell>
              <For each={props.table.columns}>
                {(column) => {
                  const metric = normalizeAlertResourceMetricKey(column);
                  return (
                    <TableCell
                      class={`${getPlatformTableCellClassForKind(getAlertResourceColumnKind(column))} align-middle`}
                    >
                      <Show
                        when={metric !== 'backup' && metric !== 'snapshot'}
                        fallback={
                          <span class="text-sm text-muted" aria-hidden="true">
                            -
                          </span>
                        }
                      >
                        <AlertResourceMetricEditor
                          metric={metric}
                          column={column}
                          scope="default"
                          layout="table"
                          value={props.table.globalDefaults?.[metric]}
                          fallback={props.table.globalDefaultFallbacks?.[metric]}
                          onChange={(value) => {
                            props.table.setGlobalDefaults?.((prev) => ({
                              ...prev,
                              [metric]: value,
                            }));
                            props.table.setHasUnsavedChanges?.(true);
                          }}
                        />
                      </Show>
                    </TableCell>
                  );
                }}
              </For>
              <Show when={props.table.showOfflineAlertsColumn}>
                <TableCell class={`${getPlatformTableCellClassForKind('badge')} align-middle`}>
                  <Show
                    when={props.table.onSetGlobalOfflineState}
                    fallback={
                      <Show
                        when={props.table.onToggleGlobalDisableOffline}
                        fallback={
                          <span class="text-sm text-slate-400" aria-hidden="true">
                            -
                          </span>
                        }
                      >
                        {(() => {
                          const defaultDisabled = props.table.globalDisableOfflineFlag?.() ?? false;

                          return renderToggleBadge({
                            isEnabled: !defaultDisabled,
                            size: 'md',
                            onToggle: () => {
                              props.table.onToggleGlobalDisableOffline?.();
                              props.table.setHasUnsavedChanges?.(true);
                            },
                            labelEnabled: 'On',
                            labelDisabled: 'Off',
                            titleEnabled:
                              'Offline alerts currently enabled by default. Click to disable.',
                            titleDisabled:
                              'Offline alerts currently disabled by default. Click to enable.',
                            ariaLabel: 'Offline alerts default',
                          });
                        })()}
                      </Show>
                    }
                  >
                    {(() => {
                      const disabledGlobally = props.table.globalDisableFlag?.() ?? false;
                      const defaultDisabled = props.table.globalDisableOfflineFlag?.() ?? false;
                      const defaultSeverity = props.table.globalOfflineSeverity ?? 'warning';
                      const state: OfflineState = defaultDisabled
                        ? 'off'
                        : defaultSeverity === 'critical'
                          ? 'critical'
                          : 'warning';

                      return renderOfflineStateButton(
                        state,
                        disabledGlobally,
                        () => {
                          if (disabledGlobally) return;
                          const next = nextOfflineState(state);
                          props.table.onSetGlobalOfflineState?.(next);
                        },
                        'Offline alerts default',
                      );
                    })()}
                  </Show>
                </TableCell>
              </Show>
              <TableCell class={`${getPlatformTableCellClassForKind('badge')} align-middle`}>
                <div class="flex items-center justify-center gap-1">
                  <Show
                    when={
                      props.table.showDelayColumn &&
                      typeof props.table.onMetricDelayChange === 'function'
                    }
                  >
                    <ActionIconButton
                      onClick={() => props.setShowDelayRow(!props.showDelayRow())}
                      label={
                        props.showDelayRow()
                          ? 'Hide alert delay settings'
                          : 'Show alert delay settings'
                      }
                      tone="muted"
                      size="xs"
                    >
                      <ChevronDown
                        class={`w-4 h-4 transition-transform ${props.showDelayRow() ? 'rotate-180' : ''}`}
                        aria-hidden="true"
                      />
                    </ActionIconButton>
                  </Show>
                  <Show when={props.hasCustomGlobalDefaults() && props.table.onResetDefaults}>
                    <ActionIconButton
                      onClick={() => props.table.onResetDefaults?.()}
                      label={getAlertResourceTableResetFactoryDefaultsLabel()}
                      tone="danger"
                      size="xs"
                    >
                      <Trash2 class="w-4 h-4" aria-hidden="true" />
                    </ActionIconButton>
                  </Show>
                  <Show when={!props.table.showDelayColumn && !props.hasCustomGlobalDefaults()}>
                    <span class="text-sm text-slate-400" aria-hidden="true">
                      -
                    </span>
                  </Show>
                </div>
              </TableCell>
            </TableRow>
          </Show>
          <Show
            when={
              props.showDelayRow() &&
              props.table.showDelayColumn &&
              typeof props.table.onMetricDelayChange === 'function'
            }
          >
            <TableRow
              class={`bg-surface-alt ${props.table.globalDisableFlag?.() ? 'opacity-40' : ''}`}
            >
              <Show when={props.table.onBulkEdit}>
                <TableCell
                  class={`${getPlatformTableCellClassForKind('badge')} border-r border-border`}
                />
              </Show>
              <Show when={props.table.showAlertsColumn !== false}>
                <TableCell class={`${getPlatformTableCellClassForKind('badge')} align-middle`}>
                  <span class="text-sm" aria-hidden="true">
                    -
                  </span>
                </TableCell>
              </Show>
              <TableCell class={`${getPlatformTableCellClassForKind('name')} align-middle`}>
                <span class="text-xs font-semibold uppercase tracking-wide text-muted inline-flex items-center gap-1">
                  {getAlertResourceTableAlertDelayLabel()}
                  <HelpIcon contentId="alerts.thresholds.delay" size="xs" />
                </span>
              </TableCell>
              <For each={props.table.columns}>
                {(column) => {
                  const metric = normalizeAlertResourceMetricKey(column);
                  const typeDefaultDelay = props.table.globalDelaySeconds ?? 5;
                  const overrideDelay = getAlertResourceMetricDelayOverride(
                    props.table.metricDelaySeconds,
                    metric,
                  );

                  return (
                    <TableCell
                      class={`${getPlatformTableCellClassForKind(getAlertResourceColumnKind(column))} align-middle`}
                    >
                      <div class="relative flex justify-center w-full">
                        <input
                          type="number"
                          min="0"
                          value={overrideDelay !== undefined ? overrideDelay : ''}
                          placeholder={String(typeDefaultDelay)}
                          class="w-16 rounded-sm border border-border bg-surface px-2 py-0.5 text-sm text-center text-base-content focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                          onInput={(e) => {
                            const raw = e.currentTarget.value;
                            if (raw === '') {
                              props.table.onMetricDelayChange?.(metric, null);
                              props.table.setHasUnsavedChanges?.(true);
                              return;
                            }

                            const parsed = parseInt(raw, 10);
                            if (Number.isNaN(parsed)) {
                              return;
                            }

                            const sanitized = Math.max(0, parsed);
                            props.table.onMetricDelayChange?.(
                              metric,
                              sanitized === typeDefaultDelay ? null : sanitized,
                            );
                            props.table.setHasUnsavedChanges?.(true);
                          }}
                        />
                      </div>
                    </TableCell>
                  );
                }}
              </For>
              <Show when={props.table.showOfflineAlertsColumn}>
                <TableCell class={`${getPlatformTableCellClassForKind('badge')} align-middle`}>
                  <span class="text-sm" aria-hidden="true">
                    -
                  </span>
                </TableCell>
              </Show>
              <TableCell class={`${getPlatformTableCellClassForKind('badge')} align-middle`}>
                <span class="text-sm" aria-hidden="true">
                  -
                </span>
              </TableCell>
            </TableRow>
          </Show>
          <Show when={resourceRows().length > 0}>
            <PlatformWindowedRows items={resourceRows} estimatedRowHeight={40}>
              {(item) =>
                item.kind === 'group' ? (
                  <TableRow class={getGroupedTableRowClass()}>
                    <TableCell colspan={totalColumnCount()} class={getGroupedTableRowCellClass()}>
                      <AlertResourceGroupHeader
                        groupKey={item.key.slice('group:'.length)}
                        meta={props.table.groupHeaderMeta?.[item.key.slice('group:'.length)]}
                      />
                    </TableCell>
                  </TableRow>
                ) : (
                  renderResourceRow(item.resource)
                )
              }
            </PlatformWindowedRows>
          </Show>
          <Show
            when={
              !props.table.groupedResources &&
              props.table.resources &&
              props.table.resources.length === 0
            }
          >
            <TableRow>
              <TableCell
                colspan={totalColumnCount()}
                class={`${getPlatformTableCellClassForKind('badge')} px-4 py-8 text-sm text-muted`}
              >
                {getAlertResourceTableNoResultsState(props.table.title)}
              </TableCell>
            </TableRow>
          </Show>
          <Show when={props.hasRows() === false}>
            <TableRow>
              <TableCell
                colspan={totalColumnCount()}
                class={`${getPlatformTableCellClassForKind('badge')} px-4 py-6 text-sm text-muted`}
              >
                {getAlertResourceTableEmptyState(props.table.emptyMessage)}
              </TableCell>
            </TableRow>
          </Show>
        </TableBody>
      </Table>
    </Card>
  );
}