import { useState, useCallback } from 'react'; import { Zap, Copy, Check, RefreshCw, EllipsisVertical, CloudOff, ExternalLink, ChevronDown, ArrowDown, ArrowUp, LoaderCircle, History, Edit } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; import { useQueryClient } from '@tanstack/react-query'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'; import { ExternalFavicon } from '@/components/ExternalFavicon'; import { SyncStepError } from './SyncStepError'; import { ForcePullDialog } from './ForcePullDialog'; import { ForcePushDialog } from './ForcePushDialog'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; import { NostrRepoEditDialog } from '@/components/NostrRepoEditDialog'; import { useGitStatus } from '@/hooks/useGitStatus'; import { useGitSettings } from '@/hooks/useGitSettings'; import { useGit } from '@/hooks/useGit'; import { useFSPaths } from '@/hooks/useFSPaths'; import { useAppContext } from '@/hooks/useAppContext'; import { useGitSyncState } from '@/hooks/useGitSyncState'; import { useGitAutosync } from '@/hooks/useGitAutosync'; import type { SyncStepProps } from '../types'; import { cn } from '@/lib/utils'; import { NostrURI } from '@/lib/NostrURI'; import { ngitWebUrl } from '@/lib/ngitWebUrl'; import { findCredentialsForRepo } from '@/lib/gitCredentials'; export function SyncStep({ projectId, remoteUrl }: SyncStepProps) { const queryClient = useQueryClient(); const [copiedUrl, setCopiedUrl] = useState(false); const [syncSuccess, setSyncSuccess] = useState(false); const [isExpanded, setIsExpanded] = useState(false); const [showForcePullDialog, setShowForcePullDialog] = useState(false); const [showForcePushDialog, setShowForcePushDialog] = useState(false); const [gitHistoryOpen, setGitHistoryOpen] = useState(false); const [editRepoOpen, setEditRepoOpen] = useState(false); const [repoIdentifier, setRepoIdentifier] = useState(null); const { data: gitStatus } = useGitStatus(projectId); const { settings } = useGitSettings(); const { git } = useGit(); const { projectsPath } = useFSPaths(); const { config } = useAppContext(); const gitSync = useGitSyncState(); const dir = `${projectsPath}/${projectId}`; const ref = gitStatus?.currentBranch || 'main'; // Use the new hook for autosync state const { autosync, isLoading: isLoadingAutosync, setAutosync } = useGitAutosync(dir); // Get unified sync state and error const syncState = gitSync.getState(dir); const isSyncing = syncState?.isActive || false; const currentOperation = syncState?.operation || null; const error = gitSync.getError(dir) || null; const hasRemoteChanges = gitStatus?.remoteBranchExists && ((gitStatus?.ahead ?? 0) > 0 || (gitStatus?.behind ?? 0) > 0); const commitsAhead = gitStatus?.ahead ?? 0; const commitsBehind = gitStatus?.behind ?? 0; // Helper to set error for this directory const setError = useCallback((err: Error | null) => { gitSync.setError(dir, err); }, [dir, gitSync]); // Generic git operation handler with success feedback const executeGitOperation = useCallback(async ( action: () => Promise ) => { if (!remoteUrl) return; setError(null); setSyncSuccess(false); try { await action(); // Show success feedback setSyncSuccess(true); setTimeout(() => setSyncSuccess(false), 2500); } catch (err) { console.warn(err); // Error is already set by the provider } }, [remoteUrl, setError]); const handleSync = async () => { await executeGitOperation(() => gitSync.sync(dir, ref)); }; const handlePull = async () => { await executeGitOperation(() => gitSync.pull(dir, ref)); }; const handlePush = async () => { await executeGitOperation(() => gitSync.push(dir, ref)); }; const handleForcePull = async () => { await executeGitOperation(() => gitSync.forcePull(dir, ref)); }; const handleForcePush = async () => { await executeGitOperation(() => gitSync.forcePush(dir, ref)); }; // Temporary feedback state helper const showTemporaryFeedback = useCallback(( setter: (value: boolean) => void, duration: number ) => { setter(true); setTimeout(() => setter(false), duration); }, []); const handleCopyUrl = async () => { if (!remoteUrl) return; try { await navigator.clipboard.writeText(remoteUrl.href); showTemporaryFeedback(setCopiedUrl, 2000); } catch (err) { console.error('Failed to copy URL:', err); } }; const handleDisconnect = async () => { if (!remoteUrl) return; try { await git.deleteRemote({ dir, remote: 'origin' }); // Clear any errors when disconnecting setError(null); queryClient.invalidateQueries({ queryKey: ['git-status', projectId] }); } catch (err) { const message = err instanceof Error ? err : new Error('Failed to disconnect'); setError(message); } }; const getExternalUrl = useCallback(async (url: URL): Promise => { if (url.protocol === 'http:' || url.protocol === 'https:') { return url.href; } if (url.protocol === 'nostr:') { const nostrUri = await NostrURI.parse(url.href); return ngitWebUrl(config.ngitWebUrl, nostrUri); } return null; }, [config.ngitWebUrl]); const handleOpenExternal = async () => { if (!remoteUrl) return; try { const externalUrl = await getExternalUrl(remoteUrl); if (externalUrl) { window.open(externalUrl, '_blank', 'noopener,noreferrer'); } } catch (err) { console.error('Failed to open external URL:', err); } }; const getProviderInfo = useCallback(() => { if (!remoteUrl) return null; // Check if it's a Nostr URI if (remoteUrl.protocol === 'nostr:') { return { name: 'Nostr Git', icon: , isNostr: true, }; } // Check if we have a matched credential const matchedCredential = findCredentialsForRepo(remoteUrl, settings.credentials); return { name: matchedCredential? matchedCredential.name : remoteUrl.hostname, icon: , isNostr: false, }; }, [remoteUrl, settings.credentials]); const providerInfo = getProviderInfo(); const remoteName = providerInfo?.name ?? 'the remote'; // Extract repo identifier from Nostr URI if applicable const getRepoIdentifier = useCallback(async (): Promise => { if (!remoteUrl || remoteUrl.protocol !== 'nostr:') { return null; } try { const nostrUri = await NostrURI.parse(remoteUrl.href); return nostrUri.identifier; } catch { return null; } }, [remoteUrl]); // Get the button label based on current operation const getButtonLabel = (): string => { if (!isSyncing) return 'Sync'; switch (currentOperation) { case 'fetch': return 'Fetching'; case 'pull': return 'Pulling'; case 'push': return 'Pushing'; default: return 'Syncing'; } }; const handleEditRepo = async () => { const repoId = await getRepoIdentifier(); if (repoId) { setRepoIdentifier(repoId); setEditRepoOpen(true); } }; const handleRepoEditSuccess = () => { // Refresh git status after successful edit queryClient.invalidateQueries({ queryKey: ['git-status', projectId] }); }; return (
{providerInfo?.icon}

{providerInfo?.name}

{providerInfo?.isNostr && ( Edit Repository )} setGitHistoryOpen(true)} className="gap-2"> Rollback Disconnect
{error && ( setError(null)} onForcePull={() => setShowForcePullDialog(true)} onForcePush={() => setShowForcePushDialog(true)} onPull={handlePull} remoteName={remoteName} remoteUrl={remoteUrl} /> )} {/* Unsynced changes notification */} {hasRemoteChanges && !error && (

This branch is{' '} {commitsAhead > 0 && ( <> {commitsAhead} commit{commitsAhead !== 1 ? 's' : ''} ahead of {commitsBehind > 0 ? ' and ' : ' '} )} {commitsBehind > 0 && ( <> {commitsBehind} commit{commitsBehind !== 1 ? 's' : ''} behind{' '} )} {ref} on {remoteName}.

)}
{repoIdentifier && ( )}
); }