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.

15.1 KB
Raw Blame
import { Show, createMemo, type Component, type JSX } from 'solid-js';
import { StatusDot } from '@/components/shared/StatusDot';
import { TableCell, TableRow } from '@/components/shared/Table';
import { getSimpleStatusIndicator } from '@/utils/status';
import { asTrimmedString } from '@/utils/stringUtils';
import {
  PlatformWindowedRows,
  PlatformResponsiveTableLabel,
  PlatformSortableTableHead,
  PlatformTableEmptyState,
  PlatformTableToolbar,
  createPlatformTableFilterState,
  createPlatformTableSortState,
  formatPlatformTableTitleCaseValue,
  getPlatformTableCellClassForKind,
  summarizePlatformTableValues,
  type PlatformTableFilterOption,
  type PlatformTableSortValue,
  PlatformTableShell,
  withPlatformStatusCounts,
} from '@/features/platformPage/sharedPlatformPage';
import {
  getPlatformInlineStateClass,
  getPlatformStatusTextToneClass,
  isPlatformAttentionVariant,
} from '@/features/platformPage/platformStatusTone';
import {
  PlatformResourceDetailToggleButton,
  PlatformResourceDetailTableRow,
  createPlatformResourceDetailState,
  createPlatformResourceLabelResolver,
  getPlatformResourceDetailRowClass,
} from '@/features/platformPage/PlatformResourceDetailTableRow';
import type { Resource, ResourceTrueNASShareMeta } from '@/types/resource';
import {
  filterTrueNASShares,
  getTrueNASResourceDisplayStatus,
  mapTrueNASShareStatus,
  type TrueNASShareStatusFilter,
} from './truenasPageModel';

const TRUENAS_SHARE_STATUS_OPTIONS: PlatformTableFilterOption<TrueNASShareStatusFilter>[] = [
  { value: 'all', label: 'All' },
  { value: 'active', label: 'Active', tone: 'success' },
  { value: 'attention', label: 'Attention', tone: 'warning' },
  { value: 'disabled', label: 'Disabled', tone: 'danger' },
];

const shareMeta = (resource: Resource): ResourceTrueNASShareMeta | undefined =>
  resource.truenas?.share;

const formatProtocol = (share: ResourceTrueNASShareMeta | undefined): string =>
  asTrimmedString(share?.protocol)?.toUpperCase() || '-';

const formatAccess = (
  share: ResourceTrueNASShareMeta | undefined,
): { label: string; title: string } => {
  const flags = [
    share?.readOnly === true ? 'Read-only' : share?.readOnly === false ? 'Read/write' : undefined,
    share?.browsable === true ? 'Browsable' : share?.browsable === false ? 'Hidden' : undefined,
    share?.accessBasedEnumeration ? 'ABE' : undefined,
    share?.auditEnabled ? 'Audit' : undefined,
    share?.exposeSnapshots ? 'Snapshots' : undefined,
  ];
  return summarizePlatformTableValues(flags, { emptyText: '-', maxVisible: 3 });
};

const formatClients = (
  share: ResourceTrueNASShareMeta | undefined,
): { label: string; title: string } => {
  const networks = summarizePlatformTableValues(share?.networks, { emptyText: '-' }).values;
  const hosts = summarizePlatformTableValues(share?.hosts, { emptyText: '-' }).values;
  const aliases = summarizePlatformTableValues(share?.aliases, { emptyText: '-' }).values;
  const values = [
    ...networks.map((network) => `net:${network}`),
    ...hosts.map((host) => `host:${host}`),
    ...aliases.map((alias) => `alias:${alias}`),
  ];
  return summarizePlatformTableValues(values, { emptyText: '-' });
};

const formatSecurity = (
  share: ResourceTrueNASShareMeta | undefined,
): { label: string; title: string } => {
  const values = [
    ...(share?.security ?? []),
    ...[
      share?.mapRootUser ? `root:${share.mapRootUser}` : undefined,
      share?.mapAllUser ? `all:${share.mapAllUser}` : undefined,
    ],
  ];
  return summarizePlatformTableValues(values, { emptyText: '-' });
};

const shareName = (resource: Resource, share: ResourceTrueNASShareMeta | undefined): string =>
  asTrimmedString(share?.name) ||
  asTrimmedString(resource.displayName) ||
  asTrimmedString(resource.name) ||
  resource.id;

