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.

10.7 KB
Raw Blame
import type { Component } from 'solid-js';
import { For, Show, createMemo, createResource, createSignal } from 'solid-js';
import { useNavigate } from '@solidjs/router';
import { apiFetchJSON } from '@/utils/apiClient';
import { Card } from '@/components/shared/Card';
import { SearchInput } from '@/components/shared/SearchInput';
import { TableRow, TableHead, TableCell } from '@/components/shared/Table';
import { EmptyState } from '@/components/shared/EmptyState';
import { StatusDot } from '@/components/shared/StatusDot';
import { buildKubernetesPath, buildKubernetesRouteSearch } from '@/routing/resourceLinks';
import {
  PlatformDetailTable,
  PlatformDetailTableBody,
  PlatformDetailTableHeader,
  PlatformResponsiveTableLabel,
  formatPlatformTableIntegerValue,
  getPlatformTableCellClassForKind,
  getPlatformTableHeadClassForKind,
} from '@/features/platformPage/sharedPlatformPage';
import {
  getK8sNamespacesDrawerPresentation,
  getK8sNamespacesEmptyState,
  getK8sNamespacesFailureState,
  getK8sNamespacesLoadingState,
} from '@/utils/k8sNamespacePresentation';
import { getNamespaceCountsIndicator, type NamespaceCounts } from '@/utils/k8sStatusPresentation';
import { asTrimmedString } from '@/utils/stringUtils';

type NamespaceRow = {
  namespace: string;
  pods: NamespaceCounts;
  deployments: NamespaceCounts;
};

type NamespacesResponse = {
  cluster: string;
  data: NamespaceRow[];
};

const EMPTY_RESPONSE: NamespacesResponse = { cluster: '', data: [] };

