Fix Kanban drag jitter: use DragOverlay + ghost placeholder

Root causes of the jitter:
1. No DragOverlay — card transformed in-place via translate(), causing
   parent column layout reflow as siblings shifted around the gap.
2. transition-all on cards fought with drag transforms on slow moves.
3. closestCorners collision bounced rapidly between column boundaries.

Fixes:
- DragOverlay renders a floating copy of the card above everything,
  with a subtle 2deg rotation and shadow for visual feedback.
- Original card becomes a ghost placeholder (accent border, 40% opacity)
  so the column layout stays stable during drag.
- Switched to closestCenter collision detection (less boundary bounce).
- Increased PointerSensor distance from 5px to 8px to reduce accidental
  drag activation.
- Removed transition-all from card styles (no more CSS vs drag fight).
- dropAnimation: null for instant snap on release.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Kyle 2026-03-17 04:37:56 +08:00
parent 7eac213c20
commit e0a5f4855f

View File

@ -1,226 +1,262 @@
import {
DndContext,
closestCorners,
PointerSensor,
TouchSensor,
useSensor,
useSensors,
type DragEndEvent,
useDroppable,
useDraggable,
} from '@dnd-kit/core';
import { format, parseISO } from 'date-fns';
import type { ProjectTask } from '@/types';
import { Badge } from '@/components/ui/badge';
import { AssigneeAvatars } from './AssignmentPicker';
const COLUMNS: { id: string; label: string; color: string }[] = [
{ id: 'pending', label: 'Pending', color: 'text-gray-400' },
{ id: 'in_progress', label: 'In Progress', color: 'text-blue-400' },
{ id: 'blocked', label: 'Blocked', color: 'text-red-400' },
{ id: 'on_hold', label: 'On Hold', color: 'text-orange-400' },
{ id: 'review', label: 'Review', color: 'text-yellow-400' },
{ id: 'completed', label: 'Completed', color: 'text-green-400' },
];
const priorityColors: Record<string, string> = {
none: 'bg-gray-500/20 text-gray-400',
low: 'bg-green-500/20 text-green-400',
medium: 'bg-yellow-500/20 text-yellow-400',
high: 'bg-red-500/20 text-red-400',
};
interface KanbanBoardProps {
tasks: ProjectTask[];
selectedTaskId: number | null;
kanbanParentTask?: ProjectTask | null;
onSelectTask: (taskId: number) => void;
onStatusChange: (taskId: number, status: string) => void;
onBackToAllTasks?: () => void;
}
function KanbanColumn({
column,
tasks,
selectedTaskId,
onSelectTask,
}: {
column: (typeof COLUMNS)[0];
tasks: ProjectTask[];
selectedTaskId: number | null;
onSelectTask: (taskId: number) => void;
}) {
const { setNodeRef, isOver } = useDroppable({ id: column.id });
return (
<div
ref={setNodeRef}
className={`flex-1 min-w-[160px] md:min-w-[200px] rounded-lg border transition-colors duration-150 ${
isOver ? 'border-accent/40 bg-accent/5' : 'border-border bg-card/50'
}`}
>
{/* Column header */}
<div className="px-3 py-2.5 border-b border-border">
<div className="flex items-center justify-between">
<span className={`text-sm font-semibold font-heading ${column.color}`}>
{column.label}
</span>
<span className="text-[11px] text-muted-foreground tabular-nums bg-secondary rounded-full px-2 py-0.5">
{tasks.length}
</span>
</div>
</div>
{/* Cards */}
<div className="p-2 space-y-2 min-h-[100px]">
{tasks.map((task) => (
<KanbanCard
key={task.id}
task={task}
isSelected={selectedTaskId === task.id}
onSelect={() => onSelectTask(task.id)}
/>
))}
</div>
</div>
);
}
function KanbanCard({
task,
isSelected,
onSelect,
}: {
task: ProjectTask;
isSelected: boolean;
onSelect: () => void;
}) {
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
id: task.id,
data: { task },
});
const style = transform
? {
transform: `translate(${transform.x}px, ${transform.y}px)`,
opacity: isDragging ? 0.5 : 1,
}
: undefined;
const completedSubtasks = task.subtasks?.filter((s) => s.status === 'completed').length ?? 0;
const totalSubtasks = task.subtasks?.length ?? 0;
return (
<div
ref={setNodeRef}
style={style}
{...listeners}
{...attributes}
onClick={onSelect}
className={`rounded-md border p-3 cursor-pointer transition-all duration-150 ${
isSelected
? 'border-accent/40 bg-accent/5 shadow-sm shadow-accent/10'
: 'border-border bg-card hover:bg-card-elevated hover:border-accent/20'
}`}
>
<p className="text-sm font-medium leading-tight mb-2">{task.title}</p>
<div className="flex items-center gap-1.5 flex-wrap">
<Badge
className={`text-[9px] px-1.5 py-0.5 rounded-full ${priorityColors[task.priority] ?? priorityColors.none}`}
>
{task.priority}
</Badge>
{task.due_date && (
<span className="text-[11px] text-muted-foreground tabular-nums">
{format(parseISO(task.due_date), 'MMM d')}
</span>
)}
{totalSubtasks > 0 && (
<span className="text-[11px] text-muted-foreground tabular-nums">
{completedSubtasks}/{totalSubtasks}
</span>
)}
</div>
{/* Assignee avatars */}
{task.assignments && task.assignments.length > 0 && (
<div className="flex justify-end mt-2">
<AssigneeAvatars assignments={task.assignments} max={2} />
</div>
)}
</div>
);
}
export default function KanbanBoard({
tasks,
selectedTaskId,
kanbanParentTask,
onSelectTask,
onStatusChange,
onBackToAllTasks,
}: KanbanBoardProps) {
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }) ,
useSensor(TouchSensor, { activationConstraint: { delay: 200, tolerance: 8 } })
);
// Subtask view is driven by kanbanParentTask (decoupled from selected task)
const isSubtaskView = kanbanParentTask != null && (kanbanParentTask.subtasks?.length ?? 0) > 0;
const activeTasks: ProjectTask[] = isSubtaskView ? (kanbanParentTask.subtasks ?? []) : tasks;
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over) return;
const taskId = active.id as number;
const newStatus = over.id as string;
const task = activeTasks.find((t) => t.id === taskId);
if (task && task.status !== newStatus && COLUMNS.some((c) => c.id === newStatus)) {
onStatusChange(taskId, newStatus);
}
};
const tasksByStatus = COLUMNS.map((col) => ({
column: col,
tasks: activeTasks.filter((t) => t.status === col.id),
}));
return (
<div className="flex flex-col gap-3">
{/* Subtask view header */}
{isSubtaskView && kanbanParentTask && (
<div className="flex items-center gap-3 px-1">
<button
onClick={onBackToAllTasks}
className="text-xs text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2"
>
Back to all tasks
</button>
<span className="text-muted-foreground text-xs">/</span>
<span className="text-xs text-foreground font-medium">
Subtasks of: {kanbanParentTask.title}
</span>
</div>
)}
<DndContext
sensors={sensors}
collisionDetection={closestCorners}
onDragEnd={handleDragEnd}
>
<div className="flex gap-3 overflow-x-auto pb-2">
{tasksByStatus.map(({ column, tasks: colTasks }) => (
<KanbanColumn
key={column.id}
column={column}
tasks={colTasks}
selectedTaskId={selectedTaskId}
onSelectTask={onSelectTask}
/>
))}
</div>
</DndContext>
</div>
);
}
import { useState, useCallback } from 'react';
import {
DndContext,
closestCenter,
PointerSensor,
TouchSensor,
useSensor,
useSensors,
type DragStartEvent,
type DragEndEvent,
useDroppable,
useDraggable,
DragOverlay,
} from '@dnd-kit/core';
import { format, parseISO } from 'date-fns';
import type { ProjectTask } from '@/types';
import { Badge } from '@/components/ui/badge';
import { AssigneeAvatars } from './AssignmentPicker';
const COLUMNS: { id: string; label: string; color: string }[] = [
{ id: 'pending', label: 'Pending', color: 'text-gray-400' },
{ id: 'in_progress', label: 'In Progress', color: 'text-blue-400' },
{ id: 'blocked', label: 'Blocked', color: 'text-red-400' },
{ id: 'on_hold', label: 'On Hold', color: 'text-orange-400' },
{ id: 'review', label: 'Review', color: 'text-yellow-400' },
{ id: 'completed', label: 'Completed', color: 'text-green-400' },
];
const priorityColors: Record<string, string> = {
none: 'bg-gray-500/20 text-gray-400',
low: 'bg-green-500/20 text-green-400',
medium: 'bg-yellow-500/20 text-yellow-400',
high: 'bg-red-500/20 text-red-400',
};
interface KanbanBoardProps {
tasks: ProjectTask[];
selectedTaskId: number | null;
kanbanParentTask?: ProjectTask | null;
onSelectTask: (taskId: number) => void;
onStatusChange: (taskId: number, status: string) => void;
onBackToAllTasks?: () => void;
}
function KanbanColumn({
column,
tasks,
selectedTaskId,
draggingId,
onSelectTask,
}: {
column: (typeof COLUMNS)[0];
tasks: ProjectTask[];
selectedTaskId: number | null;
draggingId: number | null;
onSelectTask: (taskId: number) => void;
}) {
const { setNodeRef, isOver } = useDroppable({ id: column.id });
return (
<div
ref={setNodeRef}
className={`flex-1 min-w-[160px] md:min-w-[200px] rounded-lg border transition-colors duration-150 ${
isOver ? 'border-accent/40 bg-accent/5' : 'border-border bg-card/50'
}`}
>
{/* Column header */}
<div className="px-3 py-2.5 border-b border-border">
<div className="flex items-center justify-between">
<span className={`text-sm font-semibold font-heading ${column.color}`}>
{column.label}
</span>
<span className="text-[11px] text-muted-foreground tabular-nums bg-secondary rounded-full px-2 py-0.5">
{tasks.length}
</span>
</div>
</div>
{/* Cards */}
<div className="p-2 space-y-2 min-h-[100px]">
{tasks.map((task) => (
<KanbanCard
key={task.id}
task={task}
isSelected={selectedTaskId === task.id}
isDragSource={draggingId === task.id}
onSelect={() => onSelectTask(task.id)}
/>
))}
</div>
</div>
);
}
// Card content — shared between in-place card and drag overlay
function CardContent({ task, isSelected, ghost }: { task: ProjectTask; isSelected: boolean; ghost?: boolean }) {
const completedSubtasks = task.subtasks?.filter((s) => s.status === 'completed').length ?? 0;
const totalSubtasks = task.subtasks?.length ?? 0;
return (
<div
className={`rounded-md border p-3 ${
ghost
? 'border-accent/20 bg-accent/5 opacity-40'
: isSelected
? 'border-accent/40 bg-accent/5 shadow-sm shadow-accent/10'
: 'border-border bg-card hover:bg-card-elevated hover:border-accent/20'
}`}
>
<p className="text-sm font-medium leading-tight mb-2">{task.title}</p>
<div className="flex items-center gap-1.5 flex-wrap">
<Badge
className={`text-[9px] px-1.5 py-0.5 rounded-full ${priorityColors[task.priority] ?? priorityColors.none}`}
>
{task.priority}
</Badge>
{task.due_date && (
<span className="text-[11px] text-muted-foreground tabular-nums">
{format(parseISO(task.due_date), 'MMM d')}
</span>
)}
{totalSubtasks > 0 && (
<span className="text-[11px] text-muted-foreground tabular-nums">
{completedSubtasks}/{totalSubtasks}
</span>
)}
</div>
{task.assignments && task.assignments.length > 0 && (
<div className="flex justify-end mt-2">
<AssigneeAvatars assignments={task.assignments} max={2} />
</div>
)}
</div>
);
}
function KanbanCard({
task,
isSelected,
isDragSource,
onSelect,
}: {
task: ProjectTask;
isSelected: boolean;
isDragSource: boolean;
onSelect: () => void;
}) {
const { attributes, listeners, setNodeRef } = useDraggable({
id: task.id,
data: { task },
});
return (
<div
ref={setNodeRef}
{...listeners}
{...attributes}
onClick={onSelect}
className="cursor-pointer"
>
<CardContent task={task} isSelected={isSelected} ghost={isDragSource} />
</div>
);
}
export default function KanbanBoard({
tasks,
selectedTaskId,
kanbanParentTask,
onSelectTask,
onStatusChange,
onBackToAllTasks,
}: KanbanBoardProps) {
const [draggingId, setDraggingId] = useState<number | null>(null);
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
useSensor(TouchSensor, { activationConstraint: { delay: 200, tolerance: 8 } })
);
const isSubtaskView = kanbanParentTask != null && (kanbanParentTask.subtasks?.length ?? 0) > 0;
const activeTasks: ProjectTask[] = isSubtaskView ? (kanbanParentTask.subtasks ?? []) : tasks;
const draggingTask = draggingId ? activeTasks.find((t) => t.id === draggingId) ?? null : null;
const handleDragStart = useCallback((event: DragStartEvent) => {
setDraggingId(event.active.id as number);
}, []);
const handleDragEnd = useCallback((event: DragEndEvent) => {
setDraggingId(null);
const { active, over } = event;
if (!over) return;
const taskId = active.id as number;
const newStatus = over.id as string;
const task = activeTasks.find((t) => t.id === taskId);
if (task && task.status !== newStatus && COLUMNS.some((c) => c.id === newStatus)) {
onStatusChange(taskId, newStatus);
}
}, [activeTasks, onStatusChange]);
const handleDragCancel = useCallback(() => {
setDraggingId(null);
}, []);
const tasksByStatus = COLUMNS.map((col) => ({
column: col,
tasks: activeTasks.filter((t) => t.status === col.id),
}));
return (
<div className="flex flex-col gap-3">
{/* Subtask view header */}
{isSubtaskView && kanbanParentTask && (
<div className="flex items-center gap-3 px-1">
<button
onClick={onBackToAllTasks}
className="text-xs text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2"
>
Back to all tasks
</button>
<span className="text-muted-foreground text-xs">/</span>
<span className="text-xs text-foreground font-medium">
Subtasks of: {kanbanParentTask.title}
</span>
</div>
)}
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragCancel={handleDragCancel}
>
<div className="flex gap-3 overflow-x-auto pb-2">
{tasksByStatus.map(({ column, tasks: colTasks }) => (
<KanbanColumn
key={column.id}
column={column}
tasks={colTasks}
selectedTaskId={selectedTaskId}
draggingId={draggingId}
onSelectTask={onSelectTask}
/>
))}
</div>
{/* Floating overlay — renders above everything, no layout impact */}
<DragOverlay dropAnimation={null}>
{draggingTask ? (
<div className="w-[200px] opacity-95 shadow-lg shadow-black/30 rotate-[2deg]">
<CardContent task={draggingTask} isSelected={false} />
</div>
) : null}
</DragOverlay>
</DndContext>
</div>
);
}