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.

27.9 KB
Raw Blame
import { For, Show, createMemo } from 'solid-js';
import Check from 'lucide-solid/icons/check';
import Pencil from 'lucide-solid/icons/pencil';
import RotateCcw from 'lucide-solid/icons/rotate-ccw';
import Timer from 'lucide-solid/icons/timer';
import X from 'lucide-solid/icons/x';

import { ActionIconButton } from '@/components/shared/Button';
import { Card } from '@/components/shared/Card';
import { FormTextarea } from '@/components/shared/FormTextarea';
import { TogglePrimitive } from '@/components/shared/Toggle';
import { StatusBadge } from '@/components/shared/StatusBadge';
import { AlertResourceMetricEditor } from './AlertResourceMetricEditor';
import { AlertResourceGroupHeader } from './AlertResourceGroupHeader';
import { PlatformWindowedList } from '@/features/platformPage/PlatformWindowedList';
import {
  getAlertResourceTableCustomBadgeLabel,
  getAlertResourceTableEditNotePlaceholder,
  getAlertResourceTableEmptyState,
  getAlertResourceTableOfflineStateOrder,
  getAlertResourceTableOfflineStatePresentation,
  getAlertResourceTableRevertToDefaultsLabel,
} from '@/utils/alertResourceTablePresentation';
import {
  alertResourceSupportsMetric,
  buildAlertResourceEditPayload,
  getAlertResourceLabel,
  getAlertResourceInitialEditMetric,
  getAlertResourceMetricDisplayValue,
  getAlertResourceRelaxedTriggerSummary,
  isAlertResourceMetricOverridden,
  getAlertResourceIntentTargetLabel,
  getAlertResourcePreferredIntentSignal,
  normalizeAlertResourceMetricKey,
} from './alertResourceTableModel';
import type { Resource } from '@/features/alerts/thresholds/tableTypes';
import { AlertResourceRelaxedTriggers } from './AlertResourceRelaxedTriggers';
import type { OfflineState, ResourceTableProps } from './ResourceTable';

interface AlertResourceTableMobileProps {
  table: ResourceTableProps;
  hasRows: () => boolean;
  hasCustomGlobalDefaults: () => boolean;
  activeMetricInput: () => { resourceId: string; metric: string } | null;
  setActiveMetricInput: (value: { resourceId: string; metric: string } | null) => void;
}

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

