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.

13.8 KB
Raw Blame
import { Component, JSX, Show, createMemo } from 'solid-js';
import DatabaseIcon from 'lucide-solid/icons/database';
import HardDriveIcon from 'lucide-solid/icons/hard-drive';
import { FilterBar, filterChipStatusDot, type FilterDef } from '@/components/shared/FilterBar';
import { FormSelect } from '@/components/shared/FormSelect';
import { Subtabs } from '@/components/shared/Subtabs';
import { useBreakpoint } from '@/hooks/useBreakpoint';
import { STORAGE_KEYS } from '@/utils/localStorage';
import {
  DEFAULT_PHYSICAL_DISK_FACET_FILTER,
  type PhysicalDiskFilterOption,
} from '@/features/storageBackups/diskPresentation';
import {
  getNextStorageSortDirection,
  getStorageSortDirectionIconClass,
  getStorageSortDirectionTitle,
  STORAGE_FILTER_SORT_DIRECTION_BUTTON_CLASS,
  STORAGE_FILTER_SORT_ICON_CLASS,
  STORAGE_FILTER_SORT_SELECT_CLASS,
  STORAGE_FILTER_SORT_WRAP_CLASS,
} from '@/features/storageBackups/storageFilterPresentation';
import {
  DEFAULT_STORAGE_GROUP_KEY,
  DEFAULT_STORAGE_SELECTED_NODE_ID,
  DEFAULT_STORAGE_SORT_DIRECTION,
  DEFAULT_STORAGE_SORT_KEY,
  DEFAULT_STORAGE_SORT_OPTIONS,
  DEFAULT_STORAGE_SOURCE_FILTER,
  DEFAULT_STORAGE_STATUS_FILTER,
  getDefaultStorageSortDirection,
  hasActiveStorageFilters,
  normalizeStorageSortKey,
  STORAGE_GROUP_BY_OPTIONS,
  STORAGE_STATUS_FILTER_OPTIONS,
  type StorageStatusFilterValue,
  type StorageView,
} from './storagePageState';
import type { StorageGroupKey, StorageSortKey } from './useStorageModel';
import type { StorageSourceOption } from '@/utils/storageSources';

type StoragePageControlsProps = {
  kioskMode: () => boolean;
  view: () => StorageView;
  setView: (value: StorageView) => void;
  showViewTabs?: boolean;
  search: () => string;
  setSearch: (value: string) => void;
  filterAriaLabel?: string;
  searchPlaceholder?: string;
  searchEmptyMessage?: string;
  searchTrailing?: JSX.Element;
  groupBy: () => StorageGroupKey;
  setGroupBy: (value: StorageGroupKey) => void;
  sortKey: () => StorageSortKey;
  setSortKey: (value: StorageSortKey) => void;
  sortDirection: () => 'asc' | 'desc';
  setSortDirection: (value: 'asc' | 'desc') => void;
  statusFilter: () => StorageStatusFilterValue;
  setStatusFilter: (value: StorageStatusFilterValue) => void;
  sourceFilter: () => string;
  setSourceFilter: (value: string) => void;
  sourceOptions: () => StorageSourceOption[];
  diskRoleFilter?: () => string;
  setDiskRoleFilter?: (value: string) => void;
  diskRoleOptions?: () => PhysicalDiskFilterOption[];
  diskGroupFilter?: () => string;
  setDiskGroupFilter?: (value: string) => void;
  diskGroupOptions?: () => PhysicalDiskFilterOption[];
  nodeFilterOptions: Array<{ value: string; label: string }>;
  selectedNodeId: () => string;
  setSelectedNodeId: (value: string) => void;
  storageFilterGroupBy: () => StorageGroupKey;
  // When a platform page mounts StorageSurface with `forcedSourceFilter`
  // the Source chip is already locked by the page and would otherwise
  // render as a redundant pinned filter. Setting this drops it from the
  // rendered filter row.
  suppressSourceFilter?: boolean;
  // Platform-embedded storage tabs use the search box for host/node
  // scoping, matching the platform overview filter contract.
  suppressNodeFilter?: boolean;
  // for picking a key that namespaces views per platform context so
  // saved queries from one platform do not leak into another.
};

