⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(projects): rework project drag-and-drop interaction
Andrejc6046d8b5d78
diff --git a/apps/web/src/components/nav-projects.tsx b/apps/web/src/components/nav-projects.tsxindex 60f3b0f18..cc59759f7 100644--- a/apps/web/src/components/nav-projects.tsx+++ b/apps/web/src/components/nav-projects.tsx@@ -2,16 +2,20 @@ import {closestCenter,DndContext,type DragEndEvent,- KeyboardSensor,+ DragOverlay,+ type DragStartEvent,MouseSensor,TouchSensor,useSensor,useSensors,} from "@dnd-kit/core";+import {+ restrictToFirstScrollableAncestor,+ restrictToVerticalAxis,+} from "@dnd-kit/modifiers";import {arrayMove,SortableContext,- sortableKeyboardCoordinates,useSortable,verticalListSortingStrategy,} from "@dnd-kit/sortable";@@ -22,12 +26,12 @@ import {ChevronRight,Folder,Forward,- GripVertical,MoreHorizontal,Settings,Trash2,} from "lucide-react";import { type CSSProperties, type ReactNode, useState } from "react";+import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";import {Collapsible,@@ -78,45 +82,32 @@ function SortableProjectItem({canReorder: boolean;children: ReactNode;}) {- const { t } = useTranslation();- const {- attributes,- listeners,- setNodeRef,- setActivatorNodeRef,- transform,- transition,- isDragging,- } = useSortable({ id, disabled: !canReorder });+ const { listeners, setNodeRef, transform, transition, isDragging } =+ useSortable({+ id,+ disabled: !canReorder,+ // The reorder already moves the row; animating the index change too+ // replays the same move from a stale offset.+ animateLayoutChanges: () => false,+ // dnd-kit defaults to `ease`; this is the app's curve.+ transition: { duration: 200, easing: "var(--ease-out)" },+ });const style: CSSProperties = {transform: CSS.Transform.toString(transform),transition,- opacity: isDragging ? 0.5 : 1,};return (- <SidebarMenuItem ref={setNodeRef} style={style}>- {canReorder && (- // Only the handle activates a drag. Spreading the sortable props over- // the whole item would make it a role="button" tab stop wrapping the- // menu and dropdown buttons, and would let Enter start a drag.- // The handle stays visible below `md`: `TouchSensor` is registered, and- // touch devices never hover, so hiding it there strands the affordance.- <button- type="button"- ref={setActivatorNodeRef}- className="absolute top-1.5 end-6 z-10 flex aspect-square w-5 cursor-grab items-center justify-center rounded-lg p-0 text-sidebar-foreground opacity-100 outline-hidden md:opacity-0 ring-sidebar-ring transition-opacity hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:opacity-100 focus-visible:ring-2 group-data-[collapsible=icon]:hidden group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100"- onClick={(event) => event.stopPropagation()}- {...attributes}- {...listeners}- >- <GripVertical className="h-4 w-4" />- <span className="sr-only">- {t("workspace:projects.reorderHandle")}- </span>- </button>- )}+ // `listeners` without `attributes`: the latter puts role="button" and a tab+ // stop on the row, wrapping the link and the dropdown inside it.+ <SidebarMenuItem+ ref={setNodeRef}+ style={style}+ data-kaneo-sortable=""+ className={isDragging ? "opacity-0" : undefined}+ {...(canReorder ? listeners : {})}+ >{children}</SidebarMenuItem>);@@ -131,7 +122,7 @@ export function NavProjects() {});const queryClient = useQueryClient();const { mutateAsync: deleteProject } = useDeleteProject();- const { mutate: reorderProjects } = useReorderProjects();+ const reorderProjects = useReorderProjects();const { canCreateProjects, canDeleteProjects, canUpdateProjects } =useWorkspacePermission();const canCreate = canCreateProjects();@@ -152,6 +143,13 @@ export function NavProjects() {const [projectToDeleteId, setProjectToDeleteID] = useState<string | null>(null,);+ const [draggingProjectId, setDraggingProjectId] = useState<string | null>(+ null,+ );++ const draggingProject = projects?.find(+ (project) => project.id === draggingProjectId,+ );const isCurrentProject = (projectId: string) => {return (@@ -169,8 +167,8 @@ export function NavProjects() {});};- // Distance/delay thresholds keep a tap on the handle from being read as a- // drag; permission gating lives on the handle and `useSortable`'s `disabled`.+ // Below these thresholds the row is still a link and the sidebar still+ // scrolls; above them the gesture becomes a drag.const sensors = useSensors(useSensor(MouseSensor, {activationConstraint: { distance: 8 },@@ -178,16 +176,23 @@ export function NavProjects() {useSensor(TouchSensor, {activationConstraint: { delay: 200, tolerance: 8 },}),- // Without the sortable coordinate getter, a keyboard drag nudges a virtual- // pointer by fixed pixel steps instead of moving between list positions.- useSensor(KeyboardSensor, {- coordinateGetter: sortableKeyboardCoordinates,- }),);+ const handleDragStart = (event: DragStartEvent) => {+ document.body.classList.add("kaneo-dragging");+ setDraggingProjectId(String(event.active.id));+ };++ const endDrag = () => {+ document.body.classList.remove("kaneo-dragging");+ setDraggingProjectId(null);+ };+const handleDragEnd = (event: DragEndEvent) => {const { active, over } = event;+ endDrag();+if (!over || active.id === over.id || !projects || !workspace) return;const oldIndex = projects.findIndex((project) => project.id === active.id);@@ -197,20 +202,11 @@ export function NavProjects() {const reordered = arrayMove(projects, oldIndex, newIndex);- reorderProjects(- {- workspaceId: workspace.id,- projects: reordered.map((project, index) => ({- id: project.id,- position: index,- })),+ reorderProjects(workspace.id, reordered, {+ onError: () => {+ toast.error(t("workspace:projects.reorderError"));},- {- onError: () => {- toast.error(t("workspace:projects.reorderError"));- },- },- );+ });};if (!workspace) return null;@@ -230,12 +226,18 @@ export function NavProjects() {</CollapsibleTrigger><CollapsiblePanel><SidebarGroupContent>- <SidebarMenu className="gap-0.5">- <DndContext- sensors={sensors}- collisionDetection={closestCenter}- onDragEnd={handleDragEnd}- >+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ modifiers={[+ restrictToVerticalAxis,+ restrictToFirstScrollableAncestor,+ ]}+ onDragStart={handleDragStart}+ onDragEnd={handleDragEnd}+ onDragCancel={endDrag}+ >+ <SidebarMenu className="gap-0.5"><SortableContextitems={projects?.map((project) => project.id) ?? []}strategy={verticalListSortingStrategy}@@ -261,6 +263,11 @@ export function NavProjects() {render={<buttontype="button"+ // The row is the drag source; this press+ // must not reach it.+ onPointerDown={(event) =>+ event.stopPropagation()+ }className="absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground after:-inset-2 after:absolute md:after:hidden peer-data-[size=sm]/menu-button:top-1 peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 group-data-[collapsible=icon]:hidden group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0"/>}@@ -339,20 +346,32 @@ export function NavProjects() {);})}</SortableContext>- </DndContext>- {canCreate && (- <SidebarMenuItem className="mt-1">- <SidebarMenuButton- size="default"- className="h-8 ps-3.5 text-sm hover:bg-transparent hover:text-sidebar-accent-foreground active:bg-transparent"- onClick={() => setIsCreateProjectModalOpen(true)}- >- <span>{t("navigation:projectList.addProject")}</span>- </SidebarMenuButton>- </SidebarMenuItem>+ {canCreate && (+ <SidebarMenuItem className="mt-1">+ <SidebarMenuButton+ size="default"+ className="h-8 ps-3.5 text-sm hover:bg-transparent hover:text-sidebar-accent-foreground active:bg-transparent"+ onClick={() => setIsCreateProjectModalOpen(true)}+ >+ <span>{t("navigation:projectList.addProject")}</span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ )}+ </SidebarMenu>++ {/* Portalled: `SidebarContent` is `overflow-auto` and clips it. */}+ {createPortal(+ <DragOverlay dropAnimation={null}>+ {draggingProject ? (+ <div className="flex h-8 w-(--sidebar-width) max-w-64 items-center rounded-lg border bg-sidebar not-dark:bg-clip-padding ps-3.5 pe-2 text-sm text-sidebar-accent-foreground shadow-lg/5">+ <span className="truncate">{draggingProject.name}</span>+ </div>+ ) : null}+ </DragOverlay>,+ document.body,)}- </SidebarMenu>+ </DndContext></SidebarGroupContent></CollapsiblePanel></SidebarGroup>diff --git a/apps/web/src/hooks/mutations/project/use-reorder-projects.ts b/apps/web/src/hooks/mutations/project/use-reorder-projects.tsindex e1e1b7d5c..af5010276 100644--- a/apps/web/src/hooks/mutations/project/use-reorder-projects.ts+++ b/apps/web/src/hooks/mutations/project/use-reorder-projects.ts@@ -1,54 +1,73 @@-import { useMutation, useQueryClient } from "@tanstack/react-query";+import {+ type MutateOptions,+ useMutation,+ useQueryClient,+} from "@tanstack/react-query";+import { useCallback } from "react";import type getProjects from "@/fetchers/project/get-projects";import reorderProjects from "@/fetchers/project/reorder-projects";-type ProjectList = Awaited<ReturnType<typeof getProjects>>;+type ProjectList = NonNullable<Awaited<ReturnType<typeof getProjects>>>;type ReorderProjectsVariables = {workspaceId: string;- projects: Array<{ id: string; position: number }>;+ projects: ProjectList;+ previousProjects?: ProjectList;};function useReorderProjects() {const queryClient = useQueryClient();- return useMutation({+ const mutation = useMutation({mutationFn: ({ workspaceId, projects }: ReorderProjectsVariables) =>- reorderProjects(workspaceId, projects),- // Reordering is a pure UI gesture — without an optimistic write the list- // snaps back to the server order until the refetch lands.- onMutate: async ({ workspaceId, projects }: ReorderProjectsVariables) => {- const queryKey = ["projects", workspaceId];- await queryClient.cancelQueries({ queryKey });-- const previousProjects = queryClient.getQueryData<ProjectList>(queryKey);-+ reorderProjects(+ workspaceId,+ projects.map((project, index) => ({ id: project.id, position: index })),+ ),+ onError: (_error, { workspaceId, previousProjects }) => {if (previousProjects) {- const positionById = new Map(- projects.map(({ id, position }) => [id, position]),- );-- queryClient.setQueryData<ProjectList>(- queryKey,- [...previousProjects].sort(- (a, b) =>- (positionById.get(a.id) ?? a.position) -- (positionById.get(b.id) ?? b.position),- ),- );- }-- return { queryKey, previousProjects };- },- onError: (_error, _variables, context) => {- if (context?.previousProjects) {- queryClient.setQueryData(context.queryKey, context.previousProjects);+ queryClient.setQueryData(["projects", workspaceId], previousProjects);}},onSettled: (_data, _error, { workspaceId }) => {queryClient.invalidateQueries({ queryKey: ["projects", workspaceId] });},});++ // Writes the cache here rather than in `onMutate`, which sits behind an await+ // and lands a render later than dnd-kit's own state clear.+ const reorder = useCallback(+ (+ workspaceId: string,+ orderedProjects: ProjectList,+ options?: MutateOptions<unknown, Error, ReorderProjectsVariables>,+ ) => {+ const queryKey = ["projects", workspaceId];+ const previousProjects = queryClient.getQueryData<ProjectList>(queryKey);++ queryClient.setQueryData<ProjectList>(+ queryKey,+ // Positions rewritten, not just the array order, or a second drag+ // before the refetch sorts new indices against stale ones.+ orderedProjects.map((project, index) => ({+ ...project,+ position: index,+ })),+ );++ // After the write, never before: awaiting an in-flight abort first would+ // paint the old order in the gap.+ queryClient.cancelQueries({ queryKey });++ mutation.mutate(+ { workspaceId, projects: orderedProjects, previousProjects },+ options,+ );+ },+ [queryClient, mutation],+ );++ return reorder;}export default useReorderProjects;diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex d4be617e3..96cafc8a6 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -59,6 +59,12 @@ input:-webkit-autofill:active {[data-slot="sidebar-menu-badge"] {transition: none !important;}++ /* dnd-kit writes the shuffle transition inline, so this needs !important. The+ dragged element still tracks the pointer; only the reflow is neutralized. */+ [data-kaneo-sortable] {+ transition: none !important;+ }}@@ -1341,4 +1347,10 @@ input:-webkit-autofill:active {background: color-mix(in srgb, var(--primary) 18%, transparent);}+ /* Descendants too, or the cursor reverts to that of the row under it. */+ body.kaneo-dragging,+ body.kaneo-dragging * {+ cursor: grabbing !important;+ }+}diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/index.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/index.tsxindex 2148c0ca8..0395d5525 100644--- a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/index.tsx+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/index.tsx@@ -2,23 +2,31 @@ import {closestCenter,DndContext,type DragEndEvent,- KeyboardSensor,MouseSensor,TouchSensor,useSensor,useSensors,} from "@dnd-kit/core";+import {+ restrictToParentElement,+ restrictToVerticalAxis,+} from "@dnd-kit/modifiers";import {arrayMove,SortableContext,- sortableKeyboardCoordinates,useSortable,verticalListSortingStrategy,} from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { createFileRoute, useNavigate } from "@tanstack/react-router";-import { GripVertical, LayoutGrid, Plus } from "lucide-react";-import { type CSSProperties, type ReactNode, useState } from "react";+import { LayoutGrid, Plus } from "lucide-react";+import {+ type CSSProperties,+ type ReactNode,+ useEffect,+ useMemo,+ useState,+} from "react";import { useTranslation } from "react-i18next";import WorkspaceLayout from "@/components/common/workspace-layout";import PageTitle from "@/components/page-title";@@ -51,6 +59,7 @@ import { useRegisterShortcuts } from "@/hooks/use-keyboard-shortcuts";import { useWorkspacePermission } from "@/hooks/use-workspace-permission";import { formatDateMedium } from "@/lib/format";import { toast } from "@/lib/toast";+import { cn } from "@/lib/utils";export const Route = createFileRoute("/_layout/_authenticated/dashboard/workspace/$workspaceId/",@@ -69,51 +78,44 @@ function SortableProjectRow({onClick: () => void;children: ReactNode;}) {- const { t } = useTranslation();const {- attributes,listeners,setNodeRef,- setActivatorNodeRef,transform,transition,isDragging,- } = useSortable({ id, disabled: !canReorder });+ isSorting,+ } = useSortable({+ id,+ disabled: !canReorder,+ // The reorder already moves the row; animating the index change too+ // replays the same move from a stale offset.+ animateLayoutChanges: () => false,+ // dnd-kit defaults to `ease`; this is the app's curve.+ transition: { duration: 200, easing: "var(--ease-out)" },+ });const style: CSSProperties = {transform: CSS.Transform.toString(transform),- transition,- opacity: isDragging ? 0.5 : 1,+ // Only while a drag is live, or the dropped row eases back from the drop+ // point over a list that has already reordered.+ transition: isSorting ? transition : undefined,};return (+ // `listeners` without `attributes`: the latter puts role="button" and a tab+ // stop on the row.<TableRowref={setNodeRef}style={style}- className="group/row cursor-pointer"+ data-kaneo-sortable=""+ className={cn(+ "group/row cursor-pointer",+ isDragging && "relative z-10 bg-muted shadow-md",+ )}onClick={onClick}+ {...(canReorder ? listeners : {})}>- <TableCell className="w-8 py-3 pe-0">- {canReorder && (- // The row itself navigates on click, so only the handle activates a- // drag. It stays visible below `md`: `TouchSensor` is registered, and- // touch devices never hover, so hiding it there strands the- // affordance.- <button- type="button"- ref={setActivatorNodeRef}- className="flex cursor-grab items-center text-muted-foreground opacity-100 transition-opacity md:opacity-0 focus-visible:opacity-100 group-hover/row:opacity-100 hover:text-foreground"- onClick={(event) => event.stopPropagation()}- {...attributes}- {...listeners}- >- <GripVertical className="h-4 w-4" />- <span className="sr-only">- {t("workspace:projects.reorderHandle")}- </span>- </button>- )}- </TableCell>{children}</TableRow>);@@ -127,13 +129,41 @@ function RouteComponent() {const { data: projects, isLoading } = useGetProjects({workspaceId,});- const { mutate: reorderProjects } = useReorderProjects();+ const reorderProjects = useReorderProjects();++ // React state, not the query cache: dnd-kit clears its transforms with a+ // setState in the same handler, while a cache write notifies a task later,+ // leaving a frame with the transforms gone and the rows not yet moved.+ const [droppedOrder, setDroppedOrder] = useState<string[] | null>(null);++ const orderedProjects = useMemo(() => {+ if (!projects || !droppedOrder) return projects;++ const rank = new Map(droppedOrder.map((id, index) => [id, index]));++ return [...projects].sort(+ (a, b) =>+ (rank.get(a.id) ?? Number.MAX_SAFE_INTEGER) -+ (rank.get(b.id) ?? Number.MAX_SAFE_INTEGER),+ );+ }, [projects, droppedOrder]);++ // Released once the server agrees, or a reorder made elsewhere stays pinned.+ useEffect(() => {+ if (!droppedOrder || !projects) return;+ if (projects.map((project) => project.id).join() === droppedOrder.join()) {+ setDroppedOrder(null);+ }+ }, [projects, droppedOrder]);+const { canCreateProjects, canUpdateProjects } = useWorkspacePermission();const canCreate = canCreateProjects();// Matches the API, which gates /project/reorder on `project: ["update"]`// alone — not the create+update+delete bundle.const canReorder = canUpdateProjects();+ // Below these thresholds the row is still a link and the page still scrolls;+ // above them the gesture becomes a drag.const sensors = useSensors(useSensor(MouseSensor, {activationConstraint: { distance: 8 },@@ -141,39 +171,38 @@ function RouteComponent() {useSensor(TouchSensor, {activationConstraint: { delay: 200, tolerance: 8 },}),- // Without the sortable coordinate getter, a keyboard drag nudges a virtual- // pointer by fixed pixel steps instead of moving between list positions.- useSensor(KeyboardSensor, {- coordinateGetter: sortableKeyboardCoordinates,- }),);+ const handleDragStart = () => {+ document.body.classList.add("kaneo-dragging");+ };+const handleDragEnd = (event: DragEndEvent) => {const { active, over } = event;- if (!over || active.id === over.id || !projects) return;+ document.body.classList.remove("kaneo-dragging");- const oldIndex = projects.findIndex((project) => project.id === active.id);- const newIndex = projects.findIndex((project) => project.id === over.id);+ if (!over || active.id === over.id || !orderedProjects) return;++ const oldIndex = orderedProjects.findIndex(+ (project) => project.id === active.id,+ );+ const newIndex = orderedProjects.findIndex(+ (project) => project.id === over.id,+ );if (oldIndex === -1 || newIndex === -1) return;- const reordered = arrayMove(projects, oldIndex, newIndex);+ const reordered = arrayMove(orderedProjects, oldIndex, newIndex);- reorderProjects(- {- workspaceId,- projects: reordered.map((project, index) => ({- id: project.id,- position: index,- })),- },- {- onError: () => {- toast.error(t("workspace:projects.reorderError"));- },+ setDroppedOrder(reordered.map((project) => project.id));++ reorderProjects(workspaceId, reordered, {+ onError: () => {+ setDroppedOrder(null);+ toast.error(t("workspace:projects.reorderError"));},- );+ });};const handleCreateProject = () => {@@ -219,7 +248,6 @@ function RouteComponent() {<Table><TableHeader><TableRow>- <TableHead className="w-8" /><TableHead className="text-foreground font-medium">{t("workspace:projects.title")}</TableHead>@@ -237,7 +265,6 @@ function RouteComponent() {<TableBody>{[1, 2, 3].map((i) => (<TableRow key={i}>- <TableCell className="w-8 py-3 pe-0" /><TableCell className="py-3"><div className="flex items-center gap-3"><Skeleton className="h-5 w-5" />@@ -335,12 +362,14 @@ function RouteComponent() {<DndContextsensors={sensors}collisionDetection={closestCenter}+ modifiers={[restrictToVerticalAxis, restrictToParentElement]}+ onDragStart={handleDragStart}onDragEnd={handleDragEnd}+ onDragCancel={() => document.body.classList.remove("kaneo-dragging")}><Table><TableHeader className="p-4"><TableRow>- <TableHead className="w-8" /><TableHead className="text-foreground font-medium">{t("workspace:projects.title")}</TableHead>@@ -357,10 +386,10 @@ function RouteComponent() {</TableHeader><TableBody><SortableContext- items={projects?.map((project) => project.id) ?? []}+ items={orderedProjects?.map((project) => project.id) ?? []}strategy={verticalListSortingStrategy}>- {projects?.map((project) => {+ {orderedProjects?.map((project) => {if (!project || !project.id || !project.statistics)return null;