[WEB-1416] chore: Refactor project sidebar dnd and remove @hello-pangea dnd (#4581)

* upgrade cmdk version to 1.0 to fix a critical issue

* project side bar dnd

* add some comments

* slight logic change for highlighting on drop
This commit is contained in:
rahulramesha 2024-05-27 19:20:26 +05:30 committed by GitHub
parent 44f743d52c
commit b93fa4a340
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 280 additions and 260 deletions

View file

@ -1,8 +1,13 @@
import { useRef, useState } from "react";
import { DraggableProvided, DraggableStateSnapshot } from "@hello-pangea/dnd";
import { useEffect, useRef, useState } from "react";
import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine";
import { draggable, dropTargetForElements } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
import { pointerOutsideOfPreview } from "@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview";
import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview";
import { attachInstruction, extractInstruction } from "@atlaskit/pragmatic-drag-and-drop-hitbox/tree-item";
import { observer } from "mobx-react";
import Link from "next/link";
import { useRouter } from "next/router";
import { createRoot } from "react-dom/client";
import {
MoreVertical,
PenSquare,
@ -28,6 +33,7 @@ import {
ContrastIcon,
LayersIcon,
setPromiseToast,
DropIndicator,
} from "@plane/ui";
import { LeaveProjectModal, ProjectLogo, PublishProjectModal } from "@/components/project";
import { EUserProjectRoles } from "@/constants/project";
@ -36,17 +42,23 @@ import { cn } from "@/helpers/common.helper";
import { useAppTheme, useEventTracker, useProject } from "@/hooks/store";
import useOutsideClickDetector from "@/hooks/use-outside-click-detector";
import { usePlatformOS } from "@/hooks/use-platform-os";
import { HIGHLIGHT_CLASS, highlightIssueOnDrop } from "../issues/issue-layouts/utils";
// helpers
// components
type Props = {
projectId: string;
provided?: DraggableProvided;
snapshot?: DraggableStateSnapshot;
handleCopyText: () => void;
shortContextMenu?: boolean;
handleOnProjectDrop?: (
sourceId: string | undefined,
destinationId: string | undefined,
shouldDropAtEnd: boolean
) => void;
projectListType: "JOINED" | "FAVORITES";
disableDrag?: boolean;
disableDrop?: boolean;
isLastChild: boolean;
};
const navigation = (workspaceSlug: string, projectId: string) => [
@ -89,7 +101,8 @@ const navigation = (workspaceSlug: string, projectId: string) => [
export const ProjectSidebarListItem: React.FC<Props> = observer((props) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { projectId, provided, snapshot, handleCopyText, shortContextMenu = false, disableDrag } = props;
const { projectId, handleCopyText, disableDrag, disableDrop, isLastChild, handleOnProjectDrop, projectListType } =
props;
// store hooks
const { sidebarCollapsed: isCollapsed, toggleSidebar } = useAppTheme();
const { setTrackElement } = useEventTracker();
@ -99,8 +112,12 @@ export const ProjectSidebarListItem: React.FC<Props> = observer((props) => {
const [leaveProjectModalOpen, setLeaveProjectModal] = useState(false);
const [publishModalOpen, setPublishModal] = useState(false);
const [isMenuActive, setIsMenuActive] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const [instruction, setInstruction] = useState<"DRAG_OVER" | "DRAG_BELOW" | undefined>(undefined);
// refs
const actionSectionRef = useRef<HTMLDivElement | null>(null);
const projectRef = useRef<HTMLDivElement | null>(null);
const dragHandleRef = useRef<HTMLButtonElement | null>(null);
// router
const router = useRouter();
const { workspaceSlug, projectId: URLProjectId } = router.query;
@ -160,7 +177,97 @@ export const ProjectSidebarListItem: React.FC<Props> = observer((props) => {
}
};
useEffect(() => {
const element = projectRef.current;
const dragHandleElement = dragHandleRef.current;
if (!element) return;
return combine(
draggable({
element,
canDrag: () => !disableDrag,
dragHandle: dragHandleElement ?? undefined,
getInitialData: () => ({ id: projectId, dragInstanceId: "PROJECTS" }),
onDragStart: () => {
setIsDragging(true);
},
onDrop: () => {
setIsDragging(false);
},
onGenerateDragPreview: ({ nativeSetDragImage }) => {
// Add a custom drag image
setCustomNativeDragPreview({
getOffset: pointerOutsideOfPreview({ x: "0px", y: "0px" }),
render: ({ container }) => {
const root = createRoot(container);
root.render(
<div className="rounded flex items-center bg-custom-background-100 text-sm p-1 pr-2">
<div className="flex items-center h-7 w-5 grid place-items-center flex-shrink-0">
{project && <ProjectLogo logo={project?.logo_props} />}
</div>
<p className="truncate text-custom-sidebar-text-200">{project?.name}</p>
</div>
);
return () => root.unmount();
},
nativeSetDragImage,
});
},
}),
dropTargetForElements({
element,
canDrop: ({ source }) =>
!disableDrop && source?.data?.id !== projectId && source?.data?.dragInstanceId === "PROJECTS",
getData: ({ input, element }) => {
const data = { id: projectId };
// attach instruction for last in list
return attachInstruction(data, {
input,
element,
currentLevel: 0,
indentPerLevel: 0,
mode: isLastChild ? "last-in-group" : "standard",
});
},
onDrag: ({ self }) => {
const extractedInstruction = extractInstruction(self?.data)?.type;
// check if the highlight is to be shown above or below
setInstruction(
extractedInstruction
? extractedInstruction === "reorder-below" && isLastChild
? "DRAG_BELOW"
: "DRAG_OVER"
: undefined
);
},
onDragLeave: () => {
setInstruction(undefined);
},
onDrop: ({ self, source }) => {
setInstruction(undefined);
const extractedInstruction = extractInstruction(self?.data)?.type;
const currentInstruction = extractedInstruction
? extractedInstruction === "reorder-below" && isLastChild
? "DRAG_BELOW"
: "DRAG_OVER"
: undefined;
if (!currentInstruction) return;
const sourceId = source?.data?.id as string | undefined;
const destinationId = self?.data?.id as string | undefined;
handleOnProjectDrop && handleOnProjectDrop(sourceId, destinationId, currentInstruction === "DRAG_BELOW");
highlightIssueOnDrop(`sidebar-${sourceId}-${projectListType}`);
},
})
);
}, [projectRef?.current, dragHandleRef?.current, projectId, isLastChild, projectListType, handleOnProjectDrop]);
useOutsideClickDetector(actionSectionRef, () => setIsMenuActive(false));
useOutsideClickDetector(projectRef, () => projectRef?.current?.classList?.remove(HIGHLIGHT_CLASS));
if (!project) return null;
@ -168,48 +275,47 @@ export const ProjectSidebarListItem: React.FC<Props> = observer((props) => {
<>
<PublishProjectModal isOpen={publishModalOpen} project={project} onClose={() => setPublishModal(false)} />
<LeaveProjectModal project={project} isOpen={leaveProjectModalOpen} onClose={handleLeaveProjectModalClose} />
<Disclosure key={`${project.id} ${URLProjectId}`} defaultOpen={URLProjectId === project.id}>
<Disclosure key={`${project.id}_${URLProjectId}`} ref={projectRef} defaultOpen={URLProjectId === project.id}>
{({ open }) => (
<>
<div
id={`sidebar-${projectId}-${projectListType}`}
className={cn("rounded relative", { "bg-custom-sidebar-background-80 opacity-60": isDragging })}
>
<DropIndicator classNames="absolute top-0" isVisible={instruction === "DRAG_OVER"} />
<div
className={cn(
"group relative flex w-full items-center rounded-md px-2 py-1 text-custom-sidebar-text-100 hover:bg-custom-sidebar-background-80",
"group relative flex w-full items-center rounded-md py-1 text-custom-sidebar-text-100 hover:bg-custom-sidebar-background-80",
{
"opacity-60": snapshot?.isDragging,
"bg-custom-sidebar-background-80": isMenuActive,
"pl-8": disableDrag,
}
)}
>
{provided && !disableDrag && (
{!disableDrag && (
<Tooltip
isMobile={isMobile}
tooltipContent={project.sort_order === null ? "Join the project to rearrange" : "Drag to rearrange"}
position="top-right"
disabled={isDragging}
>
<button
type="button"
className={cn(
"absolute -left-2.5 top-1/2 hidden -translate-y-1/2 rounded p-0.5 text-custom-sidebar-text-400",
"flex opacity-0 rounded text-custom-sidebar-text-400 hover:bg-custom-sidebar-background-80 ml-2",
{
"group-hover:flex": !isCollapsed,
"group-hover:opacity-100": !isCollapsed,
"cursor-not-allowed opacity-60": project.sort_order === null,
flex: isMenuActive,
}
)}
{...provided?.dragHandleProps}
ref={dragHandleRef}
>
<MoreVertical className="h-3.5" />
<MoreVertical className="-ml-3 h-3.5" />
<MoreVertical className="-ml-5 h-3.5" />
</button>
</Tooltip>
)}
<Tooltip
tooltipContent={`${project.name}`}
position="right"
className="ml-2"
disabled={!isCollapsed}
isMobile={isMobile}
>
<Tooltip tooltipContent={`${project.name}`} position="right" disabled={!isCollapsed} isMobile={isMobile}>
<Disclosure.Button
as="div"
className={cn(
@ -220,11 +326,11 @@ export const ProjectSidebarListItem: React.FC<Props> = observer((props) => {
)}
>
<div
className={cn("flex w-full flex-grow items-center gap-1 truncate", {
className={cn("flex w-full flex-grow items-center gap-1 truncate -ml-1", {
"justify-center": isCollapsed,
})}
>
<div className="h-7 w-7 grid place-items-center flex-shrink-0">
<div className="h-7 w-5 grid place-items-center flex-shrink-0">
<ProjectLogo logo={project.logo_props} />
</div>
{!isCollapsed && <p className="truncate text-custom-sidebar-text-200">{project.name}</p>}
@ -380,7 +486,8 @@ export const ProjectSidebarListItem: React.FC<Props> = observer((props) => {
})}
</Disclosure.Panel>
</Transition>
</>
{isLastChild && <DropIndicator isVisible={instruction === "DRAG_BELOW"} />}
</div>
)}
</Disclosure>
</>

View file

@ -1,5 +1,6 @@
import { useState, FC, useRef, useEffect } from "react";
import { DragDropContext, Draggable, DropResult, Droppable } from "@hello-pangea/dnd";
import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine";
import { autoScrollForElements } from "@atlaskit/pragmatic-drag-and-drop-auto-scroll/element";
import { observer } from "mobx-react";
import { useRouter } from "next/router";
import { ChevronDown, ChevronRight, Plus } from "lucide-react";
@ -54,21 +55,28 @@ export const ProjectSidebarList: FC = observer(() => {
});
};
const onDragEnd = (result: DropResult) => {
const { source, destination, draggableId } = result;
if (!destination || !workspaceSlug) return;
if (source.index === destination.index) return;
const handleOnProjectDrop = (
sourceId: string | undefined,
destinationId: string | undefined,
shouldDropAtEnd: boolean
) => {
if (!sourceId || !destinationId || !workspaceSlug) return;
if (sourceId === destinationId) return;
const joinedProjectsList: IProject[] = [];
joinedProjects.map((projectId) => {
const projectDetails = getProjectById(projectId);
if (projectDetails) joinedProjectsList.push(projectDetails);
});
const sourceIndex = joinedProjects.indexOf(sourceId);
const destinationIndex = shouldDropAtEnd ? joinedProjects.length : joinedProjects.indexOf(destinationId);
if (joinedProjectsList.length <= 0) return;
const updatedSortOrder = orderJoinedProjects(source.index, destination.index, draggableId, joinedProjectsList);
const updatedSortOrder = orderJoinedProjects(sourceIndex, destinationIndex, sourceId, joinedProjectsList);
if (updatedSortOrder != undefined)
updateProjectView(workspaceSlug.toString(), draggableId, { sort_order: updatedSortOrder }).catch(() => {
updateProjectView(workspaceSlug.toString(), sourceId, { sort_order: updatedSortOrder }).catch(() => {
setToast({
type: TOAST_TYPE.ERROR,
title: "Error!",
@ -98,7 +106,21 @@ export const ProjectSidebarList: FC = observer(() => {
currentContainerRef.removeEventListener("scroll", handleScroll);
}
};
}, []);
}, [containerRef]);
useEffect(() => {
const element = containerRef.current;
if (!element) return;
return combine(
autoScrollForElements({
element,
canScroll: ({ source }) => source?.data?.dragInstanceId === "PROJECTS",
getAllowedAxis: () => "vertical",
})
);
}, [containerRef]);
return (
<>
@ -123,156 +145,117 @@ export const ProjectSidebarList: FC = observer(() => {
}
)}
>
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="favorite-projects">
{(provided) => (
<div ref={provided.innerRef} {...provided.droppableProps}>
{favoriteProjects && favoriteProjects.length > 0 && (
<Disclosure as="div" className="flex flex-col" defaultOpen>
{({ open }) => (
<>
{!isCollapsed && (
<div className="group flex w-full items-center justify-between rounded p-1.5 text-xs text-custom-sidebar-text-400 hover:bg-custom-sidebar-background-80">
<Disclosure.Button
as="button"
type="button"
className="group flex w-full items-center gap-1 whitespace-nowrap rounded px-1.5 text-left text-sm font-semibold text-custom-sidebar-text-400 hover:bg-custom-sidebar-background-80"
>
Favorites
{open ? (
<ChevronDown className="h-3.5 w-3.5" />
) : (
<ChevronRight className="h-3.5 w-3.5" />
)}
</Disclosure.Button>
{isAuthorizedUser && (
<button
className="opacity-0 group-hover:opacity-100"
onClick={() => {
setTrackElement("APP_SIDEBAR_FAVORITES_BLOCK");
setIsFavoriteProjectCreate(true);
setIsProjectModalOpen(true);
}}
>
<Plus className="h-3 w-3" />
</button>
)}
</div>
)}
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform scale-95 opacity-0"
enterTo="transform scale-100 opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform scale-100 opacity-100"
leaveTo="transform scale-95 opacity-0"
<div>
{favoriteProjects && favoriteProjects.length > 0 && (
<Disclosure as="div" className="flex flex-col" defaultOpen>
{({ open }) => (
<>
{!isCollapsed && (
<div className="group flex w-full items-center justify-between rounded p-1.5 text-xs text-custom-sidebar-text-400 hover:bg-custom-sidebar-background-80">
<Disclosure.Button
as="button"
type="button"
className="group flex w-full items-center gap-1 whitespace-nowrap rounded px-1.5 text-left text-sm font-semibold text-custom-sidebar-text-400 hover:bg-custom-sidebar-background-80"
>
Favorites
{open ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
</Disclosure.Button>
{isAuthorizedUser && (
<button
className="opacity-0 group-hover:opacity-100"
onClick={() => {
setTrackElement("APP_SIDEBAR_FAVORITES_BLOCK");
setIsFavoriteProjectCreate(true);
setIsProjectModalOpen(true);
}}
>
<Disclosure.Panel as="div" className="space-y-2">
{favoriteProjects.map((projectId, index) => (
<Draggable
key={projectId}
draggableId={projectId}
index={index}
// FIXME refactor the Draggable to a different component
//isDragDisabled={!project.is_member}
>
{(provided, snapshot) => (
<div ref={provided.innerRef} {...provided.draggableProps}>
<ProjectSidebarListItem
key={projectId}
projectId={projectId}
provided={provided}
snapshot={snapshot}
handleCopyText={() => handleCopyText(projectId)}
shortContextMenu
disableDrag
/>
</div>
)}
</Draggable>
))}
</Disclosure.Panel>
</Transition>
{provided.placeholder}
</>
)}
</Disclosure>
)}
</div>
)}
</Droppable>
</DragDropContext>
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="joined-projects">
{(provided) => (
<div ref={provided.innerRef} {...provided.droppableProps}>
{joinedProjects && joinedProjects.length > 0 && (
<Disclosure as="div" className="flex flex-col" defaultOpen>
{({ open }) => (
<>
{!isCollapsed && (
<div className="group flex w-full items-center justify-between rounded p-1.5 text-xs text-custom-sidebar-text-400 hover:bg-custom-sidebar-background-80">
<Disclosure.Button
as="button"
type="button"
className="group flex w-full items-center gap-1 whitespace-nowrap rounded px-1.5 text-left text-sm font-semibold text-custom-sidebar-text-400 hover:bg-custom-sidebar-background-80"
>
Your projects
{open ? (
<ChevronDown className="h-3.5 w-3.5" />
) : (
<ChevronRight className="h-3.5 w-3.5" />
)}
</Disclosure.Button>
{isAuthorizedUser && (
<button
className="opacity-0 group-hover:opacity-100"
onClick={() => {
setTrackElement("Sidebar");
setIsFavoriteProjectCreate(false);
setIsProjectModalOpen(true);
}}
>
<Plus className="h-3 w-3" />
</button>
)}
</div>
)}
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform scale-95 opacity-0"
enterTo="transform scale-100 opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform scale-100 opacity-100"
leaveTo="transform scale-95 opacity-0"
<Plus className="h-3 w-3" />
</button>
)}
</div>
)}
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform scale-95 opacity-0"
enterTo="transform scale-100 opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform scale-100 opacity-100"
leaveTo="transform scale-95 opacity-0"
>
<Disclosure.Panel as="div" className="space-y-2">
{favoriteProjects.map((projectId, index) => (
<ProjectSidebarListItem
key={projectId}
projectId={projectId}
handleCopyText={() => handleCopyText(projectId)}
projectListType="FAVORITES"
disableDrag
disableDrop
isLastChild={index === favoriteProjects.length - 1}
/>
))}
</Disclosure.Panel>
</Transition>
</>
)}
</Disclosure>
)}
</div>
<div>
{joinedProjects && joinedProjects.length > 0 && (
<Disclosure as="div" className="flex flex-col" defaultOpen>
{({ open }) => (
<>
{!isCollapsed && (
<div className="group flex w-full items-center justify-between rounded p-1.5 text-xs text-custom-sidebar-text-400 hover:bg-custom-sidebar-background-80">
<Disclosure.Button
as="button"
type="button"
className="group flex w-full items-center gap-1 whitespace-nowrap rounded px-1.5 text-left text-sm font-semibold text-custom-sidebar-text-400 hover:bg-custom-sidebar-background-80"
>
Your projects
{open ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
</Disclosure.Button>
{isAuthorizedUser && (
<button
className="opacity-0 group-hover:opacity-100"
onClick={() => {
setTrackElement("Sidebar");
setIsFavoriteProjectCreate(false);
setIsProjectModalOpen(true);
}}
>
<Disclosure.Panel as="div" className="space-y-2">
{joinedProjects.map((projectId, index) => (
<Draggable key={projectId} draggableId={projectId} index={index}>
{(provided, snapshot) => (
<div ref={provided.innerRef} {...provided.draggableProps}>
<ProjectSidebarListItem
key={projectId}
projectId={projectId}
provided={provided}
snapshot={snapshot}
handleCopyText={() => handleCopyText(projectId)}
/>
</div>
)}
</Draggable>
))}
</Disclosure.Panel>
</Transition>
{provided.placeholder}
</>
)}
</Disclosure>
)}
</div>
)}
</Droppable>
</DragDropContext>
<Plus className="h-3 w-3" />
</button>
)}
</div>
)}
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform scale-95 opacity-0"
enterTo="transform scale-100 opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform scale-100 opacity-100"
leaveTo="transform scale-95 opacity-0"
>
<Disclosure.Panel as="div">
{joinedProjects.map((projectId, index) => (
<ProjectSidebarListItem
key={projectId}
projectId={projectId}
projectListType="JOINED"
handleCopyText={() => handleCopyText(projectId)}
isLastChild={index === joinedProjects.length - 1}
handleOnProjectDrop={handleOnProjectDrop}
/>
))}
</Disclosure.Panel>
</Transition>
</>
)}
</Disclosure>
)}
</div>
{isAuthorizedUser && joinedProjects && joinedProjects.length === 0 && (
<button