export const StoragePageControls: Component<StoragePageControlsProps> = (props) => {
  const { isMobile } = useBreakpoint();
  const isPoolsView = () => props.view() === 'pools';
  const sortDisabled = () => !isPoolsView();

  const showClearAll = createMemo(
    () =>
      hasActiveStorageFilters({
        search: props.search(),
        sortKey: props.sortKey(),
        sortDirection: props.sortDirection(),
        groupBy: props.storageFilterGroupBy(),
        statusFilter: props.statusFilter(),
        // When the Source filter is suppressed (a platform page like
        // Proxmox/Storage forces it to its own scope via
        // `forcedSourceFilter`), the user cannot change it — so it must not
        // count as an "active filter" that surfaces the Reset button.
        sourceFilter: props.suppressSourceFilter
          ? DEFAULT_STORAGE_SOURCE_FILTER
          : props.sourceFilter(),
        diskRoleFilter: props.diskRoleFilter?.(),
        diskGroupFilter: props.diskGroupFilter?.(),
      }) ||
      (!props.suppressNodeFilter &&
        (props.selectedNodeId() || DEFAULT_STORAGE_SELECTED_NODE_ID) !==
          DEFAULT_STORAGE_SELECTED_NODE_ID),
  );

  const handleClearAll = () => {
    props.setSearch('');
    props.setSortKey(DEFAULT_STORAGE_SORT_KEY);
    props.setSortDirection(DEFAULT_STORAGE_SORT_DIRECTION);
    props.setGroupBy(DEFAULT_STORAGE_GROUP_KEY);
    props.setStatusFilter(DEFAULT_STORAGE_STATUS_FILTER as StorageStatusFilterValue);
    props.setSourceFilter(DEFAULT_STORAGE_SOURCE_FILTER);
    props.setDiskRoleFilter?.(DEFAULT_PHYSICAL_DISK_FACET_FILTER);
    props.setDiskGroupFilter?.(DEFAULT_PHYSICAL_DISK_FACET_FILTER);
    props.setSelectedNodeId(DEFAULT_STORAGE_SELECTED_NODE_ID);
  };

  const handleSortKeyChange = (value: string) => {
    const nextSortKey = normalizeStorageSortKey(value) as StorageSortKey;
    const previousSortKey = props.sortKey();
    props.setSortKey(nextSortKey);
    if (nextSortKey !== previousSortKey) {
      props.setSortDirection(getDefaultStorageSortDirection(nextSortKey));
    }
  };

  const storageViewTabs = [
    {
      value: 'pools',
      label: (
        <span class="inline-flex items-center gap-1.5">
          <DatabaseIcon aria-hidden="true" class="h-3.5 w-3.5" />
          Storage
        </span>
      ),
    },
    {
      value: 'disks',
      label: (
        <span class="inline-flex items-center gap-1.5">
          <HardDriveIcon aria-hidden="true" class="h-3.5 w-3.5" />
          Physical Disks
        </span>
      ),
    },
  ];

  const buildFilters = (): FilterDef[] => {
    const filters: FilterDef[] = [];

    if (!props.suppressNodeFilter) {
      filters.push({
        id: 'storage-node',
        label: 'Node',
        group: 'scope',
        value: props.selectedNodeId,
        setValue: props.setSelectedNodeId,
        defaultValue: DEFAULT_STORAGE_SELECTED_NODE_ID,
        options: () =>
          props.nodeFilterOptions.map((option) => ({
            value: option.value,
            label: option.label,
          })),
      });
    }

    if (isPoolsView()) {
      if (!props.suppressSourceFilter) {
        filters.push({
          id: 'storage-source',
          label: 'Source',
          group: 'scope',
          value: props.sourceFilter,
          setValue: props.setSourceFilter,
          defaultValue: DEFAULT_STORAGE_SOURCE_FILTER,
          options: () =>
            props.sourceOptions().map((option) => ({
              value: option.key,
              label: option.label,
            })),
        });
      }

      filters.push({
        id: 'storage-status',
        label: 'Status',
        group: 'status',
        value: () => props.statusFilter(),
        setValue: (value: string) => props.setStatusFilter(value as StorageStatusFilterValue),
        defaultValue: DEFAULT_STORAGE_STATUS_FILTER as StorageStatusFilterValue,
        options: () =>
          STORAGE_STATUS_FILTER_OPTIONS.map((option) => ({
            value: option.value as string,
            label: option.label,
            leading:
              option.value === 'available'
                ? filterChipStatusDot('bg-emerald-500')
                : option.value === 'warning' || option.value === 'attention'
                  ? filterChipStatusDot('bg-amber-500')
                  : option.value === 'critical'
                    ? filterChipStatusDot('bg-red-500')
                    : option.value === 'offline' || option.value === 'unknown'
                      ? filterChipStatusDot('bg-slate-400')
                      : undefined,
            tone:
              option.value === 'available'
                ? 'success'
                : option.value === 'warning' || option.value === 'attention'
                  ? 'warning'
                  : option.value === 'critical'
                    ? 'danger'
                    : option.value === 'offline' || option.value === 'unknown'
                      ? 'muted'
                      : undefined,
          })),
      });
    } else {
      const diskRoleFilter = props.diskRoleFilter;
      const setDiskRoleFilter = props.setDiskRoleFilter;
      const diskRoleOptions = props.diskRoleOptions;
      if (diskRoleFilter && setDiskRoleFilter && diskRoleOptions && diskRoleOptions().length > 1) {
        filters.push({
          id: 'storage-disk-role',
          label: 'Role',
          group: 'properties',
          value: () => diskRoleFilter(),
          setValue: setDiskRoleFilter,
          defaultValue: DEFAULT_PHYSICAL_DISK_FACET_FILTER,
          options: () =>
            diskRoleOptions().map((option) => ({
              value: option.value,
              label: option.label,
            })),
        });
      }

      const diskGroupFilter = props.diskGroupFilter;
      const setDiskGroupFilter = props.setDiskGroupFilter;
      const diskGroupOptions = props.diskGroupOptions;
      if (
        diskGroupFilter &&
        setDiskGroupFilter &&
        diskGroupOptions &&
        diskGroupOptions().length > 1
      ) {
        filters.push({
          id: 'storage-disk-group',
          label: 'Group',
          group: 'properties',
          value: () => diskGroupFilter(),
          setValue: setDiskGroupFilter,
          defaultValue: DEFAULT_PHYSICAL_DISK_FACET_FILTER,
          options: () =>
            diskGroupOptions().map((option) => ({
              value: option.value,
              label: option.label,
            })),
        });
      }
    }

    return filters;
  };

  return (
    <Show when={!props.kioskMode()}>
      <div class="flex flex-col gap-2">
        <Show when={props.showViewTabs !== false}>
          <Subtabs
            value={props.view()}
            onChange={(value) => props.setView(value as StorageView)}
            tabs={storageViewTabs}
            ariaLabel="Storage view"
          />
        </Show>
        <FilterBar
          role="group"
          ariaLabel={props.filterAriaLabel ?? 'Storage filters'}
          isMobile={isMobile}
          search={{
            value: props.search,
            setValue: props.setSearch,
            placeholder:
              props.searchPlaceholder ?? 'Search storage by pool, dataset, node, or device',
            historyKey: STORAGE_KEYS.STORAGE_SEARCH_HISTORY,
            emptyMessage: props.searchEmptyMessage ?? 'Recent storage searches appear here.',
          }}
          searchTrailing={props.searchTrailing}
          filters={buildFilters()}
          viewOptions={
            <div class="space-y-3">
              <Show when={isPoolsView()}>
                <div>
                  <div class="mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-muted">
                    Layout
                  </div>
                  <FormSelect
                    label="Group by"
                    labelClass="sr-only"
                    fieldBaseClass="contents"
                    selectBaseClass={`${STORAGE_FILTER_SORT_SELECT_CLASS} w-full`}
                    value={props.storageFilterGroupBy()}
                    onChange={(event) =>
                      props.setGroupBy(event.currentTarget.value as StorageGroupKey)
                    }
                    aria-label="Group by"
                  >
                    {STORAGE_GROUP_BY_OPTIONS.map((option) => (
                      <option value={option.value}>{option.label}</option>
                    ))}
                  </FormSelect>
                </div>
              </Show>
              <div>
                <div class="mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-muted">
                  Order
                </div>
                <div class={STORAGE_FILTER_SORT_WRAP_CLASS}>
                  <FormSelect
                    label="Sort by"
                    labelClass="sr-only"
                    fieldBaseClass="contents"
                    selectBaseClass={STORAGE_FILTER_SORT_SELECT_CLASS}
                    value={props.sortKey()}
                    onChange={(event) => handleSortKeyChange(event.currentTarget.value)}
                    disabled={sortDisabled()}
                    aria-label="Sort by"
                  >
                    {DEFAULT_STORAGE_SORT_OPTIONS.map((option) => (
                      <option value={option.value}>{option.label}</option>
                    ))}
                  </FormSelect>
                  <button
                    type="button"
                    title={getStorageSortDirectionTitle(props.sortDirection())}
                    onClick={() =>
                      props.setSortDirection(getNextStorageSortDirection(props.sortDirection()))
                    }
                    disabled={sortDisabled()}
                    aria-label="Sort direction"
                    class={STORAGE_FILTER_SORT_DIRECTION_BUTTON_CLASS}
                  >
                    <svg
                      class={`${STORAGE_FILTER_SORT_ICON_CLASS} ${getStorageSortDirectionIconClass(
                        props.sortDirection(),
                      )}`}
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        d="M8 9l4-4 4 4m0 6l-4 4-4-4"
                      />
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          }
          onClearAll={handleClearAll}
          showClearAll={showClearAll}
        />
      </div>
    </Show>
  );
};

export default StoragePageControls;