export const K8sNamespacesDrawer: Component<{
  /** The cluster name the namespaces endpoint aggregates by. */
  cluster: string;
  /**
   * The value the Kubernetes page scopes its rows by: the cluster id, or the
   * name when no id is reported. Defaults to `cluster`.
   */
  scopeCluster?: string;
}> = (props) => {
  const navigate = useNavigate();
  const [search, setSearch] = createSignal('');
  const drawerPresentation = getK8sNamespacesDrawerPresentation();

  const clusterName = createMemo(() => asTrimmedString(props.cluster) ?? '');
  const scopeCluster = createMemo(() => asTrimmedString(props.scopeCluster) || clusterName());

  const [namespaces] = createResource(
    clusterName,
    async (cluster) => {
      if (!cluster) return EMPTY_RESPONSE;
      const params = new URLSearchParams();
      params.set('cluster', cluster);
      return apiFetchJSON<NamespacesResponse>(
        `/api/resources/k8s/namespaces?${params.toString()}`,
        { cache: 'no-store' },
      );
    },
    { initialValue: EMPTY_RESPONSE },
  );

  // Solid rethrows a resource's error when it is read, so every read checks
  // the state first; otherwise a failed fetch would escape to the nearest
  // error boundary instead of showing the failure state below.
  const failed = () => namespaces.state === 'errored';
  const loadError = createMemo(() => {
    if (!failed()) return '';
    return (namespaces.error as Error)?.message || 'Failed to fetch namespaces';
  });

  const rows = createMemo(() => {
    if (failed()) return [];
    const data = namespaces()?.data;
    return Array.isArray(data) ? data : [];
  });

  const filteredRows = createMemo(() => {
    const term = (asTrimmedString(search()) ?? '').toLowerCase();
    if (!term) return rows();
    return rows().filter((row) => row.namespace.toLowerCase().includes(term));
  });

  // Pods and deployments both live on the Workloads tab, which reads the
  // cluster and namespace scope from its URL.
  const openWorkloads = (namespace: string | null) => {
    if (!clusterName()) return;
    navigate(
      `${buildKubernetesPath('workloads')}${buildKubernetesRouteSearch({
        cluster: scopeCluster(),
        namespace,
      })}`,
    );
  };

  const headingId = () => `k8s-namespaces-drawer-heading-${clusterName() || 'cluster'}`;

  return (
    <section class="space-y-3" aria-labelledby={headingId()}>
      <h3 id={headingId()} class="sr-only">
        {clusterName() || 'Kubernetes cluster'} namespaces
      </h3>
      <div class="flex flex-wrap items-center justify-end gap-2">
        <div class="w-48">
          <SearchInput
            value={search}
            onChange={setSearch}
            placeholder={drawerPresentation.searchPlaceholder}
            inputClass="py-1 text-xs font-medium shadow-xs"
            typeToSearch
            clearOnEscape
          />
        </div>
        <button
          type="button"
          onClick={() => openWorkloads(null)}
          class="rounded-md border border-border bg-surface px-3 py-1 text-xs font-semibold shadow-xs hover:bg-surface-hover"
        >
          {drawerPresentation.openAllWorkloadsLabel}
        </button>
      </div>

      <Show
        when={!namespaces.loading}
        fallback={
          <Card padding="lg">
            <EmptyState {...getK8sNamespacesLoadingState()} />
          </Card>
        }
      >
        <Show
          when={!loadError()}
          fallback={
            <div role="alert" aria-live="assertive">
              <Card padding="lg" tone="danger">
                <EmptyState {...getK8sNamespacesFailureState(loadError())} tone="danger" />
              </Card>
            </div>
          }
        >
          <Show
            when={filteredRows().length > 0}
            fallback={
              <Card padding="lg">
                <EmptyState {...getK8sNamespacesEmptyState(rows().length > 0)} />
              </Card>
            }
          >
            <Card padding="none" tone="card" class="overflow-hidden">
              <PlatformDetailTable class="min-w-0 table-fixed text-xs">
                <PlatformDetailTableHeader>
                  <TableHead class={`${getPlatformTableHeadClassForKind('name')} md:w-[22%]`}>
                    {drawerPresentation.namespaceColumnLabel}
                  </TableHead>
                  <TableHead
                    class={`${getPlatformTableHeadClassForKind('numeric-value')} platform-table-mobile-w-15 md:w-[18%]`}
                  >
                    {drawerPresentation.podsColumnLabel}
                  </TableHead>
                  <TableHead
                    class={`${getPlatformTableHeadClassForKind('numeric-value')} platform-table-mobile-w-15 md:w-[22%]`}
                  >
                    {drawerPresentation.deploymentsColumnLabel}
                  </TableHead>
                  <TableHead
                    class={`${getPlatformTableHeadClassForKind('text')} platform-table-mobile-w-30 md:w-[38%]`}
                  >
                    {drawerPresentation.actionsColumnLabel}
                  </TableHead>
                </PlatformDetailTableHeader>
                <PlatformDetailTableBody>
                  <For each={filteredRows()}>
                    {(row) => {
                      const podIndicator = () => getNamespaceCountsIndicator(row.pods);
                      return (
                        <TableRow class="text-[11px] sm:text-xs">
                          <TableCell class={getPlatformTableCellClassForKind('name')}>
                            <div class="flex items-start gap-2 min-w-0">
                              <StatusDot
                                size="sm"
                                variant={podIndicator().variant}
                                title={podIndicator().label}
                                ariaHidden
                                class="mt-1"
                              />
                              {/* Namespace names are compared and copied, so
                                  they wrap rather than truncate. */}
                              <span class="min-w-0 whitespace-normal font-semibold text-base-content wrap-anywhere">
                                {row.namespace}
                              </span>
                            </div>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('numeric-value')} text-base-content`}
                          >
                            <span class="font-semibold tabular-nums">
                              {formatPlatformTableIntegerValue(row.pods.total ?? 0, '0')}
                            </span>
                            <span class="ml-2 text-[11px] text-muted">
                              {row.pods.offline > 0
                                ? `${formatPlatformTableIntegerValue(row.pods.offline, '0')} off`
                                : ''}
                              {row.pods.warning > 0
                                ? `${row.pods.offline > 0 ? ' · ' : ''}${formatPlatformTableIntegerValue(row.pods.warning, '0')} warn`
                                : ''}
                            </span>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('numeric-value')} text-base-content`}
                          >
                            <span class="font-semibold tabular-nums">
                              {formatPlatformTableIntegerValue(row.deployments.total ?? 0, '0')}
                            </span>
                            <span class="ml-2 text-[11px] text-muted">
                              {row.deployments.warning > 0
                                ? `${formatPlatformTableIntegerValue(row.deployments.warning, '0')} warn`
                                : ''}
                              {row.deployments.offline > 0
                                ? `${row.deployments.warning > 0 ? ' · ' : ''}${formatPlatformTableIntegerValue(row.deployments.offline, '0')} off`
                                : ''}
                            </span>
                          </TableCell>
                          <TableCell class={getPlatformTableCellClassForKind('text')}>
                            <button
                              type="button"
                              aria-label={`${drawerPresentation.openWorkloadsLabel} in ${row.namespace}`}
                              onClick={() => openWorkloads(row.namespace)}
                              class="rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-semibold text-base-content shadow-xs hover:bg-surface-hover"
                            >
                              <PlatformResponsiveTableLabel
                                compact="Open"
                                full={drawerPresentation.openWorkloadsLabel}
                              />
                            </button>
                          </TableCell>
                        </TableRow>
                      );
                    }}
                  </For>
                </PlatformDetailTableBody>
              </PlatformDetailTable>
            </Card>
          </Show>
        </Show>
      </Show>
    </section>
  );
};

export default K8sNamespacesDrawer;