All files / memory-monitor/src MemoryMonitor.tsx

50% Statements 68/136
53.24% Branches 82/154
35.71% Functions 15/42
52.71% Lines 68/129

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940                                                                                                                                                                                1x                                                                                                 64x     64x 64x 27x       64x 64x     64x                               64x           64x     64x     64x     64x                 64x                                                                                                                                         64x                 64x 64x     64x     64x     64x 64x 64x   64x     64x 27x     64x 27x         64x                                                                                                                               64x 64x 64x       64x 27x 27x 27x                                                 64x                               64x             64x             64x 64x   61x                 1x                         1x                             1x                                                     64x 27x       37x 7x       30x       30x                                                                                                                   1x                           27x                                                                                                                                                                       1x                                                       1x           1x           1x                                                                               1x 1x   1x                                                                                                                                                     1x       1x       1x       1x       1x       1x       1x             1x                                                                                                                                             3x                                      
import React, { forwardRef, useState, useEffect, useCallback, useMemo } from "react";
import clsx from "clsx";
import { useMemoryMonitor } from "@usefy/use-memory-monitor";
import type { MemoryMonitorProps, PanelTab, Severity, PanelSnapshot, SnapshotAnalysisContext } from "./types";
import {
  DEFAULT_SETTINGS,
  DEFAULT_TRIGGER_POSITION,
  DEFAULT_SHORTCUT,
  PANEL_DIMENSIONS,
  Z_INDEX,
  SEVERITY_COLORS,
  formatBytes,
  SNAPSHOT_SCHEDULE_OPTIONS,
  HISTORY_SIZE_LIMITS,
} from "./constants";
import { isSSR, getShouldRender, getShouldActivate } from "./utils";
import styles from "./MemoryMonitor.module.scss";
import {
  useKeyboardShortcut,
  useEscapeKey,
  usePanelState,
  useSettings,
  useAutoGC,
  useTheme,
} from "./hooks";
import {
  Panel,
  PanelTrigger,
  PanelHeader,
  PanelTabs,
  PanelResizer,
} from "./components/Panel";
import {
  MemoryGauge,
  HistoryChart,
  HeapBreakdown,
  DOMMetrics,
  TrendIndicator,
} from "./components/Visualizations";
import { StatusBadge, LeakWarning } from "./components/Alerts";
import {
  ThresholdSlider,
  AutoGCToggle,
  ActionButtons,
  IntervalSelector,
  SnapshotSettings,
} from "./components/Controls";
import { SnapshotList, SnapshotCompare, ReportButton } from "./components/Snapshots";
 
/**
 * React component for real-time browser memory monitoring.
 *
 * Features:
 * - Real-time memory visualization with charts
 * - Threshold-based alerts (warning/critical)
 * - Automatic garbage collection triggers
 * - Memory leak detection
 * - Snapshot comparison
 * - Settings persistence
 * - Environment-aware (dev/prod modes)
 * - Keyboard shortcuts (Ctrl+Shift+M)
 *
 * @example
 * ```tsx
 * // Basic usage - shows only in development
 * function App() {
 *   return (
 *     <>
 *       <YourApp />
 *       <MemoryMonitor />
 *     </>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // With custom configuration
 * <MemoryMonitor
 *   mode="development"
 *   warningThreshold={70}
 *   criticalThreshold={90}
 *   enableAutoGC
 *   autoGCThreshold={85}
 *   onWarning={(data) => console.warn('Memory warning!', data)}
 * />
 * ```
 */
