From a47f9ddc8c3041deff00aaae8bdde63ee191042f Mon Sep 17 00:00:00 2001 From: "LAPTOP-O016UC3M\\Qi Chen" <16399091+binaricat@users.noreply.github.com> Date: Tue, 9 Dec 2025 22:41:43 +0800 Subject: [PATCH] Improves performance and memoization of known hosts UI Optimizes rendering of known hosts management by introducing memoization and limiting rendered items for large datasets. Refactors callback and state management in several components to reduce unnecessary re-renders and improve responsiveness. Enhances code structure for maintainability and future scalability, and adds debug logs to aid profiling and diagnostics. --- App.tsx | 70 ++-- application/state/activeTabStore.ts | 9 +- application/state/useVaultState.ts | 27 +- components/KnownHostsManager.tsx | 571 +++++++++++++++------------- components/VaultView.tsx | 110 ++++-- 5 files changed, 453 insertions(+), 334 deletions(-) diff --git a/App.tsx b/App.tsx index 696622b71..26a48ca7e 100755 --- a/App.tsx +++ b/App.tsx @@ -14,9 +14,27 @@ import { Label } from './components/ui/label'; import { useSettingsState } from './application/state/useSettingsState'; import { useVaultState } from './application/state/useVaultState'; import { useSessionState } from './application/state/useSessionState'; +import { useIsVaultActive } from './application/state/activeTabStore'; import { ToastProvider } from './components/ui/toast'; +import { cn } from './lib/utils'; + +// Visibility container for VaultView - isolates isActive subscription +const VaultViewContainer: React.FC<{ children: React.ReactNode }> = ({ children }) => { + const isActive = useIsVaultActive(); + const containerStyle: React.CSSProperties = isActive + ? {} + : { visibility: 'hidden', pointerEvents: 'none', position: 'absolute', zIndex: -1 }; + + return ( +
+ {children} +
+ ); +}; function App() { + console.log('[App] render'); + const [isFormOpen, setIsFormOpen] = useState(false); const [isSettingsOpen, setIsSettingsOpen] = useState(false); const [isQuickSwitcherOpen, setIsQuickSwitcherOpen] = useState(false); @@ -163,31 +181,33 @@ function App() { />
- + + + diff --git a/application/state/activeTabStore.ts b/application/state/activeTabStore.ts index 444c6f675..b7fb94565 100644 --- a/application/state/activeTabStore.ts +++ b/application/state/activeTabStore.ts @@ -11,6 +11,7 @@ class ActiveTabStore { setActiveTabId = (id: string) => { if (this.activeTabId !== id) { + console.log('[ActiveTabStore] setActiveTabId:', id, 'listeners:', this.listeners.size); this.activeTabId = id; this.listeners.forEach(listener => listener()); } @@ -43,11 +44,15 @@ export const useIsTabActive = (tabId: string) => { return useSyncExternalStore(activeTabStore.subscribe, getSnapshot); }; +// Stable snapshot functions - defined once outside components +const getIsVaultActive = () => activeTabStore.getActiveTabId() === 'vault'; +const getIsSftpActive = () => activeTabStore.getActiveTabId() === 'sftp'; + // Check if vault is active export const useIsVaultActive = () => { return useSyncExternalStore( activeTabStore.subscribe, - () => activeTabStore.getActiveTabId() === 'vault' + getIsVaultActive ); }; @@ -55,7 +60,7 @@ export const useIsVaultActive = () => { export const useIsSftpActive = () => { return useSyncExternalStore( activeTabStore.subscribe, - () => activeTabStore.getActiveTabId() === 'sftp' + getIsSftpActive ); }; diff --git a/application/state/useVaultState.ts b/application/state/useVaultState.ts index 4ff3b4188..44caf09c0 100644 --- a/application/state/useVaultState.ts +++ b/application/state/useVaultState.ts @@ -92,19 +92,26 @@ export const useVaultState = () => { protocol: 'ssh', }; - // Update the known host to mark it as converted - const updatedKnownHosts = knownHosts.map(kh => - kh.id === knownHost.id - ? { ...kh, convertedToHostId: newHost.id } - : kh - ); - updateKnownHosts(updatedKnownHosts); + // Update the known host to mark it as converted using functional update + setKnownHosts(prevKnownHosts => { + const updated = prevKnownHosts.map(kh => + kh.id === knownHost.id + ? { ...kh, convertedToHostId: newHost.id } + : kh + ); + localStorageAdapter.write(STORAGE_KEY_KNOWN_HOSTS, updated); + return updated; + }); - // Add to hosts - updateHosts([...hosts, newHost]); + // Add to hosts using functional update + setHosts(prevHosts => { + const updated = [...prevHosts, sanitizeHost(newHost)]; + localStorageAdapter.write(STORAGE_KEY_HOSTS, updated); + return updated; + }); return newHost; - }, [hosts, knownHosts, updateHosts]); + }, []); useEffect(() => { const savedHosts = localStorageAdapter.read(STORAGE_KEY_HOSTS); diff --git a/components/KnownHostsManager.tsx b/components/KnownHostsManager.tsx index 12c96c8bc..2822e3a83 100644 --- a/components/KnownHostsManager.tsx +++ b/components/KnownHostsManager.tsx @@ -1,17 +1,14 @@ -import React, { useState, useMemo, useEffect, useCallback } from 'react'; +import React, { useState, useMemo, useEffect, useCallback, memo, useDeferredValue } from 'react'; import { Search, Import, Trash2, - MoreVertical, Server, Key, Clock, ArrowRight, - FileText, RefreshCw, Shield, - ExternalLink, FolderOpen, LayoutGrid, List, @@ -25,12 +22,6 @@ import { Button } from './ui/button'; import { Input } from './ui/input'; import { ScrollArea } from './ui/scroll-area'; import { cn } from '../lib/utils'; -import { - ContextMenu, - ContextMenuContent, - ContextMenuItem, - ContextMenuTrigger, -} from './ui/context-menu'; import { Popover, PopoverContent, @@ -83,6 +74,49 @@ const getKeyTypeColorFn = (keyType: string) => { } }; +// Parse known_hosts file content - pure function, moved outside component +const parseKnownHostsFile = (content: string): KnownHost[] => { + const lines = content.split('\n').filter((line) => line.trim() && !line.startsWith('#')); + const parsed: KnownHost[] = []; + + for (const line of lines) { + try { + const parts = line.trim().split(/\s+/); + if (parts.length < 3) continue; + + const [hostPattern, keyType, publicKey] = parts; + + let hostname = hostPattern; + let port = 22; + + const bracketMatch = hostPattern.match(/^\[([^\]]+)\]:(\d+)$/); + if (bracketMatch) { + hostname = bracketMatch[1]; + port = parseInt(bracketMatch[2], 10); + } else if (hostPattern.includes(',')) { + hostname = hostPattern.split(',')[0]; + } + + if (hostname.startsWith('|1|')) { + hostname = '(hashed)'; + } + + parsed.push({ + id: `kh-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + hostname, + port, + keyType, + publicKey: publicKey.slice(0, 64) + '...', + discoveredAt: Date.now(), + }); + } catch (e) { + console.warn('Failed to parse known_hosts line:', line); + } + } + + return parsed; +}; + // Memoized Grid Item Component interface HostItemProps { knownHost: KnownHost; @@ -93,165 +127,172 @@ interface HostItemProps { } const HostItem = React.memo(({ knownHost, converted, viewMode, onDelete, onConvertToHost }) => { + // Disabled to reduce log noise - uncomment for debugging + // console.log('[HostItem] render:', knownHost.hostname); if (viewMode === 'grid') { return ( - - -
-
- -
-
-
- - {knownHost.hostname} - - {knownHost.port !== 22 && ( - - :{knownHost.port} - - )} -
-
- - - {knownHost.keyType} - - - - {formatDateFn(knownHost.discoveredAt)} - -
-
-
-
- +
+ {/* Quick action buttons on hover */} +
{!converted && ( - onConvertToHost(knownHost)}> - - Convert to Managed Host - + )} - {converted && ( - - - Already Managed - - )} - onDelete(knownHost.id)} + +
+
+ +
+
+
+ + {knownHost.hostname} + + {knownHost.port !== 22 && ( + + :{knownHost.port} + + )} +
+
+ + + {knownHost.keyType} + + + + {formatDateFn(knownHost.discoveredAt)} + +
+
+
); } // List view return ( - - -
+
+ +
+
+
+ + {knownHost.hostname} + + {knownHost.port !== 22 && ( + + :{knownHost.port} + + )} + {converted && ( + + Managed + )} - > -
- -
-
-
- - {knownHost.hostname} - - {knownHost.port !== 22 && ( - - :{knownHost.port} - - )} - {converted && ( - - Managed - - )} -
-
- - - {knownHost.keyType} - - - - {formatDateFn(knownHost.discoveredAt)} - -
-
-
- {!converted && ( - - )} - -
- - +
+ + + {knownHost.keyType} + + + + {formatDateFn(knownHost.discoveredAt)} + +
+
+
{!converted && ( - onConvertToHost(knownHost)}> - - Convert to Managed Host - + )} - {converted && ( - - - Already Managed - - )} - onDelete(knownHost.id)} + +
+
); }); HostItem.displayName = 'HostItem'; +// Memoized Import Preview Item +interface ImportPreviewItemProps { + host: KnownHost; + selected: boolean; + onToggle: (id: string, checked: boolean) => void; +} + +const ImportPreviewItem = React.memo(({ host, selected, onToggle }) => { + const handleChange = useCallback((e: React.ChangeEvent) => { + onToggle(host.id, e.target.checked); + }, [host.id, onToggle]); + + return ( + + ); +}); + +ImportPreviewItem.displayName = 'ImportPreviewItem'; + const KnownHostsManager: React.FC = ({ knownHosts, hosts, @@ -262,8 +303,13 @@ const KnownHostsManager: React.FC = ({ onImportFromFile, onRefresh, }) => { + // Debug: track renders + const renderCountRef = React.useRef(0); + renderCountRef.current++; + console.log(`[KnownHostsManager] render #${renderCountRef.current} - knownHosts: ${knownHosts.length}, hosts: ${hosts.length}`); + const [search, setSearch] = useState(''); - const [deferredSearch, setDeferredSearch] = useState(''); + const deferredSearch = useDeferredValue(search); const [isImportDialogOpen, setIsImportDialogOpen] = useState(false); const [importPreview, setImportPreview] = useState([]); const [selectedIds, setSelectedIds] = useState>(new Set()); @@ -274,23 +320,20 @@ const KnownHostsManager: React.FC = ({ const [sortPopoverOpen, setSortPopoverOpen] = useState(false); const fileInputRef = React.useRef(null); const hasScannedRef = React.useRef(false); + const RENDER_LIMIT = 100; // Limit rendered items for performance // Auto-scan on first mount useEffect(() => { if (!hasScannedRef.current) { hasScannedRef.current = true; - handleScanSystem(); + // Delay scan slightly to not block initial render + const timer = setTimeout(() => { + handleScanSystem(); + }, 100); + return () => clearTimeout(timer); } }, []); - // Debounced search for performance - useEffect(() => { - const timer = setTimeout(() => { - setDeferredSearch(search); - }, 150); - return () => clearTimeout(timer); - }, [search]); - // Sort and filter hosts const filteredHosts = useMemo(() => { let result = knownHosts; @@ -324,56 +367,14 @@ const KnownHostsManager: React.FC = ({ return result; }, [knownHosts, deferredSearch, sortBy]); - // Parse known_hosts file content - const parseKnownHostsFile = (content: string): KnownHost[] => { - const lines = content.split('\n').filter((line) => line.trim() && !line.startsWith('#')); - const parsed: KnownHost[] = []; + // Limit rendered items for performance + const displayedHosts = useMemo(() => { + return filteredHosts.slice(0, RENDER_LIMIT); + }, [filteredHosts]); - for (const line of lines) { - try { - // Format: hostname[,hostname2,...] keytype base64key [comment] - // Or hashed: |1|salt|hash keytype base64key [comment] - const parts = line.trim().split(/\s+/); - if (parts.length < 3) continue; + const hasMore = filteredHosts.length > RENDER_LIMIT; - const [hostPattern, keyType, publicKey] = parts; - - // Extract hostname and port - let hostname = hostPattern; - let port = 22; - - // Handle [hostname]:port format - const bracketMatch = hostPattern.match(/^\[([^\]]+)\]:(\d+)$/); - if (bracketMatch) { - hostname = bracketMatch[1]; - port = parseInt(bracketMatch[2], 10); - } else if (hostPattern.includes(',')) { - // Multiple hostnames, take the first one - hostname = hostPattern.split(',')[0]; - } - - // Skip hashed entries for now (start with |1|) - if (hostname.startsWith('|1|')) { - hostname = '(hashed)'; - } - - parsed.push({ - id: `kh-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, - hostname, - port, - keyType, - publicKey: publicKey.slice(0, 64) + '...', // Truncate for display - discoveredAt: Date.now(), - }); - } catch (e) { - console.warn('Failed to parse known_hosts line:', line); - } - } - - return parsed; - }; - - const handleFileSelect = (e: React.ChangeEvent) => { + const handleFileSelect = useCallback((e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; @@ -396,17 +397,17 @@ const KnownHostsManager: React.FC = ({ if (fileInputRef.current) { fileInputRef.current.value = ''; } - }; + }, [knownHosts]); - const handleImportConfirm = () => { + const handleImportConfirm = useCallback(() => { const toImport = importPreview.filter((h) => selectedIds.has(h.id)); onImportFromFile(toImport); setIsImportDialogOpen(false); setImportPreview([]); setSelectedIds(new Set()); - }; + }, [importPreview, selectedIds, onImportFromFile]); - const handleScanSystem = async () => { + const handleScanSystem = useCallback(async () => { setIsScanning(true); // Try to read from common known_hosts locations via Electron if (window.nebula?.readKnownHosts) { @@ -429,18 +430,23 @@ const KnownHostsManager: React.FC = ({ } onRefresh(); setIsScanning(false); - }; + }, [knownHosts, onRefresh]); // Memoize host lookup for performance const hostIdSet = useMemo(() => new Set(hosts.map(h => h.id)), [hosts]); - // Check if a known host has been converted to a managed host - const isConverted = useCallback((knownHost: KnownHost) => { - if (knownHost.convertedToHostId) { - return hostIdSet.has(knownHost.convertedToHostId); + // Pre-compute converted status for all known hosts + const convertedMap = useMemo(() => { + const map = new Map(); + for (const kh of knownHosts) { + if (kh.convertedToHostId) { + map.set(kh.id, hostIdSet.has(kh.convertedToHostId)); + } else { + map.set(kh.id, false); + } } - return false; - }, [hostIdSet]); + return map; + }, [knownHosts, hostIdSet]); // Memoized handlers to prevent re-renders const handleDelete = useCallback((id: string) => { @@ -451,6 +457,47 @@ const KnownHostsManager: React.FC = ({ onConvertToHost(knownHost); }, [onConvertToHost]); + // View/Sort handlers + const setGridView = useCallback(() => { setViewMode('grid'); setViewPopoverOpen(false); }, []); + const setListView = useCallback(() => { setViewMode('list'); setViewPopoverOpen(false); }, []); + const setSortNameAsc = useCallback(() => { setSortBy('name-asc'); setSortPopoverOpen(false); }, []); + const setSortNameDesc = useCallback(() => { setSortBy('name-desc'); setSortPopoverOpen(false); }, []); + const setSortNewest = useCallback(() => { setSortBy('newest'); setSortPopoverOpen(false); }, []); + const setSortOldest = useCallback(() => { setSortBy('oldest'); setSortPopoverOpen(false); }, []); + const openFilePicker = useCallback(() => fileInputRef.current?.click(), []); + + // Import dialog handler + const handleToggleSelected = useCallback((id: string, checked: boolean) => { + setSelectedIds(prev => { + const next = new Set(prev); + if (checked) { + next.add(id); + } else { + next.delete(id); + } + return next; + }); + }, []); + + const closeImportDialog = useCallback(() => setIsImportDialogOpen(false), []); + + // Memoize the rendered list to prevent re-renders + const renderedItems = useMemo(() => { + console.log('[KnownHostsManager] renderedItems useMemo recalculated - displayedHosts:', displayedHosts.length); + return displayedHosts.map((knownHost) => ( + + )); + }, [displayedHosts, convertedMap, viewMode, handleDelete, handleConvertToHost]); + + console.log('[KnownHostsManager] about to return JSX'); + return (
{/* Header */} @@ -480,7 +527,7 @@ const KnownHostsManager: React.FC = ({ "w-full flex items-center gap-2 px-3 py-2 text-sm rounded-md hover:bg-secondary transition-colors", viewMode === 'grid' && "bg-secondary" )} - onClick={() => { setViewMode('grid'); setViewPopoverOpen(false); }} + onClick={setGridView} > Grid @@ -491,7 +538,7 @@ const KnownHostsManager: React.FC = ({ "w-full flex items-center gap-2 px-3 py-2 text-sm rounded-md hover:bg-secondary transition-colors", viewMode === 'list' && "bg-secondary" )} - onClick={() => { setViewMode('list'); setViewPopoverOpen(false); }} + onClick={setListView} > List @@ -513,7 +560,7 @@ const KnownHostsManager: React.FC = ({ "w-full flex items-center gap-2 px-3 py-2 text-sm rounded-md hover:bg-secondary transition-colors", sortBy === 'name-asc' && "bg-secondary" )} - onClick={() => { setSortBy('name-asc'); setSortPopoverOpen(false); }} + onClick={setSortNameAsc} > A-z @@ -524,7 +571,7 @@ const KnownHostsManager: React.FC = ({ "w-full flex items-center gap-2 px-3 py-2 text-sm rounded-md hover:bg-secondary transition-colors", sortBy === 'name-desc' && "bg-secondary" )} - onClick={() => { setSortBy('name-desc'); setSortPopoverOpen(false); }} + onClick={setSortNameDesc} > Z-a @@ -536,7 +583,7 @@ const KnownHostsManager: React.FC = ({ "w-full flex items-center gap-2 px-3 py-2 text-sm rounded-md hover:bg-secondary transition-colors whitespace-nowrap", sortBy === 'newest' && "bg-secondary" )} - onClick={() => { setSortBy('newest'); setSortPopoverOpen(false); }} + onClick={setSortNewest} > Newest to oldest @@ -547,7 +594,7 @@ const KnownHostsManager: React.FC = ({ "w-full flex items-center gap-2 px-3 py-2 text-sm rounded-md hover:bg-secondary transition-colors whitespace-nowrap", sortBy === 'oldest' && "bg-secondary" )} - onClick={() => { setSortBy('oldest'); setSortPopoverOpen(false); }} + onClick={setSortOldest} > Oldest to newest @@ -579,7 +626,7 @@ const KnownHostsManager: React.FC = ({ variant="secondary" size="sm" className="h-9 px-3 text-xs" - onClick={() => fileInputRef.current?.click()} + onClick={openFilePicker} > Import File @@ -593,7 +640,7 @@ const KnownHostsManager: React.FC = ({ "p-4", viewMode === 'grid' ? "grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 gap-3" : "space-y-2" )}> - {filteredHosts.length === 0 ? ( + {displayedHosts.length === 0 ? (
= ({ Scan System -
) : ( - filteredHosts.map((knownHost) => ( - - )) + <> + {renderedItems} + {hasMore && ( +
+ Showing {RENDER_LIMIT} of {filteredHosts.length} hosts. Use search to find specific hosts. +
+ )} + )}
@@ -643,44 +691,17 @@ const KnownHostsManager: React.FC = ({
{importPreview.map((host) => ( - + host={host} + selected={selectedIds.has(host.id)} + onToggle={handleToggleSelected} + /> ))}
-