fix: restore Nest under candidates (#3727)

Co-authored-by: Kandev Agent <agent@kandev.dev>
This commit is contained in:
João Salavisa
2026-09-16 17:41:30 +01:00
committed by GitHub
parent 057335f851
commit fc341e6cff
40 changed files with 1393 additions and 77 deletions
@@ -75,3 +75,12 @@ describe("toSheetItem remote executor projection", () => {
expect(item.primarySessionId).toBe("session-1");
});
});
describe("toSheetItem Office identity projection", () => {
// @covers AC-TASKS-SUBTASK-REPARENTING-DRAG-DROP-001.4
it("carries Office identity into the phone task drawer row", () => {
const item = toSheetItem(task({ isFromOffice: true }), emptyCtx());
expect(item.isFromOffice).toBe(true);
});
});
@@ -114,6 +114,7 @@ export function toSheetItem(
primaryExecutorProfileId: task.primaryExecutorProfileId ?? undefined,
workflowStepColor: facts.workflowStepColor,
isArchived: task.isArchived === true,
isFromOffice: task.isFromOffice,
isRemoteExecutor: task.isRemoteExecutor,
remoteExecutorId: task.primaryExecutorId ?? undefined,
remoteExecutorType: task.primaryExecutorType ?? undefined,
@@ -20,6 +20,7 @@ export function buildMobileTaskSwitcherProps(
): TaskSwitcherProps {
return {
grouped: helpers.grouped,
nestHierarchyTasks: props.tasks,
workflows: props.workflows,
stepsByWorkflowId: props.stepsByWorkflowId,
activeTaskId: props.activeTaskId,
@@ -8,7 +8,6 @@ import {
ContextMenuSubContent,
ContextMenuSubTrigger,
} from "@kandev/ui/context-menu";
import { useAppStore } from "@/components/state-provider";
import { useNestTask } from "@/hooks/use-nest-task";
import { computeNestCandidates } from "@/lib/sidebar/nest-candidates";
import type { TaskSwitcherItem } from "./task-switcher";
@@ -16,6 +15,8 @@ import { useTranslation } from "react-i18next";
type TaskNestContextMenuItemsProps = {
task: TaskSwitcherItem;
nestCandidateTasks?: TaskSwitcherItem[];
nestHierarchyTasks?: TaskSwitcherItem[];
disabled?: boolean;
};
@@ -25,25 +26,23 @@ type TaskNestContextMenuItemsProps = {
* other tasks in the same workflow, excluding the task's own descendants
* (which would create a cycle) and its current parent.
*/
export function TaskNestContextMenuItems({ task, disabled }: TaskNestContextMenuItemsProps) {
export function TaskNestContextMenuItems({
task,
nestCandidateTasks = [],
nestHierarchyTasks,
disabled,
}: TaskNestContextMenuItemsProps) {
const { t } = useTranslation();
const workflowId = task.workflowId;
// Prefer the all-workflows snapshot; fall back to the active kanban tasks,
// which the sidebar also renders from before the multi-snapshot fetch
// resolves (e.g. initial /t/:id load). Without the fallback the menu would
// show "No other tasks" even though rows are visible.
const tasks = useAppStore((s) => {
if (!workflowId) return undefined;
return (
s.kanbanMulti?.snapshots?.[workflowId]?.tasks ??
(s.kanban?.workflowId === workflowId ? s.kanban?.tasks : undefined)
);
});
const nestTask = useNestTask();
if (!workflowId || task.isArchived) return null;
const candidates = computeNestCandidates(tasks ?? [], task.id);
const candidates = computeNestCandidates(
nestCandidateTasks.filter((candidate) => candidate.workflowId === workflowId),
task.id,
nestHierarchyTasks ?? nestCandidateTasks,
);
const hasParent = Boolean(task.parentTaskId);
return (
@@ -233,6 +233,26 @@ describe("aggregateSidebarTasks active precedence", () => {
expect(result.allTasks[0].autopilot).toBe(true);
});
// @covers AC-TASKS-SUBTASK-REPARENTING-DRAG-DROP-001.4
it("preserves projected Office identity through a newer partial active task", () => {
const projected = makeTask("t1", "s1", {
isFromOffice: true,
updatedAt: "2026-08-03T00:00:00Z",
});
const active = makeTask("t1", "s1", {
updatedAt: "2026-08-03T00:00:01Z",
});
const result = aggregateSidebarTasks(
{ "wf-1": makeSnapshot([makeStep("s1", 0)], [projected]) },
"wf-1",
[active],
[makeStep("s1", 0)],
);
expect(result.allTasks[0].isFromOffice).toBe(true);
});
});
describe("aggregateSidebarTasks task lifecycle freshness", () => {
@@ -114,6 +114,7 @@ function reconcileTaskProjection(
// a partial WS event, so do not let it erase the value from the full
// workflow projection.
autopilot: active.autopilot ?? projected.autopilot,
isFromOffice: active.isFromOffice ?? projected.isFromOffice,
_workflowId: activeWorkflowId,
};
const task = activeTaskIsNewer(active, projected) ? activeTask : projected;
@@ -168,6 +168,15 @@ describe("buildSidebarItem", () => {
});
});
describe("buildSidebarItem Office identity", () => {
// @covers AC-TASKS-SUBTASK-REPARENTING-DRAG-DROP-001.4
it("preserves isFromOffice for candidate filtering", () => {
const item = buildSidebarItem(task({ isFromOffice: true }), emptyContext());
expect(item.isFromOffice).toBe(true);
});
});
describe("buildSidebarItem — parked on background work", () => {
it("carries the parked-on-background-work projection through to the sidebar row", () => {
const item = buildSidebarItem(task({ parkedOnBackgroundWork: true }), emptyContext());
@@ -159,6 +159,7 @@ export function buildSidebarItem(
remoteExecutorName: task.primaryExecutorName ?? undefined,
createdAt: task.createdAt,
isArchived: task.isArchived === true,
isFromOffice: task.isFromOffice,
parentTaskTitle: task.parentTaskId ? context.titleById.get(task.parentTaskId) : undefined,
parentTaskId: task.parentTaskId ?? undefined,
workspaceMode: task.workspaceMode,
@@ -14,6 +14,7 @@ type TaskSwitcherComponentProps = ComponentProps<typeof TaskSwitcher>;
*/
export function buildTaskSwitcherProps(args: {
grouped: TaskSwitcherComponentProps["grouped"];
nestHierarchyTasks: TaskSwitcherComponentProps["nestHierarchyTasks"];
workflows: TaskSwitcherComponentProps["workflows"];
stepsByWorkflowId: TaskSwitcherComponentProps["stepsByWorkflowId"];
highlightedTaskId: string | null;
@@ -49,6 +50,7 @@ export function buildTaskSwitcherProps(args: {
}): TaskSwitcherComponentProps {
return {
grouped: args.grouped,
nestHierarchyTasks: args.nestHierarchyTasks,
workflows: args.workflows,
stepsByWorkflowId: args.stepsByWorkflowId,
activeTaskId: args.highlightedTaskId,
@@ -501,6 +501,7 @@ export const TaskSessionSidebar = memo(function TaskSessionSidebar({
);
const switcherProps = buildTaskSwitcherProps({
grouped,
nestHierarchyTasks: displayTasks,
workflows,
stepsByWorkflowId,
highlightedTaskId,
@@ -47,6 +47,8 @@ type LinkActions = ReturnType<typeof selectTaskLinkActions>;
type SingleGroupProps = Pick<
SingleSelectionMenuProps,
| "task"
| "nestCandidateTasks"
| "nestHierarchyTasks"
| "isDeleting"
| "isArchiving"
| "isPinned"
@@ -282,6 +284,8 @@ function SingleEditGroup({
function SingleRelationshipsGroup({
task,
nestCandidateTasks,
nestHierarchyTasks,
isDeleting,
onCreateSubtask,
onDetachTask,
@@ -292,6 +296,8 @@ function SingleRelationshipsGroup({
}: Pick<
SingleGroupProps,
| "task"
| "nestCandidateTasks"
| "nestHierarchyTasks"
| "isDeleting"
| "onCreateSubtask"
| "onDetachTask"
@@ -303,7 +309,14 @@ function SingleRelationshipsGroup({
return (
<>
<TaskCreateSubtaskItem task={task} disabled={isDeleting} onCreateSubtask={onCreateSubtask} />
{!task.isArchived && <TaskNestContextMenuItems task={task} disabled={isDeleting} />}
{!task.isArchived && (
<TaskNestContextMenuItems
task={task}
nestCandidateTasks={nestCandidateTasks}
nestHierarchyTasks={nestHierarchyTasks}
disabled={isDeleting}
/>
)}
{hasLinkGroup && linkActions && pluginLinkActions && (
<TaskPluginLinkMenu
disabled={isDeleting}
@@ -12,6 +12,7 @@ import type { TaskSwitcherItem } from "./task-switcher-types";
const PLUGIN_ID = "example-task-actions";
const PLUGIN_ACTION_LABEL = "Inspect task";
const WORKFLOW_1_ID = "workflow-1";
const WORKFLOW_1_NAME = "Workflow 1";
const WORKFLOW_ID = WORKFLOW_1_ID;
const STEP_ID = "step-1";
const SEPARATOR_SLOT = "context-menu-separator";
@@ -171,7 +172,7 @@ describe("TaskItemWithContextMenu — grouped single-task actions", () => {
parentTaskId: "parent-1",
})}
workflows={[
{ id: WORKFLOW_ID, name: "Workflow 1" },
{ id: WORKFLOW_ID, name: WORKFLOW_1_NAME },
{ id: "workflow-2", name: "Workflow 2" },
]}
stepsByWorkflowId={{
@@ -246,7 +247,7 @@ describe("TaskItemWithContextMenu — grouped bulk actions", () => {
task={task({ workflowId: WORKFLOW_ID, workflowStepId: STEP_ID })}
selectedTaskIds={new Set(["task-1", "task-2"])}
workflows={[
{ id: WORKFLOW_ID, name: "Workflow 1" },
{ id: WORKFLOW_ID, name: WORKFLOW_1_NAME },
{ id: "workflow-2", name: "Workflow 2" },
]}
stepsByWorkflowId={{
@@ -309,7 +310,7 @@ function renderWorkflowMoveMenu({
workflowId: WORKFLOW_1_ID,
workflowStepId: "step-1",
})}
workflows={[{ id: WORKFLOW_1_ID, name: "Workflow 1" }]}
workflows={[{ id: WORKFLOW_1_ID, name: WORKFLOW_1_NAME }]}
stepsByWorkflowId={{
[WORKFLOW_1_ID]: [
{ id: "step-1", title: "Todo" },
@@ -26,6 +26,10 @@ export { createTaskLinkSelectAction } from "./task-switcher-link-menu";
type ContextMenuProps = TaskLinkHandlers & {
task: TaskSwitcherItem;
nestCandidateTasks?: TaskSwitcherItem[];
nestHierarchyTasks?: TaskSwitcherItem[];
getNestCandidateTasks?: () => TaskSwitcherItem[];
getNestHierarchyTasks?: () => TaskSwitcherItem[] | undefined;
workflows?: TaskMoveWorkflow[];
stepsByWorkflowId?: Record<string, StepDef[]>;
steps?: StepDef[];
@@ -55,19 +59,40 @@ type ContextMenuProps = TaskLinkHandlers & {
isMixedWorkflowSelection?: boolean;
};
type OpenedNestSources = {
candidates?: TaskSwitcherItem[];
hierarchy?: TaskSwitcherItem[];
};
function useContextMenuOpenState(props: ContextMenuProps) {
const [contextOpen, setContextOpen] = useState(false);
const [openedNestSources, setOpenedNestSources] = useState<OpenedNestSources>({});
const handleContextOpenChange = (open: boolean) => {
if (open) {
setOpenedNestSources({
candidates: props.getNestCandidateTasks?.() ?? props.nestCandidateTasks,
hierarchy: props.getNestHierarchyTasks?.() ?? props.nestHierarchyTasks,
});
}
setContextOpen(open);
};
return { contextOpen, setContextOpen, openedNestSources, handleContextOpenChange };
}
// This component coordinates the context menu and drag cancellation. Archive
// state lives in its focused adapter so unavailable actions stay unavailable.
export function TaskItemWithContextMenu(props: ContextMenuProps) {
const { children, ...menuProps } = props;
const { task, stepsByWorkflowId, steps, onRequestMoveOptions, onBeforeMoveOptionsOpen } = props;
const [contextOpen, setContextOpen] = useState(false);
const { contextOpen, setContextOpen, openedNestSources, handleContextOpenChange } =
useContextMenuOpenState(props);
const [menuKey, setMenuKey] = useState(0);
const moveTasks = useTaskWorkflowMove();
const closeMenu = () => {
setContextOpen(false);
setMenuKey((k) => k + 1);
};
const { handleOpenChange, triggerProps } = useMenuTouchDragCancel(setContextOpen);
const { handleOpenChange, triggerProps } = useMenuTouchDragCancel(handleContextOpenChange);
const { isFinePointer, isMobile } = useResponsiveBreakpoint();
const usesTouchDrawer = useTouchDrawer();
const archive = useTaskSwitcherArchiveConfirmation({
@@ -107,11 +132,17 @@ export function TaskItemWithContextMenu(props: ContextMenuProps) {
// owns its own drawer, so the inline path stays off there too.
const inlineSubmitWithOptions =
!usesTouchDrawer && !onRequestMoveOptions ? submitMoveOptionsForStep : undefined;
const contextMenuProps = buildTaskContextMenuItemsProps(props, closeMenu, moveTasks, {
onMoveToStepWithOptions: handleMoveToStepWithOptions,
onSubmitWithOptions: inlineSubmitWithOptions,
isMoving,
});
const contextMenuProps = buildTaskContextMenuItemsProps(
props,
openedNestSources,
closeMenu,
moveTasks,
{
onMoveToStepWithOptions: handleMoveToStepWithOptions,
onSubmitWithOptions: inlineSubmitWithOptions,
isMoving,
},
);
return (
<>
@@ -157,7 +188,11 @@ export function TaskItemWithContextMenu(props: ContextMenuProps) {
export type TaskContextMenuItemsProps = Omit<
ContextMenuProps,
"children" | "onBeforeMoveOptionsOpen" | "onRequestMoveOptions"
| "children"
| "onBeforeMoveOptionsOpen"
| "onRequestMoveOptions"
| "getNestCandidateTasks"
| "getNestHierarchyTasks"
> & {
closeMenu: () => void;
moveTasks: ReturnType<typeof useTaskWorkflowMove>;
@@ -171,6 +206,7 @@ export type TaskContextMenuItemsProps = Omit<
function buildTaskContextMenuItemsProps(
props: ContextMenuProps,
nestSources: OpenedNestSources,
closeMenu: () => void,
moveTasks: ReturnType<typeof useTaskWorkflowMove>,
moveOptions: {
@@ -186,10 +222,14 @@ function buildTaskContextMenuItemsProps(
children: _children,
onRequestMoveOptions: _onRequestMoveOptions,
onBeforeMoveOptionsOpen: _onBeforeMoveOptionsOpen,
getNestCandidateTasks: _getNestCandidateTasks,
getNestHierarchyTasks: _getNestHierarchyTasks,
...rest
} = props;
return {
...rest,
nestCandidateTasks: nestSources.candidates ?? rest.nestCandidateTasks,
nestHierarchyTasks: nestSources.hierarchy ?? rest.nestHierarchyTasks,
onMoveToStepWithOptions: moveOptions.onMoveToStepWithOptions,
onSubmitWithOptions: moveOptions.onSubmitWithOptions,
moveOptionsBusy: moveOptions.isMoving,
@@ -0,0 +1,112 @@
import { afterEach, describe, expect, it } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { StateProvider } from "@/components/state-provider";
import { ToastProvider } from "@/components/toast-provider";
import { TaskItemWithContextMenu } from "./task-switcher-context-menu";
import type { TaskSwitcherItem } from "./task-switcher-types";
const WORKFLOW_ID = "workflow-1";
const STEP_ID = "step-1";
function task(overrides: Partial<TaskSwitcherItem> = {}): TaskSwitcherItem {
return { id: "task-1", title: "Task 1", state: "IN_PROGRESS", ...overrides };
}
function storeTask(item: TaskSwitcherItem) {
return {
id: item.id,
title: item.title,
workflowId: item.workflowId,
workflowStepId: item.workflowStepId,
position: 0,
};
}
afterEach(cleanup);
describe("TaskItemWithContextMenu Nest under candidates", () => {
// @covers AC-TASKS-SUBTASK-REPARENTING-DRAG-DROP-001.1
// @covers AC-TASKS-SUBTASK-REPARENTING-DRAG-DROP-001.2
it("uses rendered candidates when the workflow snapshot is partial", async () => {
const current = task({ workflowId: WORKFLOW_ID, workflowStepId: STEP_ID });
const target = task({
id: "visible-target",
title: "Visible target",
workflowId: WORKFLOW_ID,
workflowStepId: STEP_ID,
});
render(
<StateProvider
initialState={
{
kanban: {
workflowId: WORKFLOW_ID,
steps: [],
tasks: [storeTask(current), storeTask(target)],
},
kanbanMulti: {
isLoading: false,
snapshots: {
[WORKFLOW_ID]: {
workflowId: WORKFLOW_ID,
workflowName: "Workflow 1",
steps: [],
tasks: [storeTask(current)],
isPlaceholder: true,
},
},
},
} as never
}
>
<ToastProvider>
<TaskItemWithContextMenu task={current} nestCandidateTasks={[current, target]}>
<div data-testid="task-row">Task 1</div>
</TaskItemWithContextMenu>
</ToastProvider>
</StateProvider>,
);
fireEvent.contextMenu(screen.getByTestId("task-row"));
const nestUnder = await screen.findByRole("menuitem", { name: "Nest under" });
fireEvent.pointerMove(nestUnder, { pointerType: "mouse" });
expect(await screen.findByRole("menuitem", { name: "Visible target" })).not.toBeNull();
});
it("captures the latest candidates when the menu opens", async () => {
const current = task({ workflowId: WORKFLOW_ID, workflowStepId: STEP_ID });
const staleTarget = task({
id: "stale-target",
title: "Stale target",
workflowId: WORKFLOW_ID,
workflowStepId: STEP_ID,
});
const latestTarget = task({
id: "latest-target",
title: "Latest target",
workflowId: WORKFLOW_ID,
workflowStepId: STEP_ID,
});
let candidates = [current, staleTarget];
render(
<StateProvider>
<ToastProvider>
<TaskItemWithContextMenu task={current} getNestCandidateTasks={() => candidates}>
<div data-testid="fresh-task-row">Task 1</div>
</TaskItemWithContextMenu>
</ToastProvider>
</StateProvider>,
);
candidates = [current, latestTarget];
fireEvent.contextMenu(screen.getByTestId("fresh-task-row"));
const nestUnder = await screen.findByRole("menuitem", { name: "Nest under" });
fireEvent.pointerMove(nestUnder, { pointerType: "mouse" });
expect(await screen.findByRole("menuitem", { name: "Latest target" })).not.toBeNull();
expect(screen.queryByRole("menuitem", { name: "Stale target" })).toBeNull();
});
});
@@ -8,6 +8,7 @@ const renderCounts = vi.hoisted(() => ({
groups: new Map<string, number>(),
nodes: new Map<string, number>(),
rows: new Map<string, number>(),
nestCandidateGetters: new Map<string, (() => TaskSwitcherItem[]) | undefined>(),
}));
function increment(counts: Map<string, number>, key: string) {
@@ -22,7 +23,18 @@ vi.mock("./task-item", () => ({
}));
vi.mock("./task-switcher-context-menu", () => ({
TaskItemWithContextMenu: ({ children }: { children: ReactElement }) => children,
TaskItemWithContextMenu: ({
task,
children,
getNestCandidateTasks,
}: {
task: TaskSwitcherItem;
children: ReactElement;
getNestCandidateTasks?: () => TaskSwitcherItem[];
}) => {
renderCounts.nestCandidateGetters.set(task.id, getNestCandidateTasks);
return children;
},
}));
vi.mock("./task-switcher-subtask-dnd", () => ({
@@ -131,6 +143,7 @@ beforeEach(() => {
renderCounts.groups.clear();
renderCounts.nodes.clear();
renderCounts.rows.clear();
renderCounts.nestCandidateGetters.clear();
});
afterEach(() => cleanup());
@@ -189,6 +202,20 @@ describe("TaskSwitcher render stability", () => {
expect(latestHandler).toHaveBeenCalledWith(TASK_B);
});
it("gives a skipped row the latest nest candidates", () => {
const taskA = task(TASK_A, WORKFLOW_A);
const taskB = task(TASK_B, WORKFLOW_A);
const view = render(switcher(groupedTogether([taskA, taskB])));
view.rerender(switcher(groupedTogether([{ ...taskA, title: TASK_A_UPDATED }, { ...taskB }])));
expect(
renderCounts.nestCandidateGetters
.get(TASK_B)?.()
.map((item) => item.title),
).toEqual([TASK_A_UPDATED, TASK_B]);
});
});
describe("TaskSwitcher nested render stability", () => {
@@ -16,6 +16,9 @@ export type SubtaskToggleInfo = {
export type TaskRowProps = {
task: TaskSwitcherItem;
nestCandidateTasks?: TaskSwitcherItem[];
getNestCandidateTasks?: () => TaskSwitcherItem[];
getNestHierarchyTasks?: () => TaskSwitcherItem[] | undefined;
isSubTask?: boolean;
depth?: number;
subtaskToggle?: SubtaskToggleInfo;
@@ -66,6 +69,9 @@ function archiveAware<T>(value: T | undefined, isArchived: boolean): T | undefin
function getContextMenuProps(props: TaskRowProps, isArchived: boolean) {
return {
nestCandidateTasks: props.nestCandidateTasks,
getNestCandidateTasks: props.getNestCandidateTasks,
getNestHierarchyTasks: props.getNestHierarchyTasks,
onEditTask: archiveAware(props.onEditTask, isArchived),
onRenameTask: archiveAware(props.onRenameTask, isArchived),
onArchiveTask: archiveAware(props.onArchiveTask, isArchived),
@@ -17,13 +17,24 @@ 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";
const OFFICE_SUBJECT = "office-subject";
const OFFICE_TARGET_ROOT = "office-target-root";
const HIDDEN_CHILD = "hidden-child";
function task(id: string, overrides: { workflowId?: string; parentTaskId?: string | null } = {}) {
function task(
id: string,
overrides: {
workflowId?: string;
parentTaskId?: string | null;
isFromOffice?: boolean;
} = {},
) {
return {
id,
title: id,
workflowId: overrides.workflowId ?? WORKFLOW,
parentTaskId: overrides.parentTaskId ?? undefined,
isFromOffice: overrides.isFromOffice,
};
}
@@ -154,4 +165,39 @@ describe("computeNestTargets", () => {
expect(targets.has("other-wf")).toBe(false);
expect(targets.has(SUB_C)).toBe(false);
});
// @covers AC-TASKS-SUBTASK-REPARENTING-DRAG-DROP-001.1
// @covers AC-TASKS-SUBTASK-REPARENTING-DRAG-DROP-001.4
it("matches the shared Office candidates for a subject with children", () => {
const officeTasks = [
task(OFFICE_SUBJECT, { isFromOffice: true }),
task("office-descendant", {
parentTaskId: OFFICE_SUBJECT,
isFromOffice: true,
}),
task(OFFICE_TARGET_ROOT, { isFromOffice: true }),
task("office-target-child", {
parentTaskId: OFFICE_TARGET_ROOT,
isFromOffice: true,
}),
];
expect(computeNestTargets(officeTasks[0], officeTasks)).toEqual(
new Set([OFFICE_TARGET_ROOT, "office-target-child"]),
);
});
it("excludes a descendant whose intermediate ancestor is hidden", () => {
const hierarchy = [
task(OFFICE_SUBJECT, { isFromOffice: true }),
task(HIDDEN_CHILD, { parentTaskId: OFFICE_SUBJECT, isFromOffice: true }),
task("visible-grandchild", { parentTaskId: HIDDEN_CHILD, isFromOffice: true }),
task("valid-target", { isFromOffice: true }),
];
const visibleTasks = hierarchy.filter((candidate) => candidate.id !== HIDDEN_CHILD);
expect(computeNestTargets(hierarchy[0], visibleTasks, hierarchy)).toEqual(
new Set(["valid-target"]),
);
});
});
@@ -122,16 +122,20 @@ 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).
* active task's workflow. Every mode excludes the task, its current parent,
* and descendants; Kanban keeps the root-only depth limit while Office may
* target tasks at any depth.
*/
export function computeNestTargets(
activeTask: Pick<TaskSwitcherItem, "id" | "workflowId" | "parentTaskId"> | undefined,
groupTasks: TaskSwitcherItem[],
hierarchyTasks: readonly TaskSwitcherItem[] = groupTasks,
): 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));
return new Set(
computeNestCandidates(sameWorkflow, activeTask.id, hierarchyTasks).map((task) => task.id),
);
}
/**
@@ -328,6 +332,47 @@ export function SortableTaskLevel({
);
}
function useActiveNestDrag(
groupTasks: TaskSwitcherItem[],
tasksById: ReadonlyMap<string, TaskSwitcherItem>,
getNestHierarchyTasks?: () => TaskSwitcherItem[] | undefined,
) {
const [activeDrag, setActiveDrag] = useState<{
id: string;
hierarchyTasks?: TaskSwitcherItem[];
} | null>(null);
const activeDragId = activeDrag?.id ?? null;
const nestTargetIds = useMemo(
() =>
computeNestTargets(
activeDragId ? tasksById.get(activeDragId) : undefined,
groupTasks,
activeDrag?.hierarchyTasks ?? groupTasks,
),
[activeDrag, activeDragId, tasksById, groupTasks],
);
const handleDragStart = useCallback(
(event: DragStartEvent) => {
setActiveDrag({
id: String(event.active.id),
hierarchyTasks: getNestHierarchyTasks?.(),
});
},
[getNestHierarchyTasks],
);
const clearActiveDrag = useCallback(() => setActiveDrag(null), []);
return { activeDragId, nestTargetIds, handleDragStart, clearActiveDrag };
}
type TaskTreeDndGroupProps = {
groupTasks: TaskSwitcherItem[];
getNestHierarchyTasks?: () => TaskSwitcherItem[] | undefined;
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;
};
/**
* 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:
@@ -339,18 +384,12 @@ export function SortableTaskLevel({
*/
export function TaskTreeDndGroup({
groupTasks,
getNestHierarchyTasks,
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);
}: TaskTreeDndGroupProps) {
const sensors = useSensors(
useSensor(MouseSensor, {
activationConstraint: TASK_SWITCHER_DRAG_ACTIVATION_CONSTRAINTS.pointer,
@@ -378,18 +417,14 @@ export function TaskTreeDndGroup({
childrenByParent: byParent,
};
}, [groupTasks]);
const nestTargetIds = useMemo(
() => computeNestTargets(activeDragId ? tasksById.get(activeDragId) : undefined, groupTasks),
[activeDragId, tasksById, groupTasks],
const { activeDragId, nestTargetIds, handleDragStart, clearActiveDrag } = useActiveNestDrag(
groupTasks,
tasksById,
getNestHierarchyTasks,
);
const handleDragStart = useCallback((event: DragStartEvent) => {
setActiveDragId(String(event.active.id));
}, []);
const handleDragCancel = useCallback(() => setActiveDragId(null), []);
const handleDragEnd = useCallback(
(event: DragEndEvent) => {
setActiveDragId(null);
clearActiveDrag();
const { active, over } = event;
if (!over) return;
const decision = resolveSidebarDrop({
@@ -411,7 +446,14 @@ export function TaskTreeDndGroup({
break;
}
},
[groupRootIds, childrenByParent, onReorderGroup, onReorderSubtasks, onNestTask],
[
clearActiveDrag,
groupRootIds,
childrenByParent,
onReorderGroup,
onReorderSubtasks,
onNestTask,
],
);
const collisionDetection = useCallback<CollisionDetection>((args) => {
@@ -432,7 +474,7 @@ export function TaskTreeDndGroup({
collisionDetection={collisionDetection}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragCancel={handleDragCancel}
onDragCancel={clearActiveDrag}
>
{children(nestTargetIds, activeDragId)}
</DndContext>
@@ -1,6 +1,6 @@
"use client";
import { memo, useCallback, useMemo } from "react";
import { memo, useCallback, useLayoutEffect, useMemo, useRef } from "react";
import { countGroupTasks, type SidebarGroup } from "@/lib/sidebar/apply-view";
import {
SortableTaskLevel,
@@ -14,7 +14,14 @@ import type { TaskSwitcherItem } from "./task-switcher-types";
export type TaskRowBaseProps = Omit<
TaskRowProps,
"task" | "subtaskToggle" | "isPinned" | "isSubTask" | "depth"
| "task"
| "nestCandidateTasks"
| "getNestCandidateTasks"
| "getNestHierarchyTasks"
| "subtaskToggle"
| "isPinned"
| "isSubTask"
| "depth"
>;
type TaskTreeContext = {
@@ -23,6 +30,8 @@ type TaskTreeContext = {
onToggleSubtasks?: (parentTaskId: string) => void;
pinnedSet: Set<string>;
rowProps: TaskRowBaseProps;
getNestCandidateTasks: () => TaskSwitcherItem[];
getNestHierarchyTasks?: () => TaskSwitcherItem[] | undefined;
onReorderGroup?: (groupTaskIds: string[]) => void;
onReorderSubtasks?: (parentTaskId: string, orderedSubtaskIds: string[]) => void;
onNestTask?: (taskId: string, parentTaskId: string) => void;
@@ -74,6 +83,8 @@ function taskTreeNodeEqual(previous: TaskTreeNodeProps, next: TaskTreeNodeProps)
previous.depth !== next.depth ||
previous.isDraggable !== next.isDraggable ||
previous.ctx.rowProps !== next.ctx.rowProps ||
previous.ctx.getNestCandidateTasks !== next.ctx.getNestCandidateTasks ||
previous.ctx.getNestHierarchyTasks !== next.ctx.getNestHierarchyTasks ||
previous.ctx.onToggleSubtasks !== next.ctx.onToggleSubtasks ||
previous.ctx.onReorderGroup !== next.ctx.onReorderGroup ||
previous.ctx.onReorderSubtasks !== next.ctx.onReorderSubtasks ||
@@ -125,6 +136,8 @@ const TaskTreeNode = memo(function TaskTreeNode({
subtaskToggle={toggleInfo}
isPinned={isRoot && ctx.pinnedSet.has(task.id)}
{...ctx.rowProps}
getNestCandidateTasks={ctx.getNestCandidateTasks}
getNestHierarchyTasks={ctx.getNestHierarchyTasks}
onTogglePin={isRoot ? ctx.rowProps.onTogglePin : undefined}
/>
{isNestTarget && <NestDropZone taskId={task.id} title={task.title} />}
@@ -184,6 +197,7 @@ function getReorderHandler(parentTaskId: string | null, ctx: TaskTreeContext) {
export type GroupSectionProps = {
group: SidebarGroup;
subTasksByParentId: Map<string, TaskSwitcherItem[]>;
getNestHierarchyTasks?: () => TaskSwitcherItem[] | undefined;
rowProps: TaskRowBaseProps;
pinnedSet: Set<string>;
isCollapsed: boolean;
@@ -230,6 +244,7 @@ function groupSectionEqual(previous: GroupSectionProps, next: GroupSectionProps)
if (
previous.group !== next.group ||
previous.rowProps !== next.rowProps ||
previous.getNestHierarchyTasks !== next.getNestHierarchyTasks ||
previous.pinnedSet !== next.pinnedSet ||
previous.isCollapsed !== next.isCollapsed ||
previous.onToggleGroup !== next.onToggleGroup ||
@@ -286,6 +301,7 @@ function flattenGroupTasks(
export const GroupSection = memo(function GroupSection({
group,
subTasksByParentId,
getNestHierarchyTasks,
rowProps,
pinnedSet,
isCollapsed,
@@ -302,6 +318,11 @@ export const GroupSection = memo(function GroupSection({
() => flattenGroupTasks(group.tasks, subTasksByParentId),
[group.tasks, subTasksByParentId],
);
const groupTasksRef = useRef(groupTasks);
useLayoutEffect(() => {
groupTasksRef.current = groupTasks;
}, [groupTasks]);
const getNestCandidateTasks = useCallback(() => groupTasksRef.current, []);
const renderTree = (nestTargetIds: Set<string>) => {
if (isCollapsed) return null;
@@ -311,6 +332,8 @@ export const GroupSection = memo(function GroupSection({
onToggleSubtasks,
pinnedSet,
rowProps,
getNestCandidateTasks,
getNestHierarchyTasks,
onReorderGroup,
onReorderSubtasks,
onNestTask,
@@ -333,6 +356,7 @@ export const GroupSection = memo(function GroupSection({
)}
<TaskTreeDndGroup
groupTasks={groupTasks}
getNestHierarchyTasks={getNestHierarchyTasks}
onReorderGroup={onReorderGroup}
onReorderSubtasks={onReorderSubtasks}
onNestTask={onNestTask}
@@ -62,6 +62,7 @@ export type TaskSwitcherItem = {
lastActivityAt?: string;
createdAt?: string;
isArchived?: boolean;
isFromOffice?: boolean;
primarySessionId?: string | null;
hasPendingClarification?: boolean;
hasPendingPermission?: boolean;
@@ -81,6 +82,8 @@ export type TaskSwitcherItem = {
export type TaskSwitcherProps = {
grouped: GroupedSidebarList;
/** Complete unfiltered task set used only to validate hierarchy constraints. */
nestHierarchyTasks?: TaskSwitcherItem[];
workflows?: TaskMoveWorkflow[];
stepsByWorkflowId?: Record<string, StepDef[]>;
activeTaskId: string | null;
+9 -1
View File
@@ -158,12 +158,14 @@ function buildGroupSectionProps(
pinnedSet: Set<string>;
collapsedSet: Set<string>;
showHeader: boolean;
getNestHierarchyTasks: () => TaskSwitcherProps["nestHierarchyTasks"];
},
): GroupSectionProps {
const { group, rowProps, pinnedSet, collapsedSet, showHeader } = options;
const { group, rowProps, pinnedSet, collapsedSet, showHeader, getNestHierarchyTasks } = options;
return {
group,
subTasksByParentId: grouped.subTasksByParentId,
getNestHierarchyTasks,
rowProps,
pinnedSet,
isCollapsed: collapsedSet.has(group.key),
@@ -218,6 +220,11 @@ export const TaskSwitcher = memo(function TaskSwitcher(props: TaskSwitcherProps)
() => new Set(props.collapsedGroupKeys ?? []),
[props.collapsedGroupKeys],
);
const nestHierarchyTasksRef = useRef(props.nestHierarchyTasks);
useLayoutEffect(() => {
nestHierarchyTasksRef.current = props.nestHierarchyTasks;
}, [props.nestHierarchyTasks]);
const getNestHierarchyTasks = useMemo(() => () => nestHierarchyTasksRef.current, []);
if (isLoading) return <TaskSwitcherSkeleton />;
@@ -258,6 +265,7 @@ export const TaskSwitcher = memo(function TaskSwitcher(props: TaskSwitcherProps)
pinnedSet,
collapsedSet,
showHeader: showHeaders,
getNestHierarchyTasks,
})}
/>
))}