export const MemoryMonitor = forwardRef<HTMLDivElement, MemoryMonitorProps>(
  (props, ref) => {
    const {
      // Core Configuration
      mode = "development",
      defaultOpen = false,
      position = "right",
      zIndex = Z_INDEX.panel,
 
      // Monitoring Options
      interval = DEFAULT_SETTINGS.interval,
      enableHistory = true,
      historySize = 50,
      trackDOMNodes = true,
      trackEventListeners = true,
 
      // Threshold Configuration
      warningThreshold = DEFAULT_SETTINGS.warningThreshold,
      criticalThreshold = DEFAULT_SETTINGS.criticalThreshold,
      autoGCThreshold = DEFAULT_SETTINGS.autoGCThreshold,
      enableAutoGC = DEFAULT_SETTINGS.enableAutoGC,
 
      // Leak Detection
      enableLeakDetection = true,
      leakSensitivity = "medium",
 
      // UI Customization
      triggerContent,
      triggerPosition = DEFAULT_TRIGGER_POSITION,
      defaultWidth = PANEL_DIMENSIONS.defaultWidth,
      minWidth = PANEL_DIMENSIONS.minWidth,
      maxWidth = PANEL_DIMENSIONS.maxWidth,
      theme: themeProp = "system",
      className,
      showTrigger = true,
 
      // Callbacks
      onOpenChange,
      onWarning,
      onCritical,
      onLeakDetected,
      onAutoGC,
      onUpdate,
 
      // Advanced
      shortcut = DEFAULT_SHORTCUT,
      persistSettings = true,
      storageKey,
      disableInProduction = false,
    } = props;
 
    // SSR check - don't render anything on server
    const [mounted, setMounted] = useState(false);
    useEffect(() => {
      setMounted(true);
    }, []);
 
    // Determine if we should render and activate
    const shouldRender = getShouldRender(mode);
    const shouldActivate = getShouldActivate(mode, disableInProduction);
 
    // Settings persistence
    const { settings, updateSettings, isLoaded } = useSettings({
      storageKey,
      persist: persistSettings,
      initialSettings: {
        warningThreshold,
        criticalThreshold,
        autoGCThreshold,
        enableAutoGC,
        interval,
        theme: themeProp,
        panelWidth: defaultWidth,
        historySize,
      },
    });
 
    // Panel state
    const { isOpen, toggle, close, activeTab, setActiveTab } = usePanelState({
      defaultOpen,
      onOpenChange,
    });
 
    // Theme
    const { resolvedTheme } = useTheme({
      theme: settings.theme,
    });
    const isDark = resolvedTheme === "dark";
 
    // Panel width state
    const [panelWidth, setPanelWidth] = useState(settings.panelWidth);
 
    // Update settings when width changes
    const handleWidthChange = useCallback(
      (width: number) => {
        setPanelWidth(width);
        updateSettings({ panelWidth: width });
      },
      [updateSettings]
    );
 
    // Core memory monitor hook
    const monitor = useMemoryMonitor({
      interval: settings.interval,
      autoStart: shouldActivate,
      enabled: shouldActivate,
      enableHistory,
      historySize: settings.historySize ?? historySize,
      trackDOMNodes,
      trackEventListeners,
      thresholds: {
        warning: settings.warningThreshold,
        critical: settings.criticalThreshold,
      },
      leakDetection: {
        enabled: enableLeakDetection,
        sensitivity: leakSensitivity,
      },
      onUpdate: onUpdate
        ? (memory) => {
            onUpdate({
              heapUsed: memory.heapUsed,
              heapTotal: memory.heapTotal,
              heapLimit: memory.heapLimit,
              timestamp: memory.timestamp,
            });
          }
        : undefined,
      onWarning: onWarning
        ? (data) => {
            onWarning({
              memory: {
                heapUsed: data.memory.heapUsed,
                heapTotal: data.memory.heapTotal,
                heapLimit: data.memory.heapLimit,
                timestamp: data.memory.timestamp,
              },
              usagePercentage: data.usagePercentage,
              threshold: data.threshold,
              timestamp: data.timestamp,
            });
          }
        : undefined,
      onCritical: onCritical
        ? (data) => {
            onCritical({
              memory: {
                heapUsed: data.memory.heapUsed,
                heapTotal: data.memory.heapTotal,
                heapLimit: data.memory.heapLimit,
                timestamp: data.memory.timestamp,
              },
              usagePercentage: data.usagePercentage,
              threshold: data.threshold,
              timestamp: data.timestamp,
            });
          }
        : undefined,
      onLeakDetected: onLeakDetected
        ? (analysis) => {
            onLeakDetected({
              isLeaking: analysis.isLeaking,
              probability: analysis.probability,
              trend: analysis.trend,
              recommendation: analysis.recommendation,
            });
          }
        : undefined,
    });
 
    // Auto-GC
    useAutoGC({
      enabled: settings.enableAutoGC,
      threshold: settings.autoGCThreshold,
      usagePercentage: monitor.usagePercentage,
      requestGC: monitor.requestGC,
      onAutoGC,
    });
 
    // Keyboard shortcuts
    useKeyboardShortcut(shortcut, toggle, mounted && shouldRender);
    useEscapeKey(close, mounted && shouldRender && isOpen);
 
    // Snapshot scheduler ref to track last auto-snapshot time
    const lastAutoSnapshotRef = React.useRef<number>(0);
 
    // Current severity
    const severity: Severity = monitor.severity;
 
    // Snapshot state management
    const [snapshots, setSnapshots] = useState<PanelSnapshot[]>([]);
    const [selectedSnapshotId, setSelectedSnapshotId] = useState<string | null>(null);
    const [compareSnapshotId, setCompareSnapshotId] = useState<string | null>(null);
    // Counter for sequential snapshot numbering (persists through auto-delete cycles)
    const snapshotCounterRef = React.useRef(0);
 
    // Get selected snapshots
    const selectedSnapshot = useMemo(
      () => snapshots.find((s) => s.id === selectedSnapshotId) ?? null,
      [snapshots, selectedSnapshotId]
    );
    const compareSnapshot = useMemo(
      () => snapshots.find((s) => s.id === compareSnapshotId) ?? null,
      [snapshots, compareSnapshotId]
    );
 
    // Take snapshot handler
    const handleTakeSnapshot = useCallback((isAuto = false) => {
      const maxSnapshots = settings.snapshot?.maxSnapshots ?? DEFAULT_SETTINGS.snapshot.maxSnapshots;
      const autoDeleteOldest = settings.snapshot?.autoDeleteOldest ?? true;
 
      // Capture current analysis context
      const analysisContext: SnapshotAnalysisContext = {
        trend: monitor.trend,
        leakProbability: monitor.leakProbability,
        severity: monitor.severity,
        usagePercentage: monitor.usagePercentage ?? 0,
      };
 
      // Increment counter for sequential numbering
      snapshotCounterRef.current += 1;
      const snapshotNumber = snapshotCounterRef.current;
 
      // If at max capacity
      if (snapshots.length >= maxSnapshots) {
        if (autoDeleteOldest) {
          // Delete oldest and add new one
          setSnapshots((prev) => {
            const remaining = prev.slice(1);
            const id = `snapshot-${Date.now()}`;
            const label = isAuto ? `Auto ${snapshotNumber}` : `Snapshot ${snapshotNumber}`;
            const newSnapshot: PanelSnapshot = {
              id,
              label,
              timestamp: Date.now(),
              heapUsed: monitor.memory?.heapUsed ?? 0,
              heapTotal: monitor.memory?.heapTotal ?? 0,
              heapLimit: monitor.memory?.heapLimit ?? 0,
              domNodes: monitor.domNodes ?? undefined,
              eventListeners: monitor.eventListeners ?? undefined,
              isAuto,
              analysisContext,
            };
            monitor.takeSnapshot(id);
            return [...remaining, newSnapshot];
          });
        }
        return;
      }
 
      const id = `snapshot-${Date.now()}`;
      const label = isAuto ? `Auto ${snapshotNumber}` : `Snapshot ${snapshotNumber}`;
 
      const newSnapshot: PanelSnapshot = {
        id,
        label,
        timestamp: Date.now(),
        heapUsed: monitor.memory?.heapUsed ?? 0,
        heapTotal: monitor.memory?.heapTotal ?? 0,
        heapLimit: monitor.memory?.heapLimit ?? 0,
        domNodes: monitor.domNodes ?? undefined,
        eventListeners: monitor.eventListeners ?? undefined,
        isAuto,
        analysisContext,
      };
 
      setSnapshots((prev) => [...prev, newSnapshot]);
      monitor.takeSnapshot(id);
    }, [snapshots.length, monitor, settings.snapshot]);
 
    // Ref for the latest handleTakeSnapshot to avoid stale closure in interval
    const handleTakeSnapshotRef = React.useRef(handleTakeSnapshot);
    useEffect(() => {
      handleTakeSnapshotRef.current = handleTakeSnapshot;
    }, [handleTakeSnapshot]);
 
    // Snapshot scheduler effect
    useEffect(() => {
      const scheduleInterval = settings.snapshot?.scheduleInterval ?? "off";
      Eif (scheduleInterval === "off" || !shouldActivate) {
        return;
      }
 
      const scheduleOption = SNAPSHOT_SCHEDULE_OPTIONS.find(
        (opt) => opt.value === scheduleInterval
      );
      if (!scheduleOption || scheduleOption.intervalMs === 0) {
        return;
      }
 
      // Take first snapshot immediately when schedule is enabled
      lastAutoSnapshotRef.current = Date.now();
      handleTakeSnapshotRef.current(true);
 
      const intervalId = setInterval(() => {
        lastAutoSnapshotRef.current = Date.now();
        handleTakeSnapshotRef.current(true);
      }, scheduleOption.intervalMs);
 
      return () => {
        clearInterval(intervalId);
      };
    }, [settings.snapshot?.scheduleInterval, shouldActivate]);
 
    // Select snapshot handler
    const handleSelectSnapshot = useCallback((snapshot: PanelSnapshot) => {
      if (selectedSnapshotId === snapshot.id) {
        // Deselect if clicking the same
        setSelectedSnapshotId(null);
        setCompareSnapshotId(null);
      } else if (selectedSnapshotId === null) {
        // First selection
        setSelectedSnapshotId(snapshot.id);
      } else {
        // Second selection - set as compare target
        setCompareSnapshotId(selectedSnapshotId);
        setSelectedSnapshotId(snapshot.id);
      }
    }, [selectedSnapshotId]);
 
    // Delete snapshot handler
    const handleDeleteSnapshot = useCallback((id: string) => {
      setSnapshots((prev) => prev.filter((s) => s.id !== id));
      if (selectedSnapshotId === id) setSelectedSnapshotId(null);
      if (compareSnapshotId === id) setCompareSnapshotId(null);
    }, [selectedSnapshotId, compareSnapshotId]);
 
    // Delete all snapshots handler
    const handleDeleteAllSnapshots = useCallback(() => {
      setSnapshots([]);
      setSelectedSnapshotId(null);
      setCompareSnapshotId(null);
    }, []);
 
    // Memoized tab content
    const tabContent = useMemo(() => {
      switch (activeTab) {
        case "overview":
          return (
            <OverviewTab
              monitor={monitor}
              settings={settings}
              isDark={isDark}
              onTakeSnapshot={handleTakeSnapshot}
            />
          );
        case "history":
          return (
            <HistoryTab
              history={monitor.history}
              trend={monitor.trend}
              leakProbability={monitor.leakProbability}
              severity={monitor.severity}
              heapLimit={monitor.memory?.heapLimit ?? null}
              warningThreshold={settings.warningThreshold}
              criticalThreshold={settings.criticalThreshold}
              isDark={isDark}
            />
          );
        case "snapshots":
          return (
            <SnapshotsTab
              snapshots={snapshots}
              selectedSnapshot={selectedSnapshot}
              compareSnapshot={compareSnapshot}
              onSelect={handleSelectSnapshot}
              onDelete={handleDeleteSnapshot}
              onDeleteAll={handleDeleteAllSnapshots}
              onTakeSnapshot={() => handleTakeSnapshot(false)}
              maxSnapshots={settings.snapshot?.maxSnapshots ?? DEFAULT_SETTINGS.snapshot.maxSnapshots}
              autoDeleteOldest={settings.snapshot?.autoDeleteOldest ?? true}
              isDark={isDark}
            />
          );
        case "settings":
          return (
            <SettingsTab
              settings={settings}
              updateSettings={updateSettings}
              isSupported={monitor.isSupported}
              isDark={isDark}
            />
          );
        default:
          return null;
      }
    }, [
      activeTab,
      monitor,
      settings,
      updateSettings,
      isDark,
      snapshots,
      selectedSnapshot,
      compareSnapshot,
      handleTakeSnapshot,
      handleSelectSnapshot,
      handleDeleteSnapshot,
      handleDeleteAllSnapshots,
    ]);
 
    // Don't render on server
    if (!mounted || isSSR()) {
      return null;
    }
 
    // Don't render if mode says not to
    if (!shouldRender) {
      return null;
    }
 
    // Don't render until settings are loaded
    Iif (!isLoaded) {
      return null;
    }
 
    return (
      <>
        {/* Floating trigger button */}
        {showTrigger && !isOpen && (
          <PanelTrigger
            onClick={toggle}
            position={triggerPosition}
            zIndex={zIndex - 1}
            severity={severity}
            isDark={isDark}
          >
            {triggerContent}
          </PanelTrigger>
        )}
 
        {/* Main panel */}
        <Panel
          ref={ref}
          isOpen={isOpen}
          position={position}
          width={panelWidth}
          zIndex={zIndex}
          isDark={isDark}
          className={className}
        >
          {/* Resizer */}
          <PanelResizer
            width={panelWidth}
            onWidthChange={handleWidthChange}
            position={position}
            minWidth={minWidth}
            maxWidth={maxWidth}
          />
 
          {/* Header */}
          <PanelHeader
            severity={severity}
            isMonitoring={monitor.isMonitoring}
            onClose={close}
          />
 
          {/* Tabs */}
          <PanelTabs
            activeTab={activeTab}
            onTabChange={setActiveTab}
            isAutoSnapshotActive={(settings.snapshot?.scheduleInterval ?? "off") !== "off"}
          />
 
          {/* Tab content */}
          <div className={styles.tabContent}>
            {tabContent}
          </div>
        </Panel>
      </>
    );
  }
);
 
