feat: re-parent tasks by drag and drop in the sidebar (#2355)

This commit is contained in:
Clément Fiere
2026-08-07 16:33:41 +02:00
committed by GitHub
parent 10cd0c0a84
commit 4d80edacf2
29 changed files with 1721 additions and 115 deletions
@@ -9,6 +9,7 @@ import { buildPrepareRequest } from "@/lib/services/session-launch-helpers";
import { useWorkspaceSidebarTasks } from "@/hooks/domains/kanban/use-workspace-sidebar-tasks";
import { useTaskActions, useArchiveAndSwitchTask } from "@/hooks/use-task-actions";
import { useTaskDetachDialog } from "@/hooks/use-detach-task";
import { useNestTaskByDrag } from "@/hooks/use-nest-task";
import { useTaskRemoval } from "@/hooks/use-task-removal";
import { workspaceModeFromMetadata } from "@/lib/kanban/map-task";
import {
@@ -523,6 +524,14 @@ function useSheetDeleteActions(
};
}
/**
* Re-parent via drag: runs the same composite nest operation the context menu
* uses, resolving the workflow from the snapshot keys.
*/
function useSheetNestTask() {
return useNestTaskByDrag();
}
export function useSheetActions(workspaceId: string | null, onOpenChange: (open: boolean) => void) {
const { t } = useTranslation();
const setActiveTask = useAppStore((state) => state.setActiveTask);
@@ -532,6 +541,7 @@ export function useSheetActions(workspaceId: string | null, onOpenChange: (open:
const { removeTaskFromBoard, loadTaskSessionsForTask } = useTaskRemoval({ store });
const deleteActions = useSheetDeleteActions(store, removeTaskFromBoard);
const detachActions = useTaskDetachDialog(store);
const handleNestTask = useSheetNestTask();
const handleSelectTask = useCallback(
(taskId: string) => {
@@ -617,6 +627,7 @@ export function useSheetActions(workspaceId: string | null, onOpenChange: (open:
handleArchiveTask,
handleWorkspaceChange,
handleTaskCreated,
handleNestTask,
archivingTask,
setArchivingTask,
isArchiving,
@@ -7,7 +7,7 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@kandev/ui/sheet";
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@kandev/ui/drawer";
import { Button } from "@kandev/ui/button";
import { TaskSwitcher } from "../task-switcher";
import type { TaskSwitcherItem } from "../task-switcher";
import type { TaskSwitcherItem, TaskSwitcherProps } from "../task-switcher";
import { SidebarFilterBar } from "../sidebar-filter/sidebar-filter-bar";
import type { StepDef } from "../task-switcher-context-menu";
import type { TaskMoveWorkflow } from "../task-move-context-menu";
@@ -60,32 +60,7 @@ function useSidebarGroupToggle(viewId: string) {
);
}
// eslint-disable-next-line max-lines-per-function -- assembles the shared task tree with the mobile drawer's view state.
export function MobileTaskList({
tasks,
workflows,
stepsByWorkflowId,
activeTaskId,
selectedTaskId,
onSelectTask,
onEditTask,
onRenameTask,
onCreateSubtask,
onArchiveTask,
onDeleteTask,
onDetachTask,
onLinkPullRequest,
onLinkIssue,
onLinkMergeRequest,
onLinkJiraTicket,
onLinkLinearIssue,
onLinkSentryIssue,
deletingTaskId,
isLoading,
loadError,
onRetryLoad,
retryLabel,
}: {
type MobileTaskListProps = {
tasks: TaskSwitcherItem[];
workflows: TaskMoveWorkflow[];
stepsByWorkflowId: Record<string, StepDef[]>;
@@ -98,6 +73,7 @@ export function MobileTaskList({
onArchiveTask: (taskId: string) => void;
onDeleteTask: (taskId: string) => Promise<void> | void;
onDetachTask: (taskId: string) => Promise<void> | void;
onNestTask?: (taskId: string, parentTaskId: string) => void;
onLinkPullRequest?: (taskId: string, taskTitle?: string) => void;
onLinkIssue?: (taskId: string, taskTitle?: string) => void;
onLinkMergeRequest?: (taskId: string, taskTitle?: string) => void;
@@ -109,7 +85,69 @@ export function MobileTaskList({
loadError?: string | null;
onRetryLoad?: () => void;
retryLabel?: string;
}) {
};
/**
* Assembles the TaskSwitcher props for the mobile task list, mirroring the
* desktop `buildTaskSwitcherProps` so the prop-forwarding surface stays a
* thin mapping layer.
*/
function buildMobileTaskSwitcherProps(
props: MobileTaskListProps,
helpers: {
grouped: TaskSwitcherProps["grouped"];
collapsedGroupKeys: string[];
onToggleGroup: (groupKey: string) => void;
collapsedSubtaskParentIds: string[];
onToggleSubtasks: (parentTaskId: string) => void;
onTogglePin: (taskId: string) => void;
onReorderGroup: (groupTaskIds: string[]) => void;
onReorderSubtasks: (parentTaskId: string, orderedSubtaskIds: string[]) => void;
pinnedTaskIds: string[];
},
): TaskSwitcherProps {
return {
grouped: helpers.grouped,
workflows: props.workflows,
stepsByWorkflowId: props.stepsByWorkflowId,
activeTaskId: props.activeTaskId,
selectedTaskId: props.selectedTaskId,
collapsedGroupKeys: helpers.collapsedGroupKeys,
onToggleGroup: helpers.onToggleGroup,
collapsedSubtaskParentIds: helpers.collapsedSubtaskParentIds,
onToggleSubtasks: helpers.onToggleSubtasks,
onSelectTask: props.onSelectTask,
onEditTask: props.onEditTask,
onRenameTask: props.onRenameTask,
onCreateSubtask: props.onCreateSubtask,
onArchiveTask: props.onArchiveTask,
onDeleteTask: props.onDeleteTask,
onDetachTask: props.onDetachTask,
onNestTask: props.onNestTask,
onLinkPullRequest: props.onLinkPullRequest,
onLinkIssue: props.onLinkIssue,
onLinkMergeRequest: props.onLinkMergeRequest,
onLinkJiraTicket: props.onLinkJiraTicket,
onLinkLinearIssue: props.onLinkLinearIssue,
onLinkSentryIssue: props.onLinkSentryIssue,
onTogglePin: helpers.onTogglePin,
onReorderGroup: helpers.onReorderGroup,
onReorderSubtasks: helpers.onReorderSubtasks,
pinnedTaskIds: helpers.pinnedTaskIds,
deletingTaskId: props.deletingTaskId,
isLoading: props.isLoading,
loadError: props.loadError,
onRetryLoad: props.onRetryLoad,
retryLabel: props.retryLabel,
totalTaskCount: props.tasks.length,
};
}
/**
* The mobile task tree surface: renders the shared TaskSwitcher with the
* mobile drawer's view state (grouping, ordering, collapse, reorder, nest).
*/
export function MobileTaskList(props: MobileTaskListProps) {
const view = useEffectiveSidebarView();
const {
pinnedTaskIds,
@@ -126,49 +164,25 @@ export function MobileTaskList({
const { i18n } = useTranslation();
const grouped = useMemo(
() =>
applyView(tasks, view, {
applyView(props.tasks, view, {
pinnedTaskIds,
orderedTaskIds,
subtaskOrderByParentId,
}),
[tasks, view, pinnedTaskIds, orderedTaskIds, subtaskOrderByParentId, i18n.language],
);
return (
<TaskSwitcher
grouped={grouped}
workflows={workflows}
stepsByWorkflowId={stepsByWorkflowId}
activeTaskId={activeTaskId}
selectedTaskId={selectedTaskId}
collapsedGroupKeys={view.collapsedGroups}
onToggleGroup={handleToggleGroup}
collapsedSubtaskParentIds={collapsedSubtaskParents}
onToggleSubtasks={toggleSubtaskCollapsed}
onSelectTask={onSelectTask}
onEditTask={onEditTask}
onRenameTask={onRenameTask}
onCreateSubtask={onCreateSubtask}
onArchiveTask={onArchiveTask}
onDeleteTask={onDeleteTask}
onDetachTask={onDetachTask}
onLinkPullRequest={onLinkPullRequest}
onLinkIssue={onLinkIssue}
onLinkMergeRequest={onLinkMergeRequest}
onLinkJiraTicket={onLinkJiraTicket}
onLinkLinearIssue={onLinkLinearIssue}
onLinkSentryIssue={onLinkSentryIssue}
onTogglePin={togglePinnedTask}
onReorderGroup={handleReorderGroup}
onReorderSubtasks={handleReorderSubtasks}
pinnedTaskIds={pinnedTaskIds}
deletingTaskId={deletingTaskId}
isLoading={isLoading}
loadError={loadError}
onRetryLoad={onRetryLoad}
retryLabel={retryLabel}
totalTaskCount={tasks.length}
/>
[props.tasks, view, pinnedTaskIds, orderedTaskIds, subtaskOrderByParentId, i18n.language],
);
const switcherProps = buildMobileTaskSwitcherProps(props, {
grouped,
collapsedGroupKeys: view.collapsedGroups,
onToggleGroup: handleToggleGroup,
collapsedSubtaskParentIds: collapsedSubtaskParents,
onToggleSubtasks: toggleSubtaskCollapsed,
onTogglePin: togglePinnedTask,
onReorderGroup: handleReorderGroup,
onReorderSubtasks: handleReorderSubtasks,
pinnedTaskIds,
});
return <TaskSwitcher {...switcherProps} />;
}
function TaskSwitcherSurfaceHeader({
@@ -334,6 +348,7 @@ function TaskSwitcherSurfaceContent({
onArchiveTask={surfaceAction(presentation, onOpenChange, actions.handleArchiveTask)}
onDeleteTask={surfaceAction(presentation, onOpenChange, actions.handleDeleteTask)}
onDetachTask={surfaceAction(presentation, onOpenChange, actions.handleDetachTask)}
onNestTask={actions.handleNestTask}
onLinkPullRequest={surfaceAction(
presentation,
onOpenChange,
@@ -27,6 +27,7 @@ export function buildTaskSwitcherProps(args: {
togglePinnedTask: TaskSwitcherComponentProps["onTogglePin"];
handleReorderGroup: TaskSwitcherComponentProps["onReorderGroup"];
handleReorderSubtasks: TaskSwitcherComponentProps["onReorderSubtasks"];
handleNestTask: TaskSwitcherComponentProps["onNestTask"];
isLoadingWorkflow: boolean;
archivedError: string | null;
retryArchivedTasks: () => void;
@@ -57,6 +58,7 @@ export function buildTaskSwitcherProps(args: {
onTogglePin: args.togglePinnedTask,
onReorderGroup: args.handleReorderGroup,
onReorderSubtasks: args.handleReorderSubtasks,
onNestTask: args.handleNestTask,
pinnedTaskIds: args.pinnedTaskIds,
deletingTaskId: args.sidebarActions.deletingTaskId,
isLoading: args.isLoadingWorkflow,
@@ -17,6 +17,7 @@ import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import { useWorkspaceSidebarTasks } from "@/hooks/domains/kanban/use-workspace-sidebar-tasks";
import { useTaskActions, useArchiveAndSwitchTask } from "@/hooks/use-task-actions";
import { useTaskDetachDialog } from "@/hooks/use-detach-task";
import { useNestTaskByDrag } from "@/hooks/use-nest-task";
import { useSidebarSelection, SidebarBulkDialogs } from "./task-session-sidebar-selection";
import { useTaskRemoval } from "@/hooks/use-task-removal";
import { findTaskInSnapshots } from "@/lib/kanban/find-task";
@@ -342,6 +343,7 @@ export function useSidebarActions(store: StoreApi) {
const archiveActions = useArchiveActions(store);
const deleteActions = useDeleteActions(store, removeTaskFromBoard);
const detachActions = useTaskDetachDialog(store);
const handleNestTask = useNestTaskByDrag();
const linkActions = useSidebarLinkActions(store);
const editActions = useSidebarTaskEdit();
@@ -377,6 +379,7 @@ export function useSidebarActions(store: StoreApi) {
preparingTaskId,
handleSelectTask,
handleMoveToStep,
handleNestTask,
renamingTask,
setRenamingTask,
handleRenameTask,
@@ -467,6 +470,7 @@ export const TaskSessionSidebar = memo(function TaskSessionSidebar({
togglePinnedTask,
handleReorderGroup,
handleReorderSubtasks,
handleNestTask: sidebarActions.handleNestTask,
isLoadingWorkflow,
archivedError,
retryArchivedTasks,
@@ -1,24 +1,157 @@
import { describe, expect, it } from "vitest";
import {
DRAG_ACTIVATION_DISTANCE,
TOUCH_DRAG_ACTIVATION_DELAY_MS,
TOUCH_DRAG_ACTIVATION_TOLERANCE_PX,
taskSwitcherDragActivationConstraints,
} from "@/components/task/task-switcher-subtask-dnd";
computeNestTargets,
nestDroppableId,
parseNestDroppableId,
resolveSidebarDrop,
} from "./task-switcher-subtask-dnd";
describe("task switcher subtask DnD activation", () => {
it("keeps pointer dragging responsive but delays touch dragging for scrollable mobile lists", () => {
expect(taskSwitcherDragActivationConstraints()).toEqual({
pointer: { distance: DRAG_ACTIVATION_DISTANCE },
touch: {
delay: TOUCH_DRAG_ACTIVATION_DELAY_MS,
tolerance: TOUCH_DRAG_ACTIVATION_TOLERANCE_PX,
},
});
// Fixture ids hoisted so the repeated literals stay below sonarjs's
// no-duplicate-string threshold.
const ROOT_A = "a";
const ROOT_B = "b";
const SUB_C = "c";
const SUB_D = "d";
const SUB_E = "e";
const WORKFLOW = "wf-1";
const OTHER_WORKFLOW = "wf-2";
const PWC = "parent-with-child"; // root that already has a child
const PWC_CHILD = "child-of-pwc";
function task(id: string, overrides: { workflowId?: string; parentTaskId?: string | null } = {}) {
return {
id,
title: id,
workflowId: overrides.workflowId ?? WORKFLOW,
parentTaskId: overrides.parentTaskId ?? undefined,
};
}
describe("nestDroppableId / parseNestDroppableId", () => {
it("round-trips task ids through the nest prefix", () => {
expect(parseNestDroppableId(nestDroppableId("task-1"))).toBe("task-1");
});
it("reuses stable activation constraint references across renders", () => {
expect(taskSwitcherDragActivationConstraints()).toBe(taskSwitcherDragActivationConstraints());
it("returns null for non-nest droppable ids", () => {
expect(parseNestDroppableId("task-1")).toBeNull();
});
});
describe("resolveSidebarDrop", () => {
const roots = [ROOT_A, ROOT_B];
const childrenByParent = new Map<string, string[]>([
[ROOT_A, [SUB_C, SUB_D]],
[ROOT_B, [SUB_E]],
]);
it("maps a drop on a nest zone to a re-parent", () => {
expect(
resolveSidebarDrop({
activeId: SUB_C,
overId: nestDroppableId(ROOT_B),
groupRootIds: roots,
childrenByParent,
}),
).toEqual({ kind: "nest", parentTaskId: ROOT_B });
});
it("rejects nesting under the dragged task itself", () => {
expect(
resolveSidebarDrop({
activeId: ROOT_A,
overId: nestDroppableId(ROOT_A),
groupRootIds: roots,
childrenByParent,
}),
).toBeNull();
});
it("reorders within the group root level", () => {
expect(
resolveSidebarDrop({
activeId: ROOT_A,
overId: ROOT_B,
groupRootIds: roots,
childrenByParent,
}),
).toEqual({ kind: "reorder-group", orderedTaskIds: [ROOT_B, ROOT_A] });
});
it("reorders within one parent's children", () => {
expect(
resolveSidebarDrop({
activeId: SUB_C,
overId: SUB_D,
groupRootIds: roots,
childrenByParent,
}),
).toEqual({ kind: "reorder-subtasks", parentTaskId: ROOT_A, orderedTaskIds: [SUB_D, SUB_C] });
});
it("rejects cross-level drops (subtask onto a sibling root)", () => {
expect(
resolveSidebarDrop({
activeId: SUB_C,
overId: ROOT_B,
groupRootIds: roots,
childrenByParent,
}),
).toBeNull();
});
it("rejects a drop on the dragged task's own row", () => {
expect(
resolveSidebarDrop({
activeId: SUB_C,
overId: SUB_C,
groupRootIds: roots,
childrenByParent,
}),
).toBeNull();
});
it("rejects a drop with no over target", () => {
expect(
resolveSidebarDrop({
activeId: SUB_C,
overId: null,
groupRootIds: roots,
childrenByParent,
}),
).toBeNull();
});
});
describe("computeNestTargets", () => {
const tasks = [
task(ROOT_A), // root
task(SUB_C, { parentTaskId: ROOT_A }), // subtask of a
task(ROOT_B), // root
task(SUB_E, { parentTaskId: ROOT_B }), // subtask of b
task("other-wf", { workflowId: OTHER_WORKFLOW }), // root in another workflow
task(PWC), // root with a child (valid target)
task(PWC_CHILD, { parentTaskId: PWC }),
];
it("offers same-workflow roots excluding the task and its current parent", () => {
// c (subtask of a) may nest under b and parent-with-child only.
expect(computeNestTargets(task(SUB_C, { parentTaskId: ROOT_A }), tasks)).toEqual(
new Set([ROOT_B, PWC]),
);
});
it("offers no targets when the task has children (would exceed one level)", () => {
expect(computeNestTargets(task(PWC), tasks)).toEqual(new Set());
});
it("offers no targets when the active task is unknown", () => {
expect(computeNestTargets(undefined, tasks)).toEqual(new Set());
});
it("excludes subtasks and other workflows even when they are roots", () => {
const targets = computeNestTargets(task(SUB_C, { parentTaskId: ROOT_A }), tasks);
expect(targets.has(SUB_E)).toBe(false);
expect(targets.has("other-wf")).toBe(false);
expect(targets.has(SUB_C)).toBe(false);
});
});
@@ -1,12 +1,16 @@
"use client";
import { useCallback, useMemo } from "react";
import { useCallback, useMemo, useState } from "react";
import {
DndContext,
MouseSensor,
TouchSensor,
closestCenter,
pointerWithin,
useDroppable,
type CollisionDetection,
type DragEndEvent,
type DragStartEvent,
useSensor,
useSensors,
} from "@dnd-kit/core";
@@ -17,7 +21,9 @@ import {
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
import { computeNestCandidates } from "@/lib/sidebar/nest-candidates";
import type { TaskSwitcherItem } from "./task-switcher";
export const DRAG_ACTIVATION_DISTANCE = 8;
@@ -32,6 +38,7 @@ const TASK_SWITCHER_DRAG_ACTIVATION_CONSTRAINTS = {
},
};
/** Shared mouse/touch activation constraints for the sidebar tree drags. */
export function taskSwitcherDragActivationConstraints() {
return TASK_SWITCHER_DRAG_ACTIVATION_CONSTRAINTS;
}
@@ -43,6 +50,120 @@ export function taskSwitcherDragActivationConstraints() {
// measurements remain accurate for previously rendered rows.
const OFFSCREEN_SKIP = "[content-visibility:auto] [contain-intrinsic-block-size:auto_52px]";
// Nest drop zones are registered as `nest:<taskId>` droppables. A drop on one
// re-parents the dragged task under that task; any other drop keeps the
// existing sibling-reorder semantics.
export const NEST_DROPPABLE_PREFIX = "nest:";
/** Droppable id of a row's nest drop zone: `nest:<taskId>`. */
export function nestDroppableId(taskId: string): string {
return NEST_DROPPABLE_PREFIX + taskId;
}
/** Returns the task id when `id` is a nest droppable id, else null. */
export function parseNestDroppableId(id: string): string | null {
return id.startsWith(NEST_DROPPABLE_PREFIX) ? id.slice(NEST_DROPPABLE_PREFIX.length) : null;
}
export type SidebarDropDecision =
| { kind: "nest"; parentTaskId: string }
| { kind: "reorder-group"; orderedTaskIds: string[] }
| { kind: "reorder-subtasks"; parentTaskId: string; orderedTaskIds: string[] };
/**
* Maps a group-level drag end onto the single intended action.
*
* A drop on a `nest:` droppable re-parents the dragged task. Any other drop
* reorders only when both tasks share a sibling level (group root list or one
* parent's children); cross-level drops are a no-op, matching the previous
* per-level behavior where a drag could never leave its own level.
*/
export function resolveSidebarDrop(args: {
activeId: string;
overId: string | null;
groupRootIds: string[];
childrenByParent: Map<string, string[]>;
}): SidebarDropDecision | null {
const { activeId, overId, groupRootIds, childrenByParent } = args;
if (!overId || overId === activeId) return null;
const nestTarget = parseNestDroppableId(overId);
if (nestTarget !== null) {
if (nestTarget === activeId) return null;
return { kind: "nest", parentTaskId: nestTarget };
}
const levelOf = (taskId: string): string | null => {
if (groupRootIds.includes(taskId)) return GROUP_ROOT_LEVEL;
for (const [parentId, ids] of childrenByParent) {
if (ids.includes(taskId)) return parentId;
}
return null;
};
const activeLevel = levelOf(activeId);
const overLevel = levelOf(overId);
if (activeLevel === null || activeLevel !== overLevel) return null;
const levelIds =
activeLevel === GROUP_ROOT_LEVEL ? groupRootIds : (childrenByParent.get(activeLevel) ?? []);
const oldIndex = levelIds.indexOf(activeId);
const newIndex = levelIds.indexOf(overId);
if (oldIndex < 0 || newIndex < 0) return null;
const ordered = arrayMove(levelIds, oldIndex, newIndex);
if (activeLevel === GROUP_ROOT_LEVEL) {
return { kind: "reorder-group", orderedTaskIds: ordered };
}
return { kind: "reorder-subtasks", parentTaskId: activeLevel, orderedTaskIds: ordered };
}
// Sentinel level id for the group root list inside resolveSidebarDrop.
const GROUP_ROOT_LEVEL = "__group_root__";
/**
* Computes the rows a drag may nest the active task under, mirroring the
* context menu's candidate rules (computeNestCandidates) scoped to the
* active task's workflow: same-workflow roots, excluding the task itself,
* its current parent, and any subtask (which also excludes its descendants).
*/
export function computeNestTargets(
activeTask: Pick<TaskSwitcherItem, "id" | "workflowId" | "parentTaskId"> | undefined,
groupTasks: TaskSwitcherItem[],
): Set<string> {
if (!activeTask) return new Set();
const sameWorkflow = groupTasks.filter((t) => t.workflowId === activeTask.workflowId);
return new Set(computeNestCandidates(sameWorkflow, activeTask.id).map((t) => t.id));
}
/**
* The drop target rendered on a row that the active drag may nest under.
* Absolute strip at the row's left edge; dropping on it re-parents the
* dragged task instead of reordering. Rendered only during an active drag
* with valid targets, so it never intercepts normal row clicks.
*/
export function NestDropZone({ taskId, title }: { taskId: string; title: string }) {
const { t } = useTranslation();
const { setNodeRef, isOver } = useDroppable({ id: nestDroppableId(taskId) });
const label = t("sidebar:nestUnder", { title });
return (
<div
ref={setNodeRef}
data-testid="nest-drop-zone"
data-task-id={taskId}
aria-label={label}
className={cn(
"absolute inset-y-0 left-0 z-20 w-6",
isOver ? "bg-primary/20" : "bg-transparent hover:bg-accent/40",
)}
>
{isOver && (
<span className="pointer-events-none absolute left-6 top-1/2 -translate-y-1/2 whitespace-nowrap rounded border bg-background px-2 py-0.5 text-xs shadow">
{label}
</span>
)}
</div>
);
}
/** Sortable implementation — isolated so `useSortable` is never called conditionally. */
function DraggableSortableTaskNode({
taskId,
@@ -172,25 +293,148 @@ function useLevelDnd(tasks: TaskSwitcherItem[], onReorder?: (orderedTaskIds: str
* Renders one level of sibling task nodes. When `onReorder` is omitted the DnD
* scaffolding (and the misleading grab cursor) is skipped, so non-reorderable
* callers get a plain list with no wasted setup.
*
* By default each level owns its own `DndContext`, which confines every drag
* to its sibling level. When `externalDragContext` is set the caller already
* rendered a group-spanning `DndContext` (see `TaskTreeDndGroup`) so cross-
* level drops like nest-under can be resolved — this level only contributes
* its `SortableContext` and nodes.
*/
export function SortableTaskLevel({
tasks,
onReorder,
renderNode,
externalDragContext = false,
}: {
tasks: TaskSwitcherItem[];
onReorder?: (orderedTaskIds: string[]) => void;
renderNode: (task: TaskSwitcherItem, isDraggable: boolean) => React.ReactNode;
externalDragContext?: boolean;
}) {
const { sensors, handleDragEnd, sortableIds } = useLevelDnd(tasks, onReorder);
const isDraggable = !!onReorder;
const body = tasks.map((task) => renderNode(task, isDraggable));
if (!onReorder) return <>{body}</>;
const sortable = (
<SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>
{body}
</SortableContext>
);
if (externalDragContext) return sortable;
return (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>
{body}
</SortableContext>
{sortable}
</DndContext>
);
}
/**
* One group-spanning DndContext for the sidebar task tree. Replaces the
* per-level contexts so a drag can target rows outside its own sibling level:
* reorder stays scoped to the level the drag started in (resolveSidebarDrop),
* and dropping on a `nest:` zone re-parents the dragged task.
*
* `children` receives the nest-target ids and the active drag id so rows can
* render their `NestDropZone` affordance only when they are valid targets.
*/
export function TaskTreeDndGroup({
groupTasks,
onReorderGroup,
onReorderSubtasks,
onNestTask,
children,
}: {
groupTasks: TaskSwitcherItem[];
onReorderGroup?: (groupTaskIds: string[]) => void;
onReorderSubtasks?: (parentTaskId: string, orderedSubtaskIds: string[]) => void;
onNestTask?: (activeTaskId: string, parentTaskId: string) => void;
children: (nestTargetIds: Set<string>, activeDragId: string | null) => React.ReactNode;
}) {
const [activeDragId, setActiveDragId] = useState<string | null>(null);
const sensors = useSensors(
useSensor(MouseSensor, {
activationConstraint: TASK_SWITCHER_DRAG_ACTIVATION_CONSTRAINTS.pointer,
}),
useSensor(TouchSensor, {
activationConstraint: TASK_SWITCHER_DRAG_ACTIVATION_CONSTRAINTS.touch,
}),
);
const enabled = !!onReorderGroup || !!onReorderSubtasks || !!onNestTask;
const { tasksById, groupRootIds, childrenByParent } = useMemo(() => {
const ids = new Set(groupTasks.map((t) => t.id));
const byParent = new Map<string, string[]>();
for (const t of groupTasks) {
if (t.parentTaskId && ids.has(t.parentTaskId)) {
const arr = byParent.get(t.parentTaskId) ?? [];
arr.push(t.id);
byParent.set(t.parentTaskId, arr);
}
}
return {
tasksById: new Map(groupTasks.map((t) => [t.id, t])),
groupRootIds: groupTasks
.filter((t) => !t.parentTaskId || !ids.has(t.parentTaskId))
.map((t) => t.id),
childrenByParent: byParent,
};
}, [groupTasks]);
const nestTargetIds = useMemo(
() => computeNestTargets(activeDragId ? tasksById.get(activeDragId) : undefined, groupTasks),
[activeDragId, tasksById, groupTasks],
);
const handleDragStart = useCallback((event: DragStartEvent) => {
setActiveDragId(String(event.active.id));
}, []);
const handleDragCancel = useCallback(() => setActiveDragId(null), []);
const handleDragEnd = useCallback(
(event: DragEndEvent) => {
setActiveDragId(null);
const { active, over } = event;
if (!over) return;
const decision = resolveSidebarDrop({
activeId: String(active.id),
overId: String(over.id),
groupRootIds,
childrenByParent,
});
if (!decision) return;
switch (decision.kind) {
case "nest":
onNestTask?.(String(active.id), decision.parentTaskId);
break;
case "reorder-group":
onReorderGroup?.(decision.orderedTaskIds);
break;
case "reorder-subtasks":
onReorderSubtasks?.(decision.parentTaskId, decision.orderedTaskIds);
break;
}
},
[groupRootIds, childrenByParent, onReorderGroup, onReorderSubtasks, onNestTask],
);
const collisionDetection = useCallback<CollisionDetection>((args) => {
// A pointer resting on a nest zone always means "nest under this row";
// everywhere else falls back to the nearest-row reorder.
const within = pointerWithin(args);
const nest = within.filter((collision) =>
collision.id.toString().startsWith(NEST_DROPPABLE_PREFIX),
);
if (nest.length > 0) return nest;
return closestCenter(args);
}, []);
if (!enabled) return <>{children(new Set(), null)}</>;
return (
<DndContext
sensors={sensors}
collisionDetection={collisionDetection}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragCancel={handleDragCancel}
>
{children(nestTargetIds, activeDragId)}
</DndContext>
);
}
+92 -21
View File
@@ -1,7 +1,13 @@
"use client";
import { useMemo } from "react";
import { countGroupTasks, type SidebarGroup } from "@/lib/sidebar/apply-view";
import { SortableTaskLevel, SortableTaskNode } from "./task-switcher-subtask-dnd";
import {
SortableTaskLevel,
SortableTaskNode,
TaskTreeDndGroup,
NestDropZone,
} from "./task-switcher-subtask-dnd";
import { GroupHeader } from "./task-switcher-group";
import { TaskRow, type SubtaskToggleInfo, type TaskRowProps } from "./task-switcher-row";
import type { TaskSwitcherItem } from "./task-switcher-types";
@@ -19,6 +25,13 @@ type TaskTreeContext = {
rowProps: TaskRowBaseProps;
onReorderGroup?: (groupTaskIds: string[]) => void;
onReorderSubtasks?: (parentTaskId: string, orderedSubtaskIds: string[]) => void;
onNestTask?: (taskId: string, parentTaskId: string) => void;
// Rows in nestTargetIds render a nest drop zone while a drag is active.
nestTargetIds: Set<string>;
activeDragId: string | null;
// The group renders one DndContext spanning every level (TaskTreeDndGroup),
// so levels must not create their own.
externalDragContext: boolean;
};
function TaskTreeNode({
@@ -44,16 +57,22 @@ function TaskTreeNode({
}
: undefined;
const isRoot = depth === 0;
const isNestTarget = ctx.nestTargetIds.has(task.id);
const handle = (
<TaskRow
task={task}
depth={depth}
isSubTask={!isRoot}
subtaskToggle={toggleInfo}
isPinned={isRoot && ctx.pinnedSet.has(task.id)}
{...ctx.rowProps}
onTogglePin={isRoot ? ctx.rowProps.onTogglePin : undefined}
/>
// The relative wrapper keeps the nest drop zone pinned to this row's
// left edge rather than spanning the nested subtree below it.
<div className="relative">
<TaskRow
task={task}
depth={depth}
isSubTask={!isRoot}
subtaskToggle={toggleInfo}
isPinned={isRoot && ctx.pinnedSet.has(task.id)}
{...ctx.rowProps}
onTogglePin={isRoot ? ctx.rowProps.onTogglePin : undefined}
/>
{isNestTarget && <NestDropZone taskId={task.id} title={task.title} />}
</div>
);
const nested =
!subsHidden && hasSubs ? (
@@ -86,6 +105,7 @@ function TaskTreeLevel({
<SortableTaskLevel
tasks={tasks}
onReorder={onReorder}
externalDragContext={ctx.externalDragContext}
renderNode={(task, levelDraggable) => (
<TaskTreeNode
key={task.id}
@@ -117,8 +137,39 @@ export type GroupSectionProps = {
showHeader: boolean;
onReorderGroup?: (groupTaskIds: string[]) => void;
onReorderSubtasks?: (parentTaskId: string, orderedSubtaskIds: string[]) => void;
onNestTask?: (taskId: string, parentTaskId: string) => void;
};
/**
* Flattens one group's subtree (roots + every descendant, in rendered order)
* so the group-spanning DndContext can resolve reorder levels and nest
* targets without consulting other groups' children. Tracks visited ids so a
* corrupted cycle in `subTasksByParentId` cannot recurse forever (mirrors
* countGroupTasks' protection).
*/
function flattenGroupTasks(
roots: TaskSwitcherItem[],
subTasksByParentId: Map<string, TaskSwitcherItem[]>,
): TaskSwitcherItem[] {
const out: TaskSwitcherItem[] = [];
const visited = new Set<string>();
const visit = (task: TaskSwitcherItem) => {
if (visited.has(task.id)) return;
visited.add(task.id);
out.push(task);
const subs = subTasksByParentId.get(task.id);
if (subs) {
for (const sub of subs) visit(sub);
}
};
for (const root of roots) visit(root);
return out;
}
/**
* Renders one sidebar group's task tree (header + the recursive tree wrapped
* in the group-spanning DndContext that enables nest-by-drag).
*/
export function GroupSection({
group,
subTasksByParentId,
@@ -131,17 +182,32 @@ export function GroupSection({
showHeader,
onReorderGroup,
onReorderSubtasks,
onNestTask,
}: GroupSectionProps) {
const totalCount = countGroupTasks(group.tasks, subTasksByParentId);
const ctx: TaskTreeContext = {
subTasksByParentId,
collapsedSubs: new Set(collapsedSubtaskParentIds ?? []),
onToggleSubtasks,
pinnedSet,
rowProps,
onReorderGroup,
onReorderSubtasks,
const groupTasks = useMemo(
() => flattenGroupTasks(group.tasks, subTasksByParentId),
[group.tasks, subTasksByParentId],
);
const renderTree = (nestTargetIds: Set<string>, activeDragId: string | null) => {
if (isCollapsed) return null;
const ctx: TaskTreeContext = {
subTasksByParentId,
collapsedSubs: new Set(collapsedSubtaskParentIds ?? []),
onToggleSubtasks,
pinnedSet,
rowProps,
onReorderGroup,
onReorderSubtasks,
onNestTask,
nestTargetIds,
activeDragId,
externalDragContext: true,
};
return <TaskTreeLevel parentTaskId={null} tasks={group.tasks} depth={0} ctx={ctx} />;
};
return (
<div>
{showHeader && (
@@ -153,9 +219,14 @@ export function GroupSection({
onToggle={onToggleCollapsed}
/>
)}
{!isCollapsed && (
<TaskTreeLevel parentTaskId={null} tasks={group.tasks} depth={0} ctx={ctx} />
)}
<TaskTreeDndGroup
groupTasks={groupTasks}
onReorderGroup={onReorderGroup}
onReorderSubtasks={onReorderSubtasks}
onNestTask={onNestTask}
>
{renderTree}
</TaskTreeDndGroup>
</div>
);
}
@@ -72,6 +72,8 @@ export type TaskSwitcherProps = {
onTogglePin?: (taskId: string) => void;
onReorderGroup?: (groupTaskIds: string[]) => void;
onReorderSubtasks?: (parentTaskId: string, orderedSubtaskIds: string[]) => void;
/** Re-parent a task under another task (drag onto a nest drop zone). */
onNestTask?: (taskId: string, parentTaskId: string) => void;
pinnedTaskIds?: string[];
deletingTaskId?: string | null;
isLoading?: boolean;
@@ -72,6 +72,7 @@ function buildGroupSectionProps(
showHeader,
onReorderGroup: props.onReorderGroup,
onReorderSubtasks: props.onReorderSubtasks,
onNestTask: props.onNestTask,
};
}