veritas-kanban/web/src/components/task/ConflictResolver.tsx
2026-09-04 13:27:38 -05:00

520 lines
18 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { UiDrawer as Drawer, UiModal as Modal, OverlayFooter } from '@/components/ui/UiOverlay';
import { UiAction } from '@/components/ui/UiVocabulary';
import {
Button,
Alert,
Code,
Group,
Loader,
Paper,
ScrollArea,
Stack,
Tabs,
Text,
Textarea,
} from '@mantine/core';
import {
useConflictStatus,
useFileConflict,
useResolveConflict,
useAbortConflict,
useContinueConflict,
} from '@/hooks/useConflicts';
import {
AlertTriangle,
Check,
X,
ChevronLeft,
ChevronRight,
FileWarning,
Loader2,
ArrowLeft,
ArrowRight,
GitMerge,
} from 'lucide-react';
import type { Task } from '@veritas-kanban/shared';
import { cn } from '@/lib/utils';
interface ConflictResolverProps {
task: Task;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function ConflictResolver({ task, open, onOpenChange }: ConflictResolverProps) {
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [manualContent, setManualContent] = useState('');
const [activeTab, setActiveTab] = useState<string | null>('sidebyside');
const [showAbortDialog, setShowAbortDialog] = useState(false);
const [operation, setOperation] = useState<'resolve' | 'abort' | 'continue' | null>(null);
const [operationError, setOperationError] = useState<string | null>(null);
const [errorOperation, setErrorOperation] = useState<'resolve' | 'abort' | 'continue' | null>(
null
);
const operationInFlight = useRef(false);
const operationErrorRef = useRef<HTMLDivElement>(null);
const manualFileKey = useRef<string | null>(null);
const resolutionStatus = useRef<{ before: string[]; after: string[] } | null>(null);
const isPending = operation !== null;
const { data: status, isLoading: statusLoading } = useConflictStatus(open ? task.id : undefined);
const { data: fileConflict, isLoading: fileLoading } = useFileConflict(
open && selectedFile ? task.id : undefined,
selectedFile || undefined
);
const resolveConflict = useResolveConflict();
const abortConflict = useAbortConflict();
const continueConflict = useContinueConflict();
// Auto-select first file if none selected
useEffect(() => {
let files = status?.conflictingFiles ?? [];
if (resolutionStatus.current) {
if (
files.length === resolutionStatus.current.before.length &&
files.every((file, index) => file === resolutionStatus.current?.before[index])
) {
files = resolutionStatus.current.after;
} else {
resolutionStatus.current = null;
}
}
const firstUnresolved = files[0];
if (firstUnresolved && !selectedFile) {
setSelectedFile(firstUnresolved);
}
}, [status?.conflictingFiles, selectedFile]);
useEffect(() => {
if (!operationError) return;
// Nested modal focus traps finish their initial-focus pass after this render.
// Defer the error handoff so the actionable failure keeps focus deterministically.
const focusError = window.setTimeout(() => {
operationErrorRef.current?.focus({ preventScroll: true });
operationErrorRef.current?.scrollIntoView({ block: 'center', behavior: 'instant' });
});
return () => window.clearTimeout(focusError);
}, [operationError]);
const runOperation = async (
nextOperation: 'resolve' | 'abort' | 'continue',
request: () => Promise<void>
) => {
if (operationInFlight.current) return;
operationInFlight.current = true;
setOperation(nextOperation);
setOperationError(null);
setErrorOperation(null);
try {
await request();
} catch (error) {
setErrorOperation(nextOperation);
setOperationError(error instanceof Error ? error.message : 'Unable to update conflicts.');
} finally {
operationInFlight.current = false;
setOperation(null);
}
};
const handleResolve = (resolution: 'ours' | 'theirs' | 'manual') => {
if (!selectedFile) return;
const filePath = selectedFile;
const draft = manualContent;
const previousFiles = status?.conflictingFiles ?? [];
void runOperation('resolve', async () => {
const result = await resolveConflict.mutateAsync({
taskId: task.id,
filePath,
resolution,
manualContent: resolution === 'manual' ? draft : undefined,
});
if (!result.success) throw new Error('The conflict was not resolved.');
resolutionStatus.current = { before: previousFiles, after: result.remainingConflicts };
const nextFile = result.remainingConflicts.find((file) => file !== filePath) ?? null;
manualFileKey.current = null;
setSelectedFile(nextFile);
});
};
const handleAbort = () => {
void runOperation('abort', async () => {
const result = await abortConflict.mutateAsync(task.id);
if (result.aborted !== true) throw new Error('The conflict operation was not aborted.');
setShowAbortDialog(false);
onOpenChange(false);
});
};
const handleContinue = () => {
void runOperation('continue', async () => {
const result = await continueConflict.mutateAsync({ taskId: task.id });
if (!result.success)
throw new Error(result.error || 'Unable to continue the conflict operation.');
onOpenChange(false);
});
};
const currentIndex =
selectedFile && status?.conflictingFiles ? status.conflictingFiles.indexOf(selectedFile) : -1;
const navigateFile = (direction: 'prev' | 'next') => {
if (operationInFlight.current || !status?.conflictingFiles.length) return;
const newIndex =
direction === 'prev'
? currentIndex > 0
? currentIndex - 1
: status.conflictingFiles.length - 1
: currentIndex < status.conflictingFiles.length - 1
? currentIndex + 1
: 0;
setSelectedFile(status.conflictingFiles[newIndex]);
};
// Initialize manual content when file changes
useEffect(() => {
const fileKey = selectedFile && fileConflict ? `${task.id}\u0000${selectedFile}` : null;
if (fileConflict && fileKey && manualFileKey.current !== fileKey) {
manualFileKey.current = fileKey;
setManualContent(fileConflict.content);
}
}, [fileConflict, selectedFile, task.id]);
const handleClose = () => {
if (!operationInFlight.current) {
setOperationError(null);
setErrorOperation(null);
onOpenChange(false);
}
};
return (
<Drawer
opened={open}
onClose={handleClose}
closeOnEscape={!isPending}
closeOnClickOutside={!isPending}
closeButtonProps={{ disabled: isPending }}
position="right"
compound
title={
<Group gap="xs">
<AlertTriangle className="h-5 w-5 text-amber-500" />
<Text fw={600}>Merge Conflicts</Text>
</Group>
}
>
<Stack gap={0} className="min-h-0 flex-1 overflow-hidden">
<Group justify="space-between" align="center" className="shrink-0 border-b p-4">
<Text size="sm" c="dimmed">
{status?.rebaseInProgress ? 'Rebase' : 'Merge'} has conflicts that need to be resolved
</Text>
<Group gap="xs">
{selectedFile && activeTab === 'sidebyside' && (
<>
<Button
size="xs"
variant="outline"
onClick={() => handleResolve('ours')}
disabled={isPending}
>
Accept Ours
</Button>
<Button
size="xs"
variant="outline"
onClick={() => handleResolve('theirs')}
disabled={isPending}
>
Accept Theirs
</Button>
</>
)}
{selectedFile && activeTab === 'manual' && (
<Button
size="xs"
onClick={() => handleResolve('manual')}
disabled={isPending}
leftSection={
operation === 'resolve' ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Check className="h-4 w-4" />
)
}
>
Save Resolution
</Button>
)}
{status?.conflictingFiles.length === 0 && (
<Button
onClick={handleContinue}
disabled={isPending}
leftSection={
operation === 'continue' ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<GitMerge className="h-4 w-4" />
)
}
>
Continue {status?.rebaseInProgress ? 'Rebase' : 'Merge'}
</Button>
)}
<Button
variant="outline"
color="red"
onClick={() => setShowAbortDialog(true)}
disabled={isPending}
leftSection={<X className="h-4 w-4" />}
>
Abort
</Button>
</Group>
</Group>
<div className="vk-overlay-scroll flex flex-wrap">
{operationError && errorOperation !== 'abort' && (
<Alert
ref={operationErrorRef}
tabIndex={-1}
color="red"
title="Conflict operation failed"
className="m-4 w-full shrink-0"
>
{operationError}
</Alert>
)}
{/* File list sidebar */}
<div className="w-64 shrink-0 border-r flex flex-col">
<div className="p-3 border-b bg-muted/50">
<Text size="sm" fw={500}>
Conflicting Files ({status?.conflictingFiles.length || 0})
</Text>
</div>
<ScrollArea className="flex-1">
{statusLoading ? (
<Stack align="center" gap="xs" className="p-4" c="dimmed">
<Loader color="gray" size="sm" />
<Text size="sm" c="dimmed">
Loading...
</Text>
</Stack>
) : status?.conflictingFiles.length === 0 ? (
<Stack align="center" gap="xs" className="p-4">
<Check className="h-8 w-8 mx-auto mb-2 text-green-500" />
<Text size="sm" c="dimmed">
All conflicts resolved!
</Text>
</Stack>
) : (
<div className="p-2">
{status?.conflictingFiles.map((file) => (
<button
key={file}
onClick={() => setSelectedFile(file)}
disabled={isPending}
className={cn(
'w-full text-left px-3 py-2 rounded-md text-sm truncate',
'hover:bg-muted transition-colors',
selectedFile === file && 'bg-muted font-medium'
)}
>
<FileWarning className="h-3 w-3 inline mr-2 text-amber-500" />
{file.split('/').pop()}
<span className="text-xs text-muted-foreground block truncate pl-5">
{file}
</span>
</button>
))}
</div>
)}
</ScrollArea>
</div>
{/* Main content area */}
<div className="flex-1 flex flex-col overflow-hidden">
{selectedFile && fileConflict ? (
<>
{/* File header with navigation */}
<div className="px-4 py-2 border-b bg-muted/30 flex items-center justify-between">
<div className="flex items-center gap-2">
<Button
variant="subtle"
size="xs"
onClick={() => navigateFile('prev')}
disabled={isPending || !status?.conflictingFiles.length}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Text size="sm">
{currentIndex + 1} of {status?.conflictingFiles.length}
</Text>
<Button
variant="subtle"
size="xs"
onClick={() => navigateFile('next')}
disabled={isPending || !status?.conflictingFiles.length}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
<Code>{selectedFile}</Code>
</div>
{/* Conflict viewer tabs */}
<Tabs
value={activeTab}
onChange={setActiveTab}
className="flex-1 flex flex-col overflow-hidden"
>
<Tabs.List className="mx-4 mt-2 w-fit">
<Tabs.Tab value="sidebyside" disabled={isPending}>
Side by Side
</Tabs.Tab>
<Tabs.Tab value="manual" disabled={isPending}>
Manual Edit
</Tabs.Tab>
</Tabs.List>
{/* Side by side view */}
<Tabs.Panel value="sidebyside" className="m-0 flex-1 overflow-hidden p-4">
<div className="grid grid-cols-2 gap-4 h-full">
{/* Ours */}
<Paper className="flex flex-col overflow-hidden" radius="md" withBorder>
<Group
justify="space-between"
className="border-b bg-blue-500/10 px-3 py-2"
>
<Group gap="xs">
<ArrowLeft className="h-4 w-4" />
<Text size="sm" fw={500}>
Ours (Current)
</Text>
</Group>
</Group>
<ScrollArea className="flex-1">
<pre className="p-3 text-xs font-mono whitespace-pre-wrap">
{fileConflict.oursContent || '(empty)'}
</pre>
</ScrollArea>
</Paper>
{/* Theirs */}
<Paper className="flex flex-col overflow-hidden" radius="md" withBorder>
<Group
justify="space-between"
className="border-b bg-green-500/10 px-3 py-2"
>
<Group gap="xs">
<ArrowRight className="h-4 w-4" />
<Text size="sm" fw={500}>
Theirs (Incoming)
</Text>
</Group>
</Group>
<ScrollArea className="flex-1">
<pre className="p-3 text-xs font-mono whitespace-pre-wrap">
{fileConflict.theirsContent || '(empty)'}
</pre>
</ScrollArea>
</Paper>
</div>
</Tabs.Panel>
{/* Manual edit view */}
<Tabs.Panel
value="manual"
className="flex-1 overflow-hidden m-0 p-4 flex flex-col"
>
<Paper className="flex flex-1 flex-col overflow-hidden" radius="md" withBorder>
<Group justify="space-between" className="border-b bg-muted/50 px-3 py-2">
<Text size="sm" fw={500}>
Manual Resolution
</Text>
</Group>
<Textarea
value={manualContent}
onChange={(e) => setManualContent(e.currentTarget.value)}
disabled={isPending}
className="flex-1 font-mono text-xs resize-none border-0 rounded-none focus-visible:ring-0"
placeholder="Edit the file content to resolve conflicts..."
/>
</Paper>
</Tabs.Panel>
</Tabs>
</>
) : fileLoading ? (
<Stack align="center" justify="center" className="flex-1">
<Loader color="gray" size="md" />
</Stack>
) : (
<Text className="flex flex-1 items-center justify-center" c="dimmed">
Select a file to resolve conflicts
</Text>
)}
</div>
</div>
</Stack>
{/* Abort confirmation dialog */}
<Modal
variant="confirm"
compound
opened={showAbortDialog}
onClose={() => {
if (!operationInFlight.current) {
setOperationError(null);
setErrorOperation(null);
setShowAbortDialog(false);
}
}}
closeOnEscape={!isPending}
closeOnClickOutside={!isPending}
closeButtonProps={{ disabled: isPending }}
title={`Abort ${status?.rebaseInProgress ? 'Rebase' : 'Merge'}?`}
centered
>
<div className="vk-overlay-scroll">
{operationError && errorOperation === 'abort' && (
<Alert
ref={operationErrorRef}
tabIndex={-1}
color="red"
title="Conflict operation failed"
className="mb-4 shrink-0"
>
{operationError}
</Alert>
)}
<Text size="sm" c="dimmed">
This will discard all conflict resolutions and return to the state before the
{status?.rebaseInProgress ? ' rebase' : ' merge'} started.
</Text>
</div>
<OverlayFooter>
<UiAction variant="quiet" disabled={isPending} onClick={() => setShowAbortDialog(false)}>
Cancel
</UiAction>
<UiAction
variant="destructive"
disabled={isPending}
onClick={() => {
void handleAbort();
}}
leftSection={
operation === 'abort' ? <Loader2 className="h-4 w-4 animate-spin" /> : undefined
}
>
Abort
</UiAction>
</OverlayFooter>
</Modal>
</Drawer>
);
}