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.

12.1 KB
Raw Blame
/**
 * CollapsibleSection Component
 *
 * A reusable accordion-style section with animated expand/collapse.
 * Used to organize resource groups in the thresholds page.
 */

import { Component, For, Show, createSignal, createEffect, JSX } from 'solid-js';
import ChevronRight from 'lucide-solid/icons/chevron-right';
import ChevronDown from 'lucide-solid/icons/chevron-down';
import { StatusDot } from '@/components/shared/StatusDot';
import { getSimpleStatusIndicator } from '@/utils/status';
import {
  getAlertThresholdsSectionDisabledLabel,
  getAlertThresholdsSectionUnsavedChangesTitle,
} from '@/utils/alertThresholdsSectionPresentation';

export interface CollapsibleSectionProps {
  /** Unique identifier for the section */
  id: string;
  /** Section title */
  title: string;
  /** Number of resources in this section */
  resourceCount?: number;
  /** Whether the section is currently collapsed */
  collapsed?: boolean;
  /** Callback when collapse state changes */
  onToggle?: (collapsed: boolean) => void;
  /** Section content (children) */
  children: JSX.Element;
  /** Action buttons to show in the header (e.g., "Edit Defaults") */
  headerActions?: JSX.Element;
  /** Icon to show before the title */
  icon?: JSX.Element;
  /** Subtitle or description */
  subtitle?: string;
  /**
   * What the group alerts on by default, shown under the title so the page
   * answers "what will alert me" before the group is opened. Hidden while the
   * group is disabled, where it would promise alerts that cannot fire.
   */
  defaultsSummary?: string;
  /** Message to show when section is empty */
  emptyMessage?: string;
  /** Whether to show a visual indicator for global disable state */
  isGloballyDisabled?: boolean;
  /** Whether the section has unsaved changes */
  hasChanges?: boolean;
  /** Test ID for e2e testing */
  testId?: string;
}

export const CollapsibleSection: Component<CollapsibleSectionProps> = (props) => {
  // Local collapsed state if not controlled externally
  const [localCollapsed, setLocalCollapsed] = createSignal(props.collapsed ?? false);
  let contentElement: HTMLDivElement | undefined;

  // Sync with external collapsed state
  createEffect(() => {
    if (props.collapsed !== undefined) {
      setLocalCollapsed(props.collapsed);
    }
  });

  const isCollapsed = () => {
    return props.collapsed !== undefined ? props.collapsed : localCollapsed();
  };

  // Solid treats `inert` as a DOM property, but older DOM implementations do
  // not expose that property. Toggle the attribute directly so the browser's
  // native focus and accessibility-tree behavior is used consistently.
  createEffect(() => {
    contentElement?.toggleAttribute('inert', isCollapsed());
  });

  const handleToggle = () => {
    const newState = !isCollapsed();
    setLocalCollapsed(newState);
    props.onToggle?.(newState);
  };

  const isEmpty = () => props.resourceCount === 0;
  const showEmpty = () => isCollapsed() === false && isEmpty() && props.emptyMessage;

  return (
    <div
      class={`rounded-md border transition-all duration-200 ${props.isGloballyDisabled ? ' bg-surface-alt opacity-60' : 'border-border bg-surface '} ${props.hasChanges ? 'ring-2 ring-blue-400 ring-opacity-50' : ''}`}
      data-testid={props.testId || `section-${props.id}`}
    >
      {/*
        Keep actions beside the disclosure button rather than inside it. Apart
        from being invalid HTML, nested buttons produce an ambiguous focus
        order for keyboard and assistive-technology users.
      */}
      <div
        class={`flex w-full items-stretch transition-colors duration-150 hover:bg-surface-hover ${
          isCollapsed() ? 'rounded-md' : 'rounded-t-lg border-b border-border'
        }`}
      >
        <h3 class="min-w-0 flex-1">
          <button
            type="button"
            onClick={handleToggle}
            class="flex min-h-11 w-full min-w-0 items-center gap-3 px-4 py-3 text-left cursor-pointer select-none focus-visible:outline-solid focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-blue-500"
            aria-expanded={!isCollapsed()}
            aria-controls={`section-content-${props.id}`}
          >
            {/* Left side: Chevron + Icon + Title + Count */}
            <span class="shrink-0 text-muted transition-transform duration-200">
              <Show when={isCollapsed()} fallback={<ChevronDown class="w-5 h-5" />}>
                <ChevronRight class="w-5 h-5" />
              </Show>
            </span>

            <Show when={props.icon}>
              <span class="shrink-0 text-muted">{props.icon}</span>
            </Show>

            <span class="min-w-0">
              <span class="flex items-center gap-2">
                <span class="truncate font-semibold text-base-content">{props.title}</span>
                <Show when={props.resourceCount !== undefined}>
                  <span class="shrink-0 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-surface-alt text-muted">
                    {props.resourceCount}
                  </span>
                </Show>
                <Show when={props.isGloballyDisabled}>
                  <span class="shrink-0 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-700 dark:bg-yellow-900/25 dark:text-yellow-400">
                    {getAlertThresholdsSectionDisabledLabel()}
                  </span>
                </Show>
                <Show when={props.hasChanges}>
                  <span
                    class="shrink-0 w-2 h-2 rounded-full bg-blue-500"
                    title={getAlertThresholdsSectionUnsavedChangesTitle()}
                  />
                </Show>
              </span>
              <Show when={props.subtitle}>
                <span class="block truncate text-sm font-normal text-muted">{props.subtitle}</span>
              </Show>
              <Show when={!props.isGloballyDisabled && props.defaultsSummary}>
                <span
                  class="block text-xs font-normal tabular-nums text-muted sm:truncate sm:text-sm"
                  title={props.defaultsSummary}
                  data-thresholds-defaults-summary
                >
                  {/* Break between items only, never inside "Disk 90%". */}
                  <For each={props.defaultsSummary?.split(' · ') ?? []}>
                    {(item, index) => (
                      <>
                        {index() > 0 ? ' · ' : ''}
                        <span class="whitespace-nowrap">{item}</span>
                      </>
                    )}
                  </For>
                </span>
              </Show>
            </span>
          </button>
        </h3>

        <Show when={props.headerActions}>
          <div class="flex shrink-0 items-center gap-2 pr-4">{props.headerActions}</div>
        </Show>
      </div>

      {/* Section Content */}
      {/*
        Collapse switches the grid row track between 0fr and 1fr rather than
        animating max-height. CSS cannot transition to height:auto, so the
        earlier form animated up to a fixed max-h-[5000px] and clipped every
        section that grew past it (#1680). A taller cap only moves the cliff,
        so the row track carries the natural height and there is no ceiling.

        The transition is deliberately scoped to opacity. Under transition-all
        the browser holds grid-template-rows at whatever pixel value it had
        when the class flipped and never resolves the new track, which leaves
        a section stuck open or stuck shut permanently rather than merely
        un-animated. Verified in the browser: with transition-all the expanded
        track reported 0px indefinitely, and scoping to opacity resolved it to
        the full content height on the same element.

        The inner wrapper owns overflow-hidden so the collapsed track actually
        clips its content.
      */}
      <div
        ref={contentElement}
        id={`section-content-${props.id}`}
        aria-hidden={isCollapsed() ? 'true' : undefined}
        class={`grid transition-opacity duration-200 ease-in-out
 ${isCollapsed() ? 'grid-rows-[0fr] opacity-0' : 'grid-rows-[1fr] opacity-100'}`}
      >
        <div class="overflow-hidden min-h-0">
          <div class="p-4">
            <Show when={showEmpty()}>
              <div class="text-center py-8 text-muted">
                <p>{props.emptyMessage}</p>
              </div>
            </Show>
            <Show when={!isEmpty() || !props.emptyMessage}>{props.children}</Show>
          </div>
        </div>
      </div>
    </div>
  );
};

