import { Check, ChevronDown, Clock, Copy, Edit2, FileCode, FolderPlus, Keyboard, LayoutGrid, List as ListIcon, Loader2, Package, Play, Plus, RotateCcw, Search, Trash2 } from 'lucide-react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useI18n } from '../application/i18n/I18nProvider'; import { useStoredViewMode } from '../application/state/useStoredViewMode'; import { STORAGE_KEY_VAULT_SNIPPETS_VIEW_MODE } from '../infrastructure/config/storageKeys'; import { cn, isMacPlatform } from '../lib/utils'; import { Host, ProxyProfile, ShellHistoryEntry, Snippet, SSHKey } from '../types'; import { HotkeyScheme, KeyBinding, keyEventToString, ManagedSource, matchesKeyBinding, parseKeyCombo } from '../domain/models'; import { DistroAvatar } from './DistroAvatar'; import SelectHostPanel from './SelectHostPanel'; import { AsidePanel, AsidePanelContent, AsidePanelFooter } from './ui/aside-panel'; import { Button } from './ui/button'; import { Card } from './ui/card'; import { Combobox, ComboboxOption } from './ui/combobox'; import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuTrigger } from './ui/context-menu'; import { Dropdown, DropdownContent, DropdownTrigger } from './ui/dropdown'; import { Input } from './ui/input'; import { Label } from './ui/label'; import { SortDropdown, SortMode } from './ui/sort-dropdown'; import { Textarea } from './ui/textarea'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip'; interface SnippetsManagerProps { snippets: Snippet[]; packages: string[]; hosts: Host[]; customGroups?: string[]; shellHistory: ShellHistoryEntry[]; hotkeyScheme: HotkeyScheme; keyBindings: KeyBinding[]; onSave: (snippet: Snippet) => void; onBulkSave: (snippets: Snippet[]) => void; onDelete: (id: string) => void; onPackagesChange: (packages: string[]) => void; onRunSnippet?: (snippet: Snippet, targetHosts: Host[]) => void; // Props for inline host creation availableKeys?: SSHKey[]; proxyProfiles?: ProxyProfile[]; managedSources?: ManagedSource[]; onSaveHost?: (host: Host) => void; onCreateGroup?: (groupPath: string) => void; } type RightPanelMode = 'none' | 'edit-snippet' | 'history' | 'select-targets'; const HISTORY_PAGE_SIZE = 30; const SnippetsManager: React.FC = ({ snippets, packages, hosts, customGroups = [], shellHistory, hotkeyScheme, keyBindings, onSave, onBulkSave, onDelete, onPackagesChange, onRunSnippet, availableKeys = [], proxyProfiles = [], managedSources = [], onSaveHost, onCreateGroup, }) => { const { t } = useI18n(); // Panel state const [rightPanelMode, setRightPanelMode] = useState('none'); const [editingSnippet, setEditingSnippet] = useState>({ label: '', command: '', package: '', targets: [], }); const [targetSelection, setTargetSelection] = useState([]); const [copiedId, setCopiedId] = useState(null); const [selectedPackage, setSelectedPackage] = useState(null); const [newPackageName, setNewPackageName] = useState(''); const [isPackageDialogOpen, setIsPackageDialogOpen] = useState(false); // Rename package state const [isRenameDialogOpen, setIsRenameDialogOpen] = useState(false); const [renamingPackagePath, setRenamingPackagePath] = useState(null); const [renamePackageName, setRenamePackageName] = useState(''); const [renameError, setRenameError] = useState(''); // Search, sort, and view mode state const [search, setSearch] = useState(''); const [viewMode, setViewMode] = useStoredViewMode( STORAGE_KEY_VAULT_SNIPPETS_VIEW_MODE, 'grid', ); const [sortMode, setSortMode] = useState('az'); // Shell history lazy loading state const [historyVisibleCount, setHistoryVisibleCount] = useState(HISTORY_PAGE_SIZE); const historyScrollRef = useRef(null); const [isLoadingMore, setIsLoadingMore] = useState(false); // Shortkey recording state const [isRecordingShortkey, setIsRecordingShortkey] = useState(false); const [shortkeyError, setShortkeyError] = useState(null); const existingShortkeys = useMemo(() => ( snippets.filter(s => Boolean(s.shortkey) && s.id !== editingSnippet.id) ), [snippets, editingSnippet.id]); const isMac = useMemo(() => ( hotkeyScheme === 'mac' || (hotkeyScheme === 'disabled' && isMacPlatform()) ), [hotkeyScheme]); const activeSystemBindings = useMemo(() => { return keyBindings.flatMap((binding) => { const entries: { binding: string; isMac: boolean }[] = []; const macBinding = binding.mac; const pcBinding = binding.pc; if (hotkeyScheme === 'mac') { if (macBinding && macBinding !== 'Disabled') { entries.push({ binding: macBinding, isMac: true }); } return entries; } if (hotkeyScheme === 'pc') { if (pcBinding && pcBinding !== 'Disabled') { entries.push({ binding: pcBinding, isMac: false }); } return entries; } if (macBinding && macBinding !== 'Disabled') { entries.push({ binding: macBinding, isMac: true }); } if (pcBinding && pcBinding !== 'Disabled') { entries.push({ binding: pcBinding, isMac: false }); } return entries; }); }, [hotkeyScheme, keyBindings]); const buildKeyEventFromString = useCallback((keyString: string) => { const parsed = parseKeyCombo(keyString); if (!parsed) return null; const modifiers = new Set(parsed.modifiers); const key = parsed.key; const normalizedKey = (() => { switch (key) { case 'Space': return ' '; case '↑': return 'ArrowUp'; case '↓': return 'ArrowDown'; case '←': return 'ArrowLeft'; case '→': return 'ArrowRight'; case 'Esc': return 'Escape'; case '⌫': return 'Backspace'; case 'Del': return 'Delete'; case '↵': return 'Enter'; case '⇥': return 'Tab'; default: return key.length === 1 ? key.toLowerCase() : key; } })(); return new KeyboardEvent('keydown', { key: normalizedKey, metaKey: modifiers.has('⌘') || modifiers.has('Win'), ctrlKey: modifiers.has('⌃') || modifiers.has('Ctrl'), altKey: modifiers.has('⌥') || modifiers.has('Alt'), shiftKey: modifiers.has('Shift'), }); }, []); // Validate shortkey for conflicts (case-insensitive comparison) const normalizeKeyString = useCallback((value: string) => ( value.toLowerCase().replace(/\s+/g, '') ), []); const validateShortkey = useCallback((key: string): string | null => { if (!key) return null; const syntheticEvent = buildKeyEventFromString(key); if (syntheticEvent) { const conflictsSystem = activeSystemBindings.some(({ binding, isMac: bindingIsMac }) => ( matchesKeyBinding(syntheticEvent, binding, bindingIsMac) )); if (conflictsSystem) { return t('snippets.shortkey.error.systemConflict'); } } // Check other snippet shortcuts if (syntheticEvent) { for (const snippet of existingShortkeys) { if (snippet.shortkey && matchesKeyBinding(syntheticEvent, snippet.shortkey, isMac)) { return t('snippets.shortkey.error.snippetConflict', { name: snippet.label }); } } } else { const normalizedKey = normalizeKeyString(key); const conflictingSnippet = existingShortkeys.find(snippet => ( snippet.shortkey && normalizeKeyString(snippet.shortkey) === normalizedKey )); if (conflictingSnippet) { return t('snippets.shortkey.error.snippetConflict', { name: conflictingSnippet.label }); } } return null; }, [ activeSystemBindings, buildKeyEventFromString, existingShortkeys, isMac, normalizeKeyString, t, ]); // Handle shortkey recording useEffect(() => { if (!isRecordingShortkey) return; const handleKeyDown = (e: KeyboardEvent) => { e.preventDefault(); e.stopPropagation(); // Escape cancels recording if (e.key === 'Escape') { setIsRecordingShortkey(false); setShortkeyError(null); return; } // Skip pure modifier keys if (['Meta', 'Control', 'Alt', 'Shift'].includes(e.key)) return; const keyString = keyEventToString(e, isMac); // Validate the new shortkey const error = validateShortkey(keyString); if (error) { setShortkeyError(error); // Don't stop recording, let user try again return; } setShortkeyError(null); setEditingSnippet(prev => ({ ...prev, shortkey: keyString })); setIsRecordingShortkey(false); }; const handleClick = () => { setIsRecordingShortkey(false); setShortkeyError(null); }; // Delay adding click handler by 100ms to prevent the button click that // initiated recording from immediately triggering the click handler const timer = setTimeout(() => { window.addEventListener('click', handleClick, true); }, 100); window.addEventListener('keydown', handleKeyDown, true); return () => { clearTimeout(timer); window.removeEventListener('keydown', handleKeyDown, true); window.removeEventListener('click', handleClick, true); }; }, [isRecordingShortkey, isMac, validateShortkey]); const handleEdit = (snippet?: Snippet) => { if (snippet) { setEditingSnippet(snippet); setTargetSelection(snippet.targets || []); } else { setEditingSnippet({ label: '', command: '', package: selectedPackage || '', targets: [] }); setTargetSelection([]); } setRightPanelMode('edit-snippet'); }; const handleSubmit = () => { if (editingSnippet.label && editingSnippet.command) { onSave({ id: editingSnippet.id || crypto.randomUUID(), label: editingSnippet.label, command: editingSnippet.command, tags: editingSnippet.tags || [], package: editingSnippet.package || '', targets: targetSelection, shortkey: editingSnippet.shortkey, noAutoRun: editingSnippet.noAutoRun, }); setRightPanelMode('none'); } }; const handleCopy = (id: string, text: string) => { navigator.clipboard.writeText(text); setCopiedId(id); setTimeout(() => setCopiedId(null), 1500); }; const handleClosePanel = () => { setRightPanelMode('none'); setEditingSnippet({ label: '', command: '', package: '', targets: [] }); setTargetSelection([]); }; const targetHosts = useMemo(() => { return targetSelection .map((id) => hosts.find((h) => h.id === id)) .filter((h): h is Host => Boolean(h)); }, [targetSelection, hosts]); const openTargetPicker = () => { setRightPanelMode('select-targets'); }; const handleTargetSelect = (host: Host) => { setTargetSelection((prev) => prev.includes(host.id) ? prev.filter((id) => id !== host.id) : [...prev, host.id] ); }; const handleTargetPickerBack = () => { setRightPanelMode('edit-snippet'); }; const displayedPackages = useMemo(() => { if (!selectedPackage) { // Separate absolute paths (starting with /) from relative paths const absolutePaths = packages.filter(p => p.startsWith('/')); const relativePaths = packages.filter(p => !p.startsWith('/')); const results: { name: string; path: string; count: number }[] = []; // Process relative paths (traditional behavior) const relativeRoots = relativePaths .map((p) => p.split('/')[0]) .filter((name): name is string => Boolean(name) && name.length > 0); Array.from(new Set(relativeRoots)).forEach((name: string) => { const path: string = name; const count = snippets.filter((s) => { const pkg = s.package || ''; return pkg === path || pkg.startsWith(path + '/'); }).length; results.push({ name, path, count }); }); // Process absolute paths - show them as separate roots with "/" prefix const absoluteRoots = absolutePaths .map((p) => { const cleanPath = p.substring(1); // Remove leading slash const firstSegment = cleanPath.split('/')[0]; return firstSegment; }) .filter((name): name is string => Boolean(name) && name.length > 0); Array.from(new Set(absoluteRoots)).forEach((name: string) => { const path: string = `/${name}`; const displayName: string = `/${name}`; // Show with leading slash to distinguish const count = snippets.filter((s) => { const pkg = s.package || ''; return pkg === path || pkg.startsWith(path + '/'); }).length; results.push({ name: displayName, path, count }); }); return results; } const prefix = selectedPackage + '/'; const children = packages .filter((p) => p.startsWith(prefix)) .map((p) => p.replace(prefix, '').split('/')[0]) .filter((name): name is string => Boolean(name) && name.length > 0); return Array.from(new Set(children)).map((name) => { const path = `${selectedPackage}/${name}`; // Count snippets in this package AND all nested packages const count = snippets.filter((s) => { const pkg = s.package || ''; return pkg === path || pkg.startsWith(path + '/'); }).length; return { name, path, count }; }); }, [packages, selectedPackage, snippets]); const displayedSnippets = useMemo(() => { // Search spans all packages (#777): when the user types in the search // box we drop the current-package scoping so cross-package matches are // reachable without navigating into each one. Otherwise the user is // browsing and we keep the package scope. const hasSearch = search.trim().length > 0; let result = hasSearch ? snippets : snippets.filter((s) => (s.package || '') === (selectedPackage || '')); if (hasSearch) { const s = search.toLowerCase(); result = result.filter(sn => sn.label.toLowerCase().includes(s) || sn.command.toLowerCase().includes(s) ); } // Apply sorting result = [...result].sort((a, b) => { switch (sortMode) { case 'az': return a.label.localeCompare(b.label); case 'za': return b.label.localeCompare(a.label); default: return 0; } }); return result; }, [snippets, selectedPackage, search, sortMode]); const breadcrumb = useMemo(() => { if (!selectedPackage) return []; const isAbsolute = selectedPackage.startsWith('/'); const parts = selectedPackage.split('/').filter(Boolean); return parts.map((name, idx) => { const pathSegments = parts.slice(0, idx + 1); const path = isAbsolute ? `/${pathSegments.join('/')}` : pathSegments.join('/'); return { name, path }; }); }, [selectedPackage]); const createPackage = () => { const name = newPackageName.trim(); if (!name) return; // Allow leading slash and validate the rest - allow hyphens and Unicode letters/numbers if (!/^\/?([\w\p{L}\p{N}-]+(\/[\w\p{L}\p{N}-]+)*)\/?$/u.test(name)) { // Could add toast notification here for invalid characters return; } // Normalize path construction to avoid double slashes let full: string; if (selectedPackage) { // Strip leading slash from name when we're inside a package to avoid double slashes const normalizedName = name.startsWith('/') ? name.substring(1) : name; full = `${selectedPackage}/${normalizedName}`; } else { // At root level, preserve the leading slash if user intended it full = name; } // Strip trailing slash to ensure consistent path handling if (full.endsWith('/')) { full = full.slice(0, -1); } // Check for duplicate package names (case-insensitive) const existingPackage = packages.find(p => p.toLowerCase() === full.toLowerCase()); if (existingPackage) { // Could add toast notification here for duplicate package return; } onPackagesChange([...packages, full]); setNewPackageName(''); setIsPackageDialogOpen(false); }; const deletePackage = (path: string) => { // Remove the package and all its children const keep = packages.filter((p) => !(p === path || p.startsWith(path + '/'))); // Move all snippets from deleted packages to root const updatedSnippets = snippets.map((s) => { if (!s.package) return s; if (s.package === path || s.package.startsWith(path + '/')) { return { ...s, package: '' }; } return s; }); // Update packages first, then save snippets onPackagesChange(keep); // Bulk-save all snippets to avoid stale-closure overwrites onBulkSave(updatedSnippets); // Reset selected package if it was deleted if (selectedPackage && (selectedPackage === path || selectedPackage.startsWith(path + '/'))) { setSelectedPackage(null); } }; const movePackage = (source: string, target: string | null) => { const name = source.split('/').pop() || ''; const isAbsolute = source.startsWith('/'); const newPath = target ? `${target}/${name}` : (isAbsolute ? `/${name}` : name); if (newPath === source || newPath.startsWith(source + '/')) return; // Check if target path already exists if (packages.includes(newPath)) return; const updatedPackages = packages.map((p) => { if (p === source) return newPath; // Use more precise replacement to avoid substring issues if (p.startsWith(source + '/')) { return newPath + p.substring(source.length); } return p; }); const updatedSnippets = snippets.map((s) => { if (!s.package) return s; if (s.package === source) return { ...s, package: newPath }; // Use more precise replacement to avoid substring issues if (s.package.startsWith(source + '/')) { return { ...s, package: newPath + s.package.substring(source.length) }; } return s; }); onPackagesChange(Array.from(new Set(updatedPackages))); onBulkSave(updatedSnippets); if (selectedPackage === source) setSelectedPackage(newPath); }; const openRenameDialog = (path: string) => { const name = path.split('/').pop() || ''; setRenamingPackagePath(path); setRenamePackageName(name); setRenameError(''); setIsRenameDialogOpen(true); }; const renamePackage = () => { if (!renamingPackagePath) return; const newName = renamePackageName.trim(); // Validate: empty name if (!newName) { setRenameError(t('snippets.renameDialog.error.empty')); return; } // Validate: same rules as createPackage - allow Unicode letters, numbers, hyphens, underscores // Since we're renaming a single segment (no slashes allowed), use the segment-level pattern if (!/^[\w\p{L}\p{N}-]+$/u.test(newName)) { setRenameError(t('snippets.renameDialog.error.invalidChars')); return; } // Build new path const parts = renamingPackagePath.split('/'); parts[parts.length - 1] = newName; const newPath = parts.join('/'); // Validate: same name if (newPath === renamingPackagePath) { setIsRenameDialogOpen(false); return; } // Validate: duplicate (case-insensitive), excluding the package being renamed const existingPackage = packages.find(p => p !== renamingPackagePath && p.toLowerCase() === newPath.toLowerCase()); if (existingPackage) { setRenameError(t('snippets.renameDialog.error.duplicate')); return; } // Update all packages with this path or nested under it const updatedPackages = packages.map((p) => { if (p === renamingPackagePath) return newPath; if (p.startsWith(renamingPackagePath + '/')) { return newPath + p.substring(renamingPackagePath.length); } return p; }); // Update all snippets with this package or nested under it const updatedSnippets = snippets.map((s) => { if (!s.package) return s; if (s.package === renamingPackagePath) return { ...s, package: newPath }; if (s.package.startsWith(renamingPackagePath + '/')) { return { ...s, package: newPath + s.package.substring(renamingPackagePath.length) }; } return s; }); onPackagesChange(Array.from(new Set(updatedPackages))); onBulkSave(updatedSnippets); // Update selected package if it was renamed if (selectedPackage === renamingPackagePath) { setSelectedPackage(newPath); } else if (selectedPackage?.startsWith(renamingPackagePath + '/')) { setSelectedPackage(newPath + selectedPackage.substring(renamingPackagePath.length)); } // Update editingSnippet.package if it's in the renamed package (fixes stale state when editing) if (editingSnippet.package) { if (editingSnippet.package === renamingPackagePath) { setEditingSnippet(prev => ({ ...prev, package: newPath })); } else if (editingSnippet.package.startsWith(renamingPackagePath + '/')) { setEditingSnippet(prev => ({ ...prev, package: newPath + prev.package!.substring(renamingPackagePath.length) })); } } setIsRenameDialogOpen(false); }; const moveSnippet = (id: string, pkg: string | null) => { const sn = snippets.find((s) => s.id === id); if (!sn) return; onSave({ ...sn, package: pkg || '' }); }; // Package options for Combobox const packageOptions: ComboboxOption[] = useMemo(() => { // Generate all possible parent paths for each package const allPaths = new Set(); packages.forEach(pkg => { // Add the full package path allPaths.add(pkg); // Add all parent paths const parts = pkg.split('/').filter(Boolean); const isAbsolute = pkg.startsWith('/'); for (let i = 1; i < parts.length; i++) { const parentPath = (isAbsolute ? '/' : '') + parts.slice(0, i).join('/'); allPaths.add(parentPath); } }); return Array.from(allPaths) .sort((a, b) => { // Sort by depth first (shorter paths first), then alphabetically const depthA = (a.match(/\//g) || []).length; const depthB = (b.match(/\//g) || []).length; if (depthA !== depthB) return depthA - depthB; return a.localeCompare(b); }) .map(p => ({ value: p, label: p.includes('/') ? p.split('/').pop()! : p, sublabel: p.includes('/') ? p : undefined, })); }, [packages]); // Shell history lazy loading const visibleHistory = useMemo(() => { return shellHistory.slice(0, historyVisibleCount); }, [shellHistory, historyVisibleCount]); const hasMoreHistory = historyVisibleCount < shellHistory.length; const loadMoreHistory = useCallback(() => { if (isLoadingMore || !hasMoreHistory) return; setIsLoadingMore(true); // Simulate loading delay for smooth UX setTimeout(() => { setHistoryVisibleCount((prev) => Math.min(prev + HISTORY_PAGE_SIZE, shellHistory.length)); setIsLoadingMore(false); }, 200); }, [isLoadingMore, hasMoreHistory, shellHistory.length]); // Scroll handler for lazy loading const handleHistoryScroll = useCallback((e: React.UIEvent) => { const target = e.target as HTMLDivElement; const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight; if (scrollBottom < 100 && hasMoreHistory && !isLoadingMore) { loadMoreHistory(); } }, [hasMoreHistory, isLoadingMore, loadMoreHistory]); // Reset visible count when history panel opens useEffect(() => { if (rightPanelMode === 'history') { setHistoryVisibleCount(HISTORY_PAGE_SIZE); } }, [rightPanelMode]); const saveHistoryAsSnippet = (entry: ShellHistoryEntry, label: string) => { if (!label.trim()) return; onSave({ id: crypto.randomUUID(), label: label.trim(), command: entry.command, package: selectedPackage || '', targets: [], }); }; // Render right panel based on mode const renderRightPanel = () => { if (rightPanelMode === 'select-targets') { return ( ); } if (rightPanelMode === 'edit-snippet') { return ( {editingSnippet.id && ( {t('common.delete')} )} } > {/* Action Description */}

{t('snippets.field.description')}

setEditingSnippet({ ...editingSnippet, label: e.target.value })} className="h-10" />
{/* Package */}

{t('snippets.field.package')}

{ setEditingSnippet({ ...editingSnippet, package: val }); // If selecting an implicit parent path, persist it to packages if (val && !packages.includes(val)) { onPackagesChange([...packages, val]); } }} placeholder={t('snippets.field.packagePlaceholder')} allowCreate={true} onCreateNew={(val) => { if (!packages.includes(val)) { onPackagesChange([...packages, val]); } }} createText={t('snippets.field.createPackage')} icon={} triggerClassName="h-10" />
{/* Script */}

{t('snippets.field.scriptRequired')}