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.

7.5 KB
Raw Blame
import {
  createEffect,
  createMemo,
  createSignal,
  onCleanup,
  untrack,
  type Accessor,
} from 'solid-js';
import { findInlineDetailElement, revealInlineDetailInViewport } from './contextualFocus';
import { resolveSummaryActiveSeriesId } from './summaryCardInteraction';

const normalizeSeriesId = (value: string | null | undefined): string => value?.trim() || '';

const escapeAttributeSelectorValue = (value: string): string =>
  value.split('\\').join('\\\\').split('"').join('\\"');

const SUMMARY_CLEAR_IGNORE_SELECTOR = [
  'button',
  'a',
  'input',
  'select',
  'textarea',
  'th',
  'label',
  'summary',
  '[role="button"]',
  '[role="link"]',
  '[role="menuitem"]',
  '[data-summary-clear-ignore]',
  '[data-summary-series-id]',
  '[data-summary-group-id]',
  '[data-inline-detail-for]',
].join(', ');

export interface UseSummaryTableFocusBridgeOptions {
  focusedSeriesId?: Accessor<string | null | undefined>;
  clearPinnedScope?: () => void;
  onEscapeClear?: () => void;
  revealActiveSeries?: (seriesId: string) => void;
}

export function useSummaryTableFocusBridge(options: UseSummaryTableFocusBridgeOptions) {
  const [tableRoot, setTableRoot] = createSignal<HTMLElement | null>(null);
  const [clearSurfaceRoot, setClearSurfaceRoot] = createSignal<HTMLElement | null>(null);
  const focusedSeriesId = options.focusedSeriesId ?? (() => null);

  const focusedRow = (): HTMLElement | null => {
    const root = tableRoot();
    const focusedId = normalizeSeriesId(focusedSeriesId());
    if (!root || !focusedId) {
      return null;
    }
    return root.querySelector<HTMLElement>(
      `[data-summary-series-id="${escapeAttributeSelectorValue(focusedId)}"]`,
    );
  };

  createEffect(() => {
    const root = clearSurfaceRoot() ?? tableRoot();
    const lookupRoot = tableRoot();
    if (!root || !lookupRoot || !options.clearPinnedScope) {
      return;
    }

    const handleRootClick = (event: MouseEvent) => {
      if (!normalizeSeriesId(focusedSeriesId())) {
        return;
      }
      const target = event.target;
      if (!(target instanceof HTMLElement) || !root.contains(target)) {
        return;
      }
      if (target.closest(SUMMARY_CLEAR_IGNORE_SELECTOR)) {
        return;
      }
      if (!lookupRoot.contains(target)) {
        const lookupRect = lookupRoot.getBoundingClientRect();
        const targetRect = target.getBoundingClientRect();
        const targetCenterY =
          targetRect.height > 0 ? targetRect.top + targetRect.height / 2 : event.clientY;
        if (targetCenterY < lookupRect.top) {
          return;
        }
      }
      options.clearPinnedScope?.();
    };

    root.addEventListener('click', handleRootClick);
    onCleanup(() => {
      root.removeEventListener('click', handleRootClick);
    });
  });

  createEffect(() => {
    if (typeof document === 'undefined' || !options.onEscapeClear) {
      return;
    }

    const handleDocumentKeyDown = (event: KeyboardEvent) => {
      if (
        event.key !== 'Escape' ||
        event.defaultPrevented ||
        event.altKey ||
        event.ctrlKey ||
        event.metaKey ||
        event.shiftKey
      ) {
        return;
      }
      const target = event.target;
      if (target instanceof HTMLElement && target.closest('[role="dialog"], [aria-modal="true"]')) {
        return;
      }
      options.onEscapeClear?.();
    };

    document.addEventListener('keydown', handleDocumentKeyDown);
    onCleanup(() => {
      document.removeEventListener('keydown', handleDocumentKeyDown);
    });
  });

  // Runs inside the reveal effect below with tracking off, so the cleanup it
  // registers still belongs to that effect run.
  const revealFocusedSeries = (root: HTMLElement, focusedId: string) => {
    options.revealActiveSeries?.(focusedId);

    let settled = false;
    let rafId: number | undefined;
    let observer: MutationObserver | undefined;
    let timeoutId: number | undefined;

    const cleanup = () => {
      settled = true;
      if (rafId !== undefined) {
        window.cancelAnimationFrame(rafId);
      }
      if (timeoutId !== undefined) {
        window.clearTimeout(timeoutId);
      }
      observer?.disconnect();
    };
    onCleanup(cleanup);

    const settleReveal = (remainingFrames: number) => {
      if (settled) {
        return;
      }
      const row = focusedRow();
      const detail = findInlineDetailElement(root, focusedId);
      if (!row || !detail) {
        cleanup();
        return;
      }

      const didScroll = revealInlineDetailInViewport({
        row,
        detail,
      });

      if (remainingFrames <= 0 || !didScroll) {
        cleanup();
        return;
      }

      rafId = window.requestAnimationFrame(() => {
        settleReveal(remainingFrames - 1);
      });
    };

    const attemptReveal = (): boolean => {
      if (settled) {
        return true;
      }
      const row = focusedRow();
      if (!row || !root) {
        return false;
      }

      const detail = findInlineDetailElement(root, focusedId);
      if (!detail) {
        return false;
      }

      settleReveal(2);
      return true;
    };

    if (attemptReveal()) {
      return;
    }

    observer = new MutationObserver(() => {
      attemptReveal();
    });
    observer.observe(root, { childList: true, subtree: true });

    let remainingFrames = 24;
    const scheduleAttempt = () => {
      if (attemptReveal() || remainingFrames <= 0) {
        return;
      }
      remainingFrames -= 1;
      rafId = window.requestAnimationFrame(scheduleAttempt);
    };

    rafId = window.requestAnimationFrame(scheduleAttempt);
    timeoutId = window.setTimeout(() => {
      cleanup();
    }, 1200);
  };

  // Reveal once per deliberate focus change. The effect subscribes to the
  // focused id and table root only: the consumer's reveal callback reads live
  // table state (group maps, expanded groups) that changes on every update or
  // collapse, and a re-run would pull the page back to the row or reopen a
  // group the operator just closed.
  const revealSeriesId = createMemo(() => normalizeSeriesId(focusedSeriesId()));
  createEffect(() => {
    const focusedId = revealSeriesId();
    const root = tableRoot();
    if (!focusedId || !root || typeof window === 'undefined') {
      return;
    }
    untrack(() => revealFocusedSeries(root, focusedId));
  });

  return {
    setClearSurfaceRootRef: (element: HTMLElement | undefined) =>
      setClearSurfaceRoot(element ?? null),
    setTableRootRef: (element: HTMLElement | undefined) => setTableRoot(element ?? null),
  } as const;
}

export interface UseSummaryPageInteractionStateOptions {
  hoveredSeriesId?: Accessor<string | null | undefined>;
  focusedSeriesId?: Accessor<string | null | undefined>;
  clearPinnedScope?: () => void;
  onEscapeClear?: () => void;
  revealActiveSeries?: (seriesId: string) => void;
}

export function useSummaryPageInteractionState(options: UseSummaryPageInteractionStateOptions) {
  const hoveredSeriesId = options.hoveredSeriesId ?? (() => null);
  const focusedSeriesId = options.focusedSeriesId ?? (() => null);

  const activeSeriesId = createMemo<string | null>(() =>
    resolveSummaryActiveSeriesId({
      hoveredSeriesId: hoveredSeriesId(),
      focusedSeriesId: focusedSeriesId(),
    }),
  );

  const tableFocus = useSummaryTableFocusBridge({
    clearPinnedScope: options.clearPinnedScope,
    focusedSeriesId,
    onEscapeClear: options.onEscapeClear,
    revealActiveSeries: options.revealActiveSeries,
  });

  return {
    activeSeriesId,
    setClearSurfaceRootRef: tableFocus.setClearSurfaceRootRef,
    setTableRootRef: tableFocus.setTableRootRef,
  } as const;
}