export function AlertResourceTableMobile(props: AlertResourceTableMobileProps) {
  const mobileItems = createMemo<AlertResourceMobileItem[]>(() => {
    if (!props.table.groupedResources) {
      return (props.table.resources ?? []).map((resource) => ({
        kind: 'resource' as const,
        key: `resource:${resource.id}`,
        resource,
      }));
    }

    const items: AlertResourceMobileItem[] = [];
    for (const [groupName, resources] of Object.entries(props.table.groupedResources).sort(
      ([left], [right]) => left.localeCompare(right),
    )) {
      items.push({ kind: 'group', key: `group:${groupName}`, groupName });
      for (const resource of resources) {
        items.push({ kind: 'resource', key: `resource:${resource.id}`, resource });
      }
    }
    return items;
  });

  const getThresholds = (resource: Resource, isEditing: boolean) =>
    isEditing ? props.table.editingThresholds() : (resource.thresholds ?? {});

  const getDisplayValue = (resource: Resource, metric: string, isEditing: boolean) =>
    getAlertResourceMetricDisplayValue(
      resource,
      metric,
      props.table.editingThresholds(),
      isEditing,
    );

  const startEditing = (resource: Resource, metric?: string, event?: MouseEvent) => {
    event?.stopPropagation();
    if (resource.editable === false) {
      return;
    }
    const initialMetric =
      metric ?? getAlertResourceInitialEditMetric(props.table.columns, resource.type);
    if (initialMetric) {
      props.setActiveMetricInput({ resourceId: resource.id, metric: initialMetric });
    }
    const payload = buildAlertResourceEditPayload(resource);
    props.table.onEdit(resource.id, payload.thresholds, payload.defaults, payload.note);
  };

  const cancelEditing = () => {
    props.table.onCancelEdit();
    props.setActiveMetricInput(null);
  };

  const saveEditing = (resourceId: string) => {
    props.table.onSaveEdit(resourceId);
    props.setActiveMetricInput(null);
  };

  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 min-h-11 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 sm:min-h-0 ${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>
    );
  };

  // The value a metric cell shows, which its accessible name repeats so a
  // screen reader hears the current threshold and voice control can say it.
  const metricValueText = (metric: string, value: number) =>
    value <= 0 ? 'Off' : props.table.formatMetricValue(metric, value);

  const MetricValueWithHeat = (metricProps: {
    resource: Resource;
    metric: string;
    value: number;
    isOverridden: boolean;
  }) => {
    const isDisabledMetric = metricProps.value <= 0;
    const displayText = metricValueText(metricProps.metric, metricProps.value);

    return (
      <div
        class={`flex items-center justify-center gap-1 ${isDisabledMetric ? 'opacity-60' : ''}`.trim()}
        title={isDisabledMetric ? 'Disabled (no alerts for this metric)' : ''}
      >
        <span
          class={`text-sm ${
            isDisabledMetric
              ? 'text-muted italic'
              : metricProps.isOverridden
                ? 'text-base-content font-bold'
                : 'text-base-content'
          }`}
        >
          {displayText}
        </span>
        <Show when={props.table.hasActiveAlert(metricProps.resource, metricProps.metric)}>
          <div class="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" title="Active alert" />
        </Show>
      </div>
    );
  };

  return (
    <div class="space-y-4">
      <Show
        when={
          props.table.globalDefaults &&
          props.table.setGlobalDefaults &&
          props.table.setHasUnsavedChanges
        }
      >
        <Card
          padding="sm"
          class="border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/25"
        >
          <div class="flex justify-between items-center mb-3">
            <div class="flex items-center gap-2">
              <span class="font-semibold text-sm">Global Defaults</span>
              <Show when={props.hasCustomGlobalDefaults()}>
                <span class="text-[10px] 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>
            <Show
              when={props.table.showAlertsColumn !== false && props.table.onToggleGlobalDisable}
            >
              <TogglePrimitive
                size="sm"
                checked={!props.table.globalDisableFlag?.()}
                onToggle={() => {
                  props.table.onToggleGlobalDisable?.();
                  props.table.setHasUnsavedChanges?.(true);
                }}
                ariaLabel="Global alerts toggle"
              />
            </Show>
          </div>

          <div class="grid grid-cols-2 gap-2">
            <For
              each={props.table.columns.filter((column) => {
                const metric = normalizeAlertResourceMetricKey(column);
                return metric !== 'backup' && metric !== 'snapshot';
              })}
            >
              {(column) => {
                const metric = normalizeAlertResourceMetricKey(column);
                return (
                  <div class="p-2 bg-surface rounded-sm border border-border-subtle flex flex-col gap-1">
                    <span class="text-[10px] uppercase text-slate-500 font-medium">{column}</span>
                    <AlertResourceMetricEditor
                      metric={metric}
                      column={column}
                      scope="default"
                      layout="card"
                      value={props.table.globalDefaults?.[metric]}
                      fallback={props.table.globalDefaultFallbacks?.[metric]}
                      onChange={(value) => {
                        props.table.setGlobalDefaults?.((prev) => ({ ...prev, [metric]: value }));
                        props.table.setHasUnsavedChanges?.(true);
                      }}
                    />
                  </div>
                );
              }}
            </For>
            <Show when={props.table.showOfflineAlertsColumn}>
              <div class="p-2 bg-surface rounded-sm border border-border-subtle flex flex-col gap-1">
                <span class="text-[10px] uppercase text-slate-500 font-medium">Offline alerts</span>
                <div class="flex items-center min-h-11 sm:min-h-0">
                  <Show
                    when={props.table.onSetGlobalOfflineState}
                    fallback={
                      <Show
                        when={props.table.onToggleGlobalDisableOffline}
                        fallback={
                          <span class="text-sm text-slate-400" aria-hidden="true">
                            -
                          </span>
                        }
                      >
                        <StatusBadge
                          isEnabled={!(props.table.globalDisableOfflineFlag?.() ?? false)}
                          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;
                          props.table.onSetGlobalOfflineState?.(nextOfflineState(state));
                        },
                        'Offline alerts default',
                      );
                    })()}
                  </Show>
                </div>
              </div>
            </Show>
          </div>
        </Card>
      </Show>

      <PlatformWindowedList
        items={mobileItems}
        estimatedItemHeight={240}
        enableThreshold={18}
        windowSize={24}
      >
        {(item) => {
          if (item.kind === 'group') {
            return (
              <div class="px-1 pt-4 pb-1 font-medium text-xs text-slate-500 uppercase">
                <AlertResourceGroupHeader
                  groupKey={item.groupName}
                  meta={props.table.groupHeaderMeta?.[item.groupName]}
                />
              </div>
            );
          }

          const resource = item.resource;
          const isEditing = () => props.table.editingId() === resource.id;
          const thresholds = () => getThresholds(resource, isEditing());
          const displayValue = (metric: string) => getDisplayValue(resource, metric, isEditing());
          const isOverridden = (metric: string) =>
            isAlertResourceMetricOverridden(resource, metric);
          const relaxedTriggerSummary = () =>
            props.table.globalDisableFlag?.()
              ? null
              : getAlertResourceRelaxedTriggerSummary(
                  resource,
                  props.table.editingThresholds(),
                  isEditing(),
                );

          return (
            <Card
              padding="sm"
              class={`flex flex-col gap-3 transition-opacity ${resource.disabled || props.table.globalDisableFlag?.() ? 'opacity-60' : ''}`}
            >
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-3 min-w-0">
                  <Show
                    when={props.table.showAlertsColumn !== false && props.table.onToggleDisabled}
                  >
                    <div class="shrink-0 scale-90 origin-left">
                      <TogglePrimitive
                        size="sm"
                        checked={
                          !(props.table.globalDisableFlag?.() ?? false) && !resource.disabled
                        }
                        disabled={props.table.globalDisableFlag?.() ?? false}
                        onToggle={() =>
                          !(props.table.globalDisableFlag?.() ?? false) &&
                          props.table.onToggleDisabled?.(resource.id)
                        }
                        ariaLabel={`Alerts for ${getAlertResourceLabel(resource)}`}
                      />
                    </div>
                  </Show>

                  <div class="min-w-0 truncate">
                    <div class="font-medium text-sm truncate">
                      {getAlertResourceLabel(resource)}
                    </div>
                    <Show when={resource.type === 'agent' && resource.clusterName}>
                      <span class="block text-xs text-muted whitespace-normal break-words">
                        {resource.clusterName}
                      </span>
                    </Show>
                    <Show when={resource.subtitle}>
                      <div
                        class="text-xs text-muted"
                        classList={{
                          truncate: !resource.readingMessage,
                          'whitespace-normal break-words': Boolean(resource.readingMessage),
                        }}
                      >
                        {resource.subtitle}
                      </div>
                    </Show>
                  </div>
                </div>

                <div class="flex gap-1 shrink-0">
                  <Show when={!isEditing() && resource.type !== 'dockerHost'}>
                    <ActionIconButton
                      onClick={() => startEditing(resource)}
                      label={`Edit thresholds for ${getAlertResourceLabel(resource)}`}
                      tone="accent"
                      size="sm"
                      class="min-h-11 min-w-11"
                    >
                      <Pencil class="w-4 h-4" aria-hidden="true" />
                    </ActionIconButton>
                  </Show>
                  <Show when={!isEditing() && props.table.onConfigureResourceIntent}>
                    <ActionIconButton
                      onClick={() =>
                        props.table.onConfigureResourceIntent?.(
                          resource.id,
                          getAlertResourcePreferredIntentSignal(props.table.columns, resource.type),
                          getAlertResourceIntentTargetLabel(resource),
                        )
                      }
                      label={`Configure alert delay for ${getAlertResourceLabel(resource)}`}
                      title="Configure individual alert delay"
                      tone="neutral"
                      size="sm"
                      class="min-h-11 min-w-11"
                    >
                      <Timer class="w-4 h-4" aria-hidden="true" />
                    </ActionIconButton>
                  </Show>
                  <Show when={isEditing()}>
                    <ActionIconButton
                      onClick={cancelEditing}
                      label="Cancel threshold edits"
                      tone="muted"
                      size="sm"
                      class="min-h-11 min-w-11"
                    >
                      <X class="w-4 h-4" aria-hidden="true" />
                    </ActionIconButton>
                    <ActionIconButton
                      onClick={() => saveEditing(resource.id)}
                      label={`Save threshold edits for ${getAlertResourceLabel(resource)}`}
                      tone="success"
                      size="sm"
                      class="min-h-11 min-w-11"
                    >
                      <Check class="w-4 h-4" aria-hidden="true" />
                    </ActionIconButton>
                  </Show>
                  <Show
                    when={
                      resource.hasOverride ||
                      (resource.type === 'agent' && resource.disableConnectivity)
                    }
                  >
                    <ActionIconButton
                      onClick={() => props.table.onRemoveOverride(resource.id)}
                      label={`Revert to defaults for ${getAlertResourceLabel(resource)}`}
                      title={getAlertResourceTableRevertToDefaultsLabel()}
                      tone="neutral"
                      size="sm"
                      class="min-h-11 min-w-11"
                    >
                      <RotateCcw class="w-4 h-4" aria-hidden="true" />
                    </ActionIconButton>
                  </Show>
                </div>
              </div>
              <Show when={resource.readingMessage}>
                <p class="text-xs text-muted whitespace-normal break-words">
                  {resource.readingMessage}
                </p>
              </Show>

              <Show when={relaxedTriggerSummary()}>
                {(summary) => (
                  <AlertResourceRelaxedTriggers summary={summary()} class="text-xs text-muted" />
                )}
              </Show>

              <Show when={isEditing()}>
                <FormTextarea
                  label="Override note"
                  labelClass="sr-only"
                  fieldBaseClass="w-full"
                  textareaBaseClass="w-full text-xs p-2 rounded-sm border border-border bg-surface-alt"
                  rows={2}
                  placeholder={getAlertResourceTableEditNotePlaceholder()}
                  value={props.table.editingNote()}
                  onInput={(e) => props.table.setEditingNote(e.currentTarget.value)}
                />
              </Show>

              <div
                class={`grid gap-2 text-sm border-t pt-2 ${isEditing() ? 'grid-cols-1' : 'grid-cols-2'}`}
              >
                <For each={props.table.columns}>
                  {(column) => {
                    const metric = normalizeAlertResourceMetricKey(column);
                    if (!alertResourceSupportsMetric(resource.type, metric)) return null;

                    // Backup and snapshot carry day-based configs, not
                    // trigger/clear thresholds. Routing them through the
                    // numeric editor persisted {trigger, clear} into the
                    // backup block, which the backend reads as an all-zero
                    // disabled config (#1126). Render the same on/off
                    // toggle the desktop rows use instead.
                    if (metric === 'backup' || metric === 'snapshot') {
                      const config = metric === 'backup' ? resource.backup : resource.snapshot;
                      const onToggle =
                        metric === 'backup'
                          ? props.table.onToggleBackup
                          : props.table.onToggleSnapshot;
                      if (!onToggle) return null;
                      const titlePrefix = metric === 'backup' ? 'Backup' : 'Snapshot';

                      return (
                        <div class="flex justify-between items-center p-1.5 bg-surface-alt rounded-sm">
                          <span class="text-[10px] uppercase font-bold tracking-wider">
                            {column}
                          </span>
                          <StatusBadge
                            isEnabled={config?.enabled ?? true}
                            onToggle={() => onToggle(resource.id)}
                            titleEnabled={`${titlePrefix} alerts enabled. Click to disable for this resource.`}
                            titleDisabled={`${titlePrefix} alerts disabled. Click to enable for this resource.`}
                            ariaLabel={`${titlePrefix} alerts for ${getAlertResourceLabel(resource)}`}
                          />
                        </div>
                      );
                    }

                    return (
                      <div class="flex justify-between items-center p-1.5 bg-surface-alt rounded-sm">
                        <span class="text-[10px] uppercase font-bold tracking-wider">
                          {column.replace(/mb\/s|%|°c/gi, '').trim()}
                        </span>

                        <Show
                          when={isEditing()}
                          fallback={
                            <button
                              type="button"
                              onClick={(e) => startEditing(resource, metric, e)}
                              class="min-h-11 min-w-11 font-mono text-xs font-medium cursor-pointer rounded-sm px-1 -mx-1 focus:outline-hidden focus-visible:ring-2 focus-visible:ring-blue-400"
                              aria-label={`Edit ${column} threshold for ${getAlertResourceLabel(resource)}: ${metricValueText(metric, displayValue(metric))}`}
                            >
                              <MetricValueWithHeat
                                resource={resource}
                                metric={metric}
                                value={displayValue(metric)}
                                isOverridden={isOverridden(metric)}
                              />
                            </button>
                          }
                        >
                          <AlertResourceMetricEditor
                            metric={metric}
                            column={column}
                            scope="override"
                            layout="card"
                            value={thresholds()?.[metric]}
                            inheritedDefault={resource.defaults?.[metric]}
                            resourceName={getAlertResourceLabel(resource)}
                            onFocus={() =>
                              props.setActiveMetricInput({ resourceId: resource.id, metric })
                            }
                            autoFocus={
                              isEditing() &&
                              props.activeMetricInput()?.resourceId === resource.id &&
                              props.activeMetricInput()?.metric === metric
                            }
                            onChange={(value) =>
                              props.table.setEditingThresholds({
                                ...props.table.editingThresholds(),
                                [metric]: value,
                              })
                            }
                          />
                        </Show>
                      </div>
                    );
                  }}
                </For>
                <Show when={props.table.showOfflineAlertsColumn}>
                  {(() => {
                    const supportsTriState =
                      typeof props.table.onSetOfflineState === 'function' &&
                      (resource.type === 'guest' || resource.type === 'dockerContainer');
                    if (!supportsTriState && !props.table.onToggleNodeConnectivity) {
                      return null;
                    }
                    const disabledGlobally = () => props.table.globalDisableFlag?.() ?? false;

                    return (
                      <div class="flex justify-between items-center p-1.5 bg-surface-alt rounded-sm">
                        <span class="text-[10px] uppercase font-bold tracking-wider">Offline</span>
                        <Show
                          when={supportsTriState}
                          fallback={
                            <StatusBadge
                              isEnabled={
                                !(props.table.globalDisableOfflineFlag?.() ?? false) &&
                                !resource.disableConnectivity
                              }
                              disabled={disabledGlobally()}
                              onToggle={() => {
                                if (disabledGlobally()) return;
                                props.table.onToggleNodeConnectivity?.(resource.id);
                              }}
                              titleEnabled="Offline alerts enabled. Click to disable for this resource."
                              titleDisabled="Offline alerts disabled. Click to enable for this resource."
                              titleWhenDisabled="Offline alerts controlled globally"
                              ariaLabel={`Offline alerts for ${getAlertResourceLabel(resource)}`}
                            />
                          }
                        >
                          {(() => {
                            const defaultDisabled =
                              props.table.globalDisableOfflineFlag?.() ?? false;
                            const defaultSeverity = props.table.globalOfflineSeverity ?? 'warning';

                            let state: OfflineState;
                            if (resource.disableConnectivity) {
                              state = 'off';
                            } else if (resource.poweredOffSeverity) {
                              state = resource.poweredOffSeverity;
                            } else if (defaultDisabled) {
                              state = 'off';
                            } else {
                              state = defaultSeverity === 'critical' ? 'critical' : 'warning';
                            }

                            return renderOfflineStateButton(
                              state,
                              disabledGlobally(),
                              () => {
                                if (disabledGlobally()) return;
                                props.table.onSetOfflineState?.(
                                  resource.id,
                                  nextOfflineState(state),
                                );
                              },
                              `Offline alerts for ${getAlertResourceLabel(resource)}`,
                            );
                          })()}
                        </Show>
                      </div>
                    );
                  })()}
                </Show>
              </div>
            </Card>
          );
        }}
      </PlatformWindowedList>
      <Show when={props.hasRows() === false}>
        <div class="text-center p-8 text-slate-500 text-sm italic bg-surface-alt rounded-md">
          {getAlertResourceTableEmptyState(props.table.emptyMessage)}
        </div>
      </Show>
    </div>
  );
}