// Columns a user can sort by. Access and Clients summarize several flags or
// endpoints at once, so they carry no single scalar to order on.
const TRUENAS_SHARE_SORT_KEYS = ['share', 'protocol', 'path', 'state'] as const;

type TrueNASShareSortKey = (typeof TRUENAS_SHARE_SORT_KEYS)[number];

const getTrueNASShareSortValue = (
  resource: Resource,
  key: TrueNASShareSortKey,
): PlatformTableSortValue => {
  const share = shareMeta(resource);
  switch (key) {
    case 'share':
      return shareName(resource, share);
    case 'protocol': {
      const protocol = formatProtocol(share);
      return protocol === '-' ? null : protocol;
    }
    case 'path':
      return asTrimmedString(share?.path) || null;
    case 'state':
      return formatPlatformTableTitleCaseValue(mapTrueNASShareStatus(resource));
    default:
      key satisfies never;
      return null;
  }
};

export const TrueNASNetworkSharesTable: Component<{
  shares: Resource[];
  scope: Resource[];
  emptyIcon: JSX.Element;
  emptyTitle: string;
  emptyDescription: string;
  showToolbar?: boolean;
  /** The page's URL search, when it owns one; the table then reads and writes it. */
  search?: () => string;
  onSearchChange?: (value: string) => void;
}> = (props) => {
  const tableState = createPlatformTableFilterState({
    resources: () => props.shares,
    initialStatus: 'all' as TrueNASShareStatusFilter,
    filter: filterTrueNASShares,
    externalSearch: props.search,
    onExternalSearchChange: props.onSearchChange,
  });
  const drawer = createPlatformResourceDetailState({ idPrefix: 'truenas-share-drawer' });
  const resolveResourceLabel = createPlatformResourceLabelResolver(() => props.scope);
  const sort = createPlatformTableSortState({
    storageKey: 'truenasShares',
    sortKeys: TRUENAS_SHARE_SORT_KEYS,
  });
  const sortedRows = createMemo(() =>
    sort.sortRows(tableState.filtered(), getTrueNASShareSortValue),
  );

  return (
    <Show
      when={props.shares.length > 0}
      fallback={
        <PlatformTableEmptyState
          icon={props.emptyIcon}
          title={props.emptyTitle}
          description={props.emptyDescription}
        />
      }
    >
      <div class="space-y-3">
        <Show when={props.showToolbar !== false}>
          <PlatformTableToolbar
            search={tableState.search}
            onSearchChange={tableState.setSearch}
            searchPlaceholder="Search TrueNAS shares"
            searchSuggestions={tableState.searchSuggestions}
            status={tableState.status()}
            onStatusChange={tableState.setStatus}
            statusOptions={withPlatformStatusCounts(
              TRUENAS_SHARE_STATUS_OPTIONS,
              tableState.countForStatus,
            )}
            visible={tableState.visible()}
            total={tableState.total()}
            rowNoun="shares"
          />
        </Show>

        <Show
          when={tableState.filtered().length > 0}
          fallback={
            <PlatformTableEmptyState
              icon={props.emptyIcon}
              title="No shares match current filters"
              description="Adjust the search or status filter to see more TrueNAS shares."
            />
          }
        >
          <PlatformTableShell
            title="Network Shares"
            tableClass="min-w-full table-fixed text-xs md:min-w-[960px]"
            header={
              <>
                <PlatformSortableTableHead
                  kind="name"
                  sort={sort}
                  sortKey="share"
                  class="platform-table-mobile-w-30 md:w-[23%]"
                >
                  Share
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="text"
                  sort={sort}
                  sortKey="protocol"
                  class="platform-table-mobile-w-15 md:w-[11%]"
                >
                  <PlatformResponsiveTableLabel compact="Proto" full="Protocol" />
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="text"
                  sort={sort}
                  sortKey="path"
                  class="platform-table-mobile-w-25 md:w-[27%]"
                >
                  Path
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="text"
                  sort={sort}
                  class="platform-table-phone-hidden md:w-[19%]"
                >
                  <PlatformResponsiveTableLabel compact="ACL" full="Access" />
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="text"
                  sort={sort}
                  class="hidden lg:table-cell md:w-[13%]"
                >
                  Clients
                </PlatformSortableTableHead>
                <PlatformSortableTableHead
                  kind="badge"
                  sort={sort}
                  sortKey="state"
                  class="platform-table-phone-hidden md:w-[7%]"
                >
                  State
                </PlatformSortableTableHead>
              </>
            }
            body={
              <>
                <PlatformWindowedRows items={sortedRows} estimatedRowHeight={32}>
                  {(resource) => {
                    const share = () => shareMeta(resource);
                    const name = () => shareName(resource, share());
                    const displayStatus = () => getTrueNASResourceDisplayStatus(resource);
                    const indicator = () => getSimpleStatusIndicator(displayStatus());
                    const access = createMemo(() => formatAccess(share()));
                    const clients = createMemo(() => formatClients(share()));
                    const security = createMemo(() => formatSecurity(share()));
                    const stateLabel = () =>
                      formatPlatformTableTitleCaseValue(mapTrueNASShareStatus(resource));
                    const detailRowId = () => drawer.detailRowId(resource);
                    const isExpanded = () => drawer.isExpanded(resource);
                    return (
                      <>
                        <TableRow
                          class={`${getPlatformResourceDetailRowClass(isExpanded())} text-[11px] sm:text-xs`}
                          data-truenas-share-row={resource.id}
                          onClick={() => drawer.toggle(resource)}
                        >
                          <TableCell class={getPlatformTableCellClassForKind('name')}>
                            <div class="flex min-w-0 items-center gap-2">
                              <PlatformResourceDetailToggleButton
                                expanded={isExpanded()}
                                resourceLabel={name()}
                                controlsId={detailRowId()}
                                onToggle={() => drawer.toggle(resource)}
                              />
                              <StatusDot
                                size="sm"
                                variant={indicator().variant}
                                title={indicator().label}
                              />
                              <div class="flex min-w-0 flex-1 items-center gap-1.5">
                                <div
                                  class="min-w-0 truncate font-medium text-base-content"
                                  title={[
                                    name(),
                                    share()?.dataset ||
                                      share()?.path ||
                                      resource.parentName ||
                                      'TrueNAS',
                                  ]
                                    .filter(Boolean)
                                    .join(' · ')}
                                >
                                  {name()}
                                </div>
                                {/* A phone hides State; a state that needs attention joins the
                                    name on its line. */}
                                <span
                                  class={`platform-table-phone-only-inline text-[11px] ${getPlatformInlineStateClass(isPlatformAttentionVariant(indicator().variant))} ${getPlatformStatusTextToneClass(indicator().variant)}`}
                                  data-truenas-share-state-phone={indicator().variant}
                                >
                                  <span class="min-w-0 truncate">{stateLabel()}</span>
                                </span>
                              </div>
                            </div>
                          </TableCell>
                          <TableCell class={getPlatformTableCellClassForKind('text')}>
                            <span class="font-mono text-[11px] text-base-content">
                              {formatProtocol(share())}
                            </span>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} text-base-content`}
                          >
                            <span
                              class="block truncate font-mono text-[11px]"
                              title={share()?.path}
                            >
                              {share()?.path || '-'}
                            </span>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} platform-table-phone-hidden text-base-content`}
                            title={[access().title, security().title].filter(Boolean).join(' | ')}
                          >
                            <span class="block truncate">{access().label}</span>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('text')} hidden text-base-content lg:table-cell`}
                            title={clients().title}
                          >
                            <span class="block truncate">{clients().label}</span>
                          </TableCell>
                          <TableCell
                            class={`${getPlatformTableCellClassForKind('badge')} platform-table-phone-hidden`}
                          >
                            <span
                              class={`text-[11px] font-medium ${getPlatformStatusTextToneClass(indicator().variant) || 'text-base-content'}`}
                              data-truenas-share-state={indicator().variant}
                            >
                              {stateLabel()}
                            </span>
                          </TableCell>
                        </TableRow>
                        <PlatformResourceDetailTableRow
                          resource={resource}
                          statusIndicator={indicator()}
                          open={isExpanded()}
                          detailRowId={detailRowId()}
                          colSpan={6}
                          resolveResourceLabel={resolveResourceLabel}
                          onClose={() => drawer.close(resource)}
                        />
                      </>
                    );
                  }}
                </PlatformWindowedRows>
              </>
            }
          />
        </Show>
      </div>
    </Show>
  );
};

export default TrueNASNetworkSharesTable;