import { useState, useCallback } from 'react'; import { Zap, Copy, Check, RefreshCw, EllipsisVertical, CloudOff, ExternalLink, ChevronDown, ArrowDown, ArrowUp, LoaderCircle } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; 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 { 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 type { SyncStepProps } from '../types'; import { cn } from '@/lib/utils'; import { NostrURI } from '@/lib/NostrURI'; import { ngitWebUrl } from '@/lib/ngitWebUrl'; import { useQueryClient } from '@tanstack/react-query'; import { findCredentialsForRepo } from '@/lib/gitCredentials'; type GitOperation = 'sync' | 'pull' | 'push' | 'force-pull' | 'force-push'; export function SyncStep({ projectId, remoteUrl }: SyncStepProps) { const queryClient = useQueryClient(); const [isSyncing, setIsSyncing] = useState(false); const [currentOperation, setCurrentOperation] = useState(null); const [error, setError] = useState(null); 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 { data: gitStatus } = useGitStatus(projectId); const { settings } = useGitSettings(); const { git } = useGit(); const { projectsPath } = useFSPaths(); const { config } = useAppContext(); const dir = `${projectsPath}/${projectId}`; const ref = gitStatus?.currentBranch || 'main'; const hasRemoteChanges = gitStatus?.remoteBranchExists && ((gitStatus?.ahead ?? 0) > 0 || (gitStatus?.behind ?? 0) > 0); const commitsAhead = gitStatus?.ahead ?? 0; const commitsBehind = gitStatus?.behind ?? 0; // Generic git operation handler const executeGitOperation = useCallback(async ( operation: GitOperation, action: () => Promise ) => { if (!remoteUrl) return; setIsSyncing(true); setCurrentOperation(operation); setError(null); setSyncSuccess(false); try { await action(); // Show success feedback setSyncSuccess(true); setTimeout(() => setSyncSuccess(false), 2500); } catch (err) { const message = err instanceof Error ? err : new Error(`Failed to ${operation}`); setError(message); } finally { setIsSyncing(false); setCurrentOperation(null); } }, [remoteUrl]); const handleSync = async () => { await executeGitOperation('sync', async () => { // Pull first to get latest changes setCurrentOperation('pull'); await git.pull({ dir, ref, singleBranch: true }); // Then push local changes setCurrentOperation('push'); await git.push({ dir, remote: 'origin', ref }); }); }; const handlePull = async () => { await executeGitOperation('pull', async () => { await git.pull({ dir, ref, singleBranch: true }); }); }; const handlePush = async () => { await executeGitOperation('push', async () => { await git.push({ dir, remote: 'origin', ref }); }); }; const handleForcePull = async () => { await executeGitOperation('force-pull', async () => { // Step 1: Fetch latest changes from remote await git.fetch({ dir, remote: 'origin', ref, singleBranch: true, }); // Step 2: Get the remote commit SHA const remoteRef = `refs/remotes/origin/${ref}`; const remoteSha = await git.resolveRef({ dir, ref: remoteRef }); // Step 3: Force update the current branch to point to remote await git.writeRef({ dir, ref: `refs/heads/${ref}`, value: remoteSha, force: true, }); // Step 4: Force checkout all files (overwrite local changes) await git.checkout({ dir, ref, force: true, }); // Invalidate git status to refresh UI queryClient.invalidateQueries({ queryKey: ['git-status', projectId] }); }); }; const handleForcePush = async () => { await executeGitOperation('force-push', async () => { await git.push({ dir, remote: 'origin', ref, force: true }); }); }; // 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' }); 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: , }; } // Check if we have a matched credential const matchedCredential = findCredentialsForRepo(remoteUrl, settings.credentials); return { name: matchedCredential? matchedCredential.name : remoteUrl.hostname, icon: , }; }, [remoteUrl, settings.credentials]); const providerInfo = getProviderInfo(); const remoteName = providerInfo?.name ?? 'the remote'; // Get the button label based on current operation const getButtonLabel = (): string => { if (!isSyncing) return 'Sync'; switch (currentOperation) { case 'pull': return 'Pull'; case 'push': return 'Push'; case 'force-pull': return 'Force Pull'; case 'force-push': return 'Force Push'; case 'sync': return 'Sync'; default: return 'Sync'; } }; return (
{providerInfo?.icon}

{providerInfo?.name}

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}.

)}
); }