import React, { Component, useCallback, useEffect, useReducer, useRef, useState } from 'react'; import { View, Text, StyleSheet, Animated, } from 'react-native'; import type { AnyDebugFeature } from '../../types'; import type { DebugQuickAction } from '../../types/config'; import { Colors } from '../theme/colors'; import { FontSize, Spacing } from '../theme/layout'; import { getPreference, persistPreference, KEYS } from '../../utils/debugPreferences'; import { FloatIcon } from '../floating/FloatIcon'; import { DebugPanel } from './DebugPanel'; import { FeatureRail } from './FeatureRail'; import type { RailItem } from './FeatureRail'; import { FeatureIntroCard } from './FeatureIntroCard'; import { FeatureStatusView } from './FeatureStatusView'; import { buildFeatureSummary } from './buildFeatureSummary'; import { filterFeatureSnapshot } from './filterFeatureSnapshot'; import { INITIAL_PANEL_FILTER_STATE, changeTabWithFilterReset, clearAllWithFilterReset, panelFilterReducer, } from './panelFilterState'; import { resolveStoredTabIndex } from './tabPersistence'; import { useTabAnimation } from './useTabAnimation'; import { t, type TranslationKey } from '../../i18n'; // ─── Error Boundary ──────────────────────────────────── interface ErrorBoundaryState { hasError: boolean; message?: string; } class DebugErrorBoundary extends Component< { children: React.ReactNode; onError?: () => void; name?: string }, ErrorBoundaryState > { state: ErrorBoundaryState = { hasError: false }; static getDerivedStateFromError(error: Error): ErrorBoundaryState { return { hasError: true, message: error.message }; } componentDidCatch(error: Error, info: React.ErrorInfo) { console.error('[DebugToolkit] Panel crashed:', error, info.componentStack); this.props.onError?.(); } render() { if (this.state.hasError) return ; return this.props.children; } } // ─── Snapshot helpers ────────────────────────────────── function snapshotCount(feature: AnyDebugFeature): number | undefined { try { const snap = feature.getSnapshot(); if (Array.isArray(snap)) return snap.length; if (snap && typeof snap === 'object') { const obj = snap as Record; if (Array.isArray(obj.items)) return obj.items.length; if (Array.isArray(obj.logs)) return obj.logs.length; if (Array.isArray(obj.entries)) return obj.entries.length; if (Array.isArray(obj.environments)) return obj.environments.length; if (typeof obj.accountCount === 'number') return obj.accountCount; } } catch { /* ignore */ } return undefined; } interface PanelConnectionStatus { label: string; color: string; } interface DevConnectSnapshot { canonicalEndpoint?: string; } const FEATURE_LABEL_KEYS: Record = { network: 'feature.network', console: 'feature.console', native: 'feature.native', navigation: 'feature.navigation', state: 'feature.state', track: 'feature.track', clipboard: 'feature.clipboard', environment: 'feature.environment', connect: 'feature.connect', history: 'feature.history', accounts: 'feature.accounts', tabs: 'feature.tabs', }; const DEFAULT_FEATURE_LABELS: Record = { network: 'Network', console: 'Console', native: 'Native', navigation: 'Navigation', state: 'State', track: 'Track', clipboard: 'Clipboard', environment: 'Environment', connect: 'Connect', history: 'History', accounts: 'Accounts', tabs: 'Custom', }; function buildPanelConnectionStatus(features: AnyDebugFeature[]): PanelConnectionStatus { const devConnect = features.find((f) => f.name === 'connect'); if (!devConnect) { return { label: t('panel.sharedHubUnavailable'), color: Colors.textMuted }; } try { const snap = (devConnect.getSnapshot() ?? {}) as DevConnectSnapshot; const endpoint = snap.canonicalEndpoint?.trim(); return { label: endpoint ? t('panel.sharedHubConfigured') : t('panel.sharedHubNotConfigured'), color: Colors.textMuted, }; } catch { return { label: t('panel.sharedHubUnavailable'), color: Colors.textMuted }; } } // ─── Main Component ──────────────────────────────────── interface FloatPanelViewProps { features: AnyDebugFeature[]; panelOpen: boolean; quickActions?: readonly DebugQuickAction[]; onOpenPanel: () => void; onClosePanel: () => void; onClearAll: () => void; } export function FloatPanelView({ features, panelOpen, quickActions = [], onOpenPanel, onClosePanel, onClearAll }: FloatPanelViewProps) { const [activeTab, setActiveTab] = useState(0); const [filters, dispatchFilters] = useReducer( panelFilterReducer, INITIAL_PANEL_FILTER_STATE, ); const { searchQuery, filterBad, searchExpanded } = filters; const tabLoaded = useRef(false); // Restore last tab on mount useEffect(() => { if (tabLoaded.current || features.length === 0) return; let mounted = true; getPreference(KEYS.lastTab).then((val) => { if (!mounted || tabLoaded.current) return; const idx = resolveStoredTabIndex(features, val); setActiveTab(idx); const featureName = features[idx]?.name; if (featureName && featureName !== val) { void persistPreference(KEYS.lastTab, featureName); } tabLoaded.current = true; }); return () => { mounted = false; }; }, [features]); const { contentOpacity, contentTranslateX, panHandlers, switchTab } = useTabAnimation({ activeTab, tabCount: features.length, onTabChange: useCallback((index: number) => { tabLoaded.current = true; changeTabWithFilterReset(dispatchFilters, setActiveTab, index); const featureName = features[index]?.name; if (featureName) { void persistPreference(KEYS.lastTab, featureName); } }, [features]), }); // Feature subscription → re-render on data changes const [, setTick] = useState(0); const refreshQueued = useRef(false); const scheduleRefresh = useCallback(() => { if (refreshQueued.current) return; refreshQueued.current = true; requestAnimationFrame(() => { refreshQueued.current = false; setTick((tick) => tick + 1); }); }, []); useEffect(() => { const unsubs = features .map((f) => f.subscribe?.(() => scheduleRefresh())) .filter((u): u is () => void => typeof u === 'function'); return () => unsubs.forEach((u) => u()); }, [features, scheduleRefresh]); // Clamp activeTab if features shrink useEffect(() => { if (features.length > 0 && activeTab >= features.length) { tabLoaded.current = true; setActiveTab(0); const featureName = features[0]?.name; if (featureName) { void persistPreference(KEYS.lastTab, featureName); } } }, [features, activeTab]); // Badge (first feature that returns one) const envBadge = features.map((f) => f.badge?.()).find((b) => b != null) ?? null; // Rail items with counts const featureLabel = (feature: AnyDebugFeature): string => { const key = FEATURE_LABEL_KEYS[feature.name]; return key && feature.label === DEFAULT_FEATURE_LABELS[feature.name] ? t(key) : feature.label; }; const railItems: RailItem[] = features.map((f) => { const b = f.badge?.(); return { id: f.name, label: featureLabel(f), dotColor: b?.color ?? null, count: snapshotCount(f) }; }); const panelConnectionStatus = buildPanelConnectionStatus(features); const handleClearAll = useCallback(() => { clearAllWithFilterReset(dispatchFilters, onClearAll); }, [onClearAll]); // Active feature + summary const activeFeature = features[activeTab]; let activeSnapshot: unknown; let snapshotIssue: { path: string; message: string } | undefined; try { activeSnapshot = activeFeature?.getSnapshot(); } catch (error) { snapshotIssue = { path: `${activeFeature?.name}.snapshot`, message: error instanceof Error ? error.message : String(error) }; } const activeSummary = activeFeature && !snapshotIssue ? buildFeatureSummary(activeFeature, activeSnapshot) : null; // Filtered snapshot — reuse activeSnapshot to avoid double getSnapshot() const filteredSnapshot = activeFeature && !snapshotIssue ? filterFeatureSnapshot(activeFeature, activeSnapshot, searchQuery, filterBad ? 'bad' : 'all') : null; // Render active feature content const renderFeatureContent = () => { if (features.length === 0) { return {t('panel.noFeatures')}; } const feature = features[activeTab]; if (!feature) return {t('panel.featureNotFound')}; const snapshot = filteredSnapshot; const TabComponent = feature.renderContent; if (TabComponent) return ; return ( {JSON.stringify(snapshot, null, 2)} ); }; const showSearch = Array.isArray(activeSnapshot) && activeSnapshot.length > 0; return ( {panelOpen && ( {activeFeature && activeSummary && ( dispatchFilters({ type: 'set-bad', bad })} searchQuery={searchQuery} onSearchChange={(query) => dispatchFilters({ type: 'set-query', query })} showSearch={showSearch} searchExpanded={searchExpanded} onSearchExpandedChange={(expanded) => ( dispatchFilters({ type: 'set-search-expanded', expanded }) )} /> )} {activeFeature && {!snapshotIssue && renderFeatureContent()} } )} ); } const styles = StyleSheet.create({ container: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, zIndex: 999, }, body: { flex: 1, flexDirection: 'row', backgroundColor: Colors.background, }, contentColumn: { flex: 1, backgroundColor: Colors.background, }, contentContainer: { flex: 1, backgroundColor: Colors.background, }, emptyText: { padding: Spacing.XL, textAlign: 'center', color: Colors.textMuted, fontSize: FontSize.SM, }, genericContent: { padding: Spacing.LG, flex: 1 }, jsonContent: { fontFamily: 'monospace', fontSize: FontSize.SM, color: Colors.text }, });