/**
 * A button for section header actions (e.g., "Edit Defaults") */
export interface SectionActionButtonProps {
  label: string;
  onClick: () => void;
  icon?: JSX.Element;
  variant?: 'default' | 'primary' | 'danger';
  disabled?: boolean;
  title?: string;
}
export const SectionActionButton: Component<SectionActionButtonProps> = (props) => {
  const variantClasses = {
    default: 'text-slate-600 hover:text-base-content hover:bg-slate-100',
    primary:
      'text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:text-blue-300 dark:hover:bg-blue-900/25',
    danger:
      'text-red-600 hover:text-red-700 hover:bg-red-50 dark:text-red-400 dark:hover:text-red-300 dark:hover:bg-red-900/25',
  };
  return (
    <button
      type="button"
      onClick={(e) => {
        e.stopPropagation();
        props.onClick();
      }}
      disabled={props.disabled}
      title={props.title}
      class={`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-sm font-medium
 transition-colors duration-150
 ${variantClasses[props.variant || 'default']}
 ${props.disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
    >
      <Show when={props.icon}>{props.icon}</Show>
      {props.label}
    </button>
  );
};

/**
 * Nested group header within a section (e.g., node name grouping VMs)
 */
export interface NestedGroupHeaderProps {
  title: string;
  subtitle?: string;
  count?: number;
  collapsed?: boolean;
  onToggle?: () => void;
  actions?: JSX.Element;
  status?: 'online' | 'offline' | 'unknown';
  href?: string;
}

export const NestedGroupHeader: Component<NestedGroupHeaderProps> = (props) => {
  const statusIndicator = () => getSimpleStatusIndicator(props.status);

  return (
    <div
      class={`flex items-center justify-between gap-3 px-3 py-2 -mx-3 rounded-md
 ${props.onToggle ? 'cursor-pointer hover:bg-surface-hover' : ''}
 transition-colors duration-150`}
      onClick={props.onToggle}
    >
      <div class="flex items-center gap-2 min-w-0">
        <Show when={props.onToggle}>
          <div class="shrink-0 text-slate-400">
            <Show when={props.collapsed} fallback={<ChevronDown class="w-4 h-4" />}>
              <ChevronRight class="w-4 h-4" />
            </Show>
          </div>
        </Show>

        <Show when={props.status}>
          <StatusDot
            class="shrink-0"
            variant={statusIndicator().variant}
            title={statusIndicator().label}
            ariaLabel={statusIndicator().label}
            size="xs"
          />
        </Show>

        <div class="min-w-0">
          <div class="flex items-center gap-2">
            <Show
              when={props.href}
              fallback={<span class="font-medium text-base-content truncate">{props.title}</span>}
            >
              <a
                href={props.href}
                target="_blank"
                rel="noopener noreferrer"
                class="font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 truncate"
                onClick={(e) => e.stopPropagation()}
              >
                {props.title}
              </a>
            </Show>
            <Show when={props.count !== undefined}>
              <span class="text-xs text-muted">({props.count})</span>
            </Show>
          </div>
          <Show when={props.subtitle}>
            <p class="text-xs text-muted truncate">{props.subtitle}</p>
          </Show>
        </div>
      </div>

      <Show when={props.actions}>
        <div class="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
          {props.actions}
        </div>
      </Show>
    </div>
  );
};

export default CollapsibleSection;