MemoryMonitor.displayName = "MemoryMonitor";
 
// ============================================================================
// Tab Components
// ============================================================================
 
interface OverviewTabProps {
  monitor: ReturnType<typeof useMemoryMonitor>;
  settings: ReturnType<typeof useSettings>["settings"];
  isDark: boolean;
  onTakeSnapshot: () => void;
}
 
function OverviewTab({ monitor, settings, isDark, onTakeSnapshot }: OverviewTabProps) {
  return (
    <div className={styles.section}>
      {/* Memory Gauge */}
      <MemoryGauge
        usagePercentage={monitor.usagePercentage ?? 0}
        severity={monitor.severity}
        heapUsed={monitor.formatted.heapUsed}
        heapLimit={monitor.formatted.heapLimit}
        warningThreshold={settings.warningThreshold}
        criticalThreshold={settings.criticalThreshold}
      />
 
      {/* Status and Trend */}
      <div className={styles.statusRow}>
        <StatusBadge severity={monitor.severity} />
        <TrendIndicator
          trend={monitor.trend}
          leakProbability={monitor.leakProbability}
          compact
        />
      </div>
 
      {/* Heap Breakdown */}
      <HeapBreakdown
        heapUsed={monitor.memory?.heapUsed ?? 0}
        heapTotal={monitor.memory?.heapTotal ?? 0}
        heapLimit={monitor.memory?.heapLimit ?? 0}
        severity={monitor.severity}
        warningThreshold={settings.warningThreshold}
        criticalThreshold={settings.criticalThreshold}
      />
 
      {/* DOM Metrics */}
      <DOMMetrics
        domNodes={monitor.domNodes}
        eventListeners={monitor.eventListeners}
      />
 
      {/* Leak Warning */}
      <LeakWarning
        isLeaking={monitor.isLeakDetected}
        probability={monitor.leakProbability}
        trend={monitor.trend}
        recommendation={
          monitor.leakProbability >= 70
            ? "High probability of memory leak. Check for unsubscribed subscriptions."
            : monitor.leakProbability >= 40
              ? "Moderate risk. Monitor memory usage closely."
              : undefined
        }
        compact
      />
 
      {/* Quick Actions */}
      <ActionButtons
        onRequestGC={monitor.requestGC}
        onTakeSnapshot={onTakeSnapshot}
        gcSupported={monitor.isSupported}
        snapshotEnabled
        exportEnabled={false}
      />
    </div>
  );
}
 
interface HistoryTabProps {
  history: ReturnType<typeof useMemoryMonitor>["history"];
  trend: ReturnType<typeof useMemoryMonitor>["trend"];
  leakProbability: number;
  severity: Severity;
  heapLimit: number | null;
  warningThreshold: number;
  criticalThreshold: number;
  isDark: boolean;
}
 
function HistoryTab({
  history,
  trend,
  leakProbability,
  heapLimit,
  warningThreshold,
  criticalThreshold,
}: HistoryTabProps) {
  return (
    <div className={styles.section}>
      {/* History Chart */}
      <HistoryChart
        history={history}
        heapLimit={heapLimit}
        warningThreshold={warningThreshold}
        criticalThreshold={criticalThreshold}
        height={200}
      />
 
      {/* Trend Indicator */}
      <TrendIndicator
        trend={trend}
        leakProbability={leakProbability}
        sampleCount={history.length}
      />
 
      {/* Stats */}
      {history.length > 0 && (
        <div className={styles.statsContainer}>
          <div className={styles.statsTitle}>
            Statistics
          </div>
          <div className={styles.statsGrid}>
            <div>
              <span className={styles.statLabel}>Min:</span>{" "}
              <span className={styles.statValue}>
                {formatBytes(Math.min(...history.map(h => h.heapUsed)))}
              </span>
            </div>
            <div>
              <span className={styles.statLabel}>Max:</span>{" "}
              <span className={styles.statValue}>
                {formatBytes(Math.max(...history.map(h => h.heapUsed)))}
              </span>
            </div>
            <div>
              <span className={styles.statLabel}>Avg:</span>{" "}
              <span className={styles.statValue}>
                {formatBytes(history.reduce((sum, h) => sum + h.heapUsed, 0) / history.length)}
              </span>
            </div>
            <div>
              <span className={styles.statLabel}>Samples:</span>{" "}
              <span className={styles.statValue}>
                {history.length}
              </span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
 
interface SnapshotsTabProps {
  snapshots: PanelSnapshot[];
  selectedSnapshot: PanelSnapshot | null;
  compareSnapshot: PanelSnapshot | null;
  onSelect: (snapshot: PanelSnapshot) => void;
  onDelete: (id: string) => void;
  onDeleteAll: () => void;
  onTakeSnapshot: () => void;
  maxSnapshots: number;
  autoDeleteOldest: boolean;
  isDark: boolean;
}
 
function SnapshotsTab({
  snapshots,
  selectedSnapshot,
  compareSnapshot,
  onSelect,
  onDelete,
  onDeleteAll,
  onTakeSnapshot,
  maxSnapshots,
  autoDeleteOldest,
}: SnapshotsTabProps) {
  const isAtCapacity = snapshots.length >= maxSnapshots;
  const canTakeSnapshot = !isAtCapacity || autoDeleteOldest;
 
  return (
    <div className={styles.section}>
      {/* Action Buttons */}
      <div className={styles.snapshotActions}>
        {/* Take Snapshot Button */}
        <button
          type="button"
          onClick={onTakeSnapshot}
          disabled={!canTakeSnapshot}
          className={styles.takeSnapshotButton}
        >
          {isAtCapacity && autoDeleteOldest
            ? "Take Snapshot (replace oldest)"
            : "Take Snapshot"}
        </button>
 
        {/* Delete All Button */}
        <button
          type="button"
          onClick={onDeleteAll}
          disabled={snapshots.length === 0}
          className={styles.deleteAllButton}
          title="Delete all snapshots"
        >
          Delete All
        </button>
      </div>
 
      {/* Report Button */}
      <ReportButton snapshots={snapshots} />
 
      {/* Capacity indicator */}
      <div className={styles.capacityIndicator}>
        <span>{snapshots.length} / {maxSnapshots} snapshots</span>
        {autoDeleteOldest && isAtCapacity && (
          <span className={styles.autoDeleteWarning}>Auto-delete enabled</span>
        )}
      </div>
 
      {/* Snapshot Comparison */}
      {selectedSnapshot && compareSnapshot && (
        <SnapshotCompare
          baseline={compareSnapshot}
          current={selectedSnapshot}
        />
      )}
 
      {/* Snapshot List */}
      <SnapshotList
        snapshots={snapshots}
        selectedId={selectedSnapshot?.id}
        compareId={compareSnapshot?.id}
        onSelect={onSelect}
        onDelete={onDelete}
        maxSnapshots={maxSnapshots}
      />
 
      {/* Help text */}
      {snapshots.length >= 2 && (
        <p className={styles.helpText}>
          Select two snapshots to compare them
        </p>
      )}
    </div>
  );
}
 
interface SettingsTabProps {
  settings: ReturnType<typeof useSettings>["settings"];
  updateSettings: ReturnType<typeof useSettings>["updateSettings"];
  isSupported: boolean;
  isDark: boolean;
}
 
function SettingsTab({ settings, updateSettings, isSupported }: SettingsTabProps) {
  const handleWarningChange = useCallback((value: number) => {
    updateSettings({ warningThreshold: value });
  }, [updateSettings]);
 
  const handleCriticalChange = useCallback((value: number) => {
    updateSettings({ criticalThreshold: value });
  }, [updateSettings]);
 
  const handleAutoGCToggle = useCallback((enabled: boolean) => {
    updateSettings({ enableAutoGC: enabled });
  }, [updateSettings]);
 
  const handleAutoGCThresholdChange = useCallback((threshold: number | null) => {
    updateSettings({ autoGCThreshold: threshold });
  }, [updateSettings]);
 
  const handleIntervalChange = useCallback((interval: number) => {
    updateSettings({ interval });
  }, [updateSettings]);
 
  const handleHistorySizeChange = useCallback((historySize: number) => {
    updateSettings({ historySize });
  }, [updateSettings]);
 
  const handleSnapshotSettingsChange = useCallback(
    (snapshotSettings: typeof settings.snapshot) => {
      updateSettings({ snapshot: snapshotSettings });
    },
    [updateSettings]
  );
 
  return (
    <div className={styles.sectionLarge}>
      {/* Threshold Settings */}
      <div className={styles.section}>
        <h4 className={styles.settingsTitle}>
          Thresholds
        </h4>
        <ThresholdSlider
          label="Warning Threshold"
          value={settings.warningThreshold}
          onChange={handleWarningChange}
          color={SEVERITY_COLORS.warning.accent}
          helperText="Alert when memory usage exceeds this level"
        />
        <ThresholdSlider
          label="Critical Threshold"
          value={settings.criticalThreshold}
          onChange={handleCriticalChange}
          color={SEVERITY_COLORS.critical.accent}
          helperText="Critical alert threshold"
        />
      </div>
 
      {/* Auto-GC Settings */}
      <AutoGCToggle
        enabled={settings.enableAutoGC}
        onToggle={handleAutoGCToggle}
        threshold={settings.autoGCThreshold}
        onThresholdChange={handleAutoGCThresholdChange}
        isSupported={isSupported}
      />
 
      {/* Polling Interval */}
      <IntervalSelector
        value={settings.interval}
        onChange={handleIntervalChange}
      />
 
      {/* History Size */}
      <div className={styles.sectionSmall}>
        <h4 className={styles.settingsTitle}>
          Memory Trend
        </h4>
        <ThresholdSlider
          label="History Size"
          value={settings.historySize ?? DEFAULT_SETTINGS.historySize}
          onChange={handleHistorySizeChange}
          min={HISTORY_SIZE_LIMITS.min}
          max={HISTORY_SIZE_LIMITS.max}
          step={10}
          color="#6366f1"
          suffix=" samples"
          helperText="Number of samples to keep in memory trend history"
        />
      </div>
 
      {/* Snapshot Settings */}
      <div className={styles.settingsDivider}>
        <SnapshotSettings
          value={settings.snapshot ?? DEFAULT_SETTINGS.snapshot}
          onChange={handleSnapshotSettingsChange}
        />
      </div>
 
      {/* Theme Settings */}
      <div className={styles.sectionSmall}>
        <h4 className={styles.settingsTitle}>
          Theme
        </h4>
        <div className={styles.themeButtons}>
          {(["system", "light", "dark"] as const).map((theme) => (
            <button
              key={theme}
              type="button"
              onClick={() => updateSettings({ theme })}
              className={clsx(
                styles.themeButton,
                settings.theme === theme
                  ? styles.themeButtonActive
                  : styles.themeButtonInactive
              )}
            >
              {theme}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}