Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to Detect Return to Previous Position in Drag-and-Drop #1496

Open
Maligosus opened this issue Oct 7, 2024 · 0 comments
Open

Unable to Detect Return to Previous Position in Drag-and-Drop #1496

Maligosus opened this issue Oct 7, 2024 · 0 comments

Comments

@Maligosus
Copy link

Maligosus commented Oct 7, 2024

Issue: Unable to Detect Return to Previous Position in Drag-and-Drop

Description

When dragging an item to a new position and then returning it to its original position without releasing the mouse, the active.id becomes equal to over.id, making it impossible to detect the return in the handleDragOver event.

After investigating, I found that the activeIndex does not update when the item's position changes. This results in a failure to capture the moment of returning the item to its original position.

Steps to Reproduce

  1. Drag an item to a new position.
  2. While still holding the mouse button, return the item to its original position.
  3. Observe that active.id now equals over.id, preventing the detection of the return.

Expected Behavior

The activeIndex should update appropriately to reflect the current position of the dragged item, allowing the detection of its return to the original position.

Current Behavior

When returning the item, active.id and over.id are the same, making it difficult to handle the drag-and-drop logic correctly.

Using TableHeaderGroup
import React, { useCallback, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';
import debounce from 'lodash/debounce';

import {
	rectSortingStrategy,
	SortableContext,
	SortingStrategy,
} from '@dnd-kit/sortable';
import {
	DndContext,
	MouseSensor,
	useSensor,
	useSensors,
	type DragOverEvent,
} from '@dnd-kit/core';
import { restrictToHorizontalAxis } from '@dnd-kit/modifiers';

import useTableStore from '../../hooks/use-store/use-table-store.hook';

import TableHeaderCell from './components/table-header-cell/table-header-cell';

import {
	TableHeaderContainer,
	TableSubHeadersContainer,
} from './table-header.css';

import TableColumn from '../../store/table/table-column/table-column';
import TableHeaderGroup from './components/table-header-group/table-header-group';

import TableHeaderDndMonitor from './components/table-header-dnd-monitor/table-header-dnd-monitor';
import { INTERNAL_COLUMN_ID } from '../../store/table/table-column/table-column.constant';

import useCollisionDetection from './hooks/use-collision-detection/use-collision-detection.hook';

import type { RowData } from '../../table.interface';

const TableHeader = <T extends RowData>() => {
	const { table, columnOrdering, columnSizing } = useTableStore<T>();

	const collisionDetection = useCollisionDetection();

	const [headerOrder, setHeaderOrder] = useState(toJS(columnOrdering.order));

	useEffect(() => {
		if (!columnOrdering.isOrderChangingNow) {
			setHeaderOrder(columnOrdering.order);
		}
	}, [columnOrdering.order, columnOrdering.isOrderChangingNow]);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	const handleDragStart = useCallback(() => {
		columnOrdering.setIsChangingOrder(true);
	}, []);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	const handleDragEnd = useCallback(() => {
		columnOrdering.setIsChangingOrder(false);
	}, []);

	const sortingStrategy = useCallback<SortingStrategy>((args) => {
		return rectSortingStrategy(args);
	}, []);

	const handleDragOver = useCallback(
		debounce((event: DragOverEvent) => {
			const { active, over } = event;
			if (active && over && active.id !== over.id) {
				if (
					active.data.current?.column instanceof TableColumn &&
					over.data.current?.column instanceof TableColumn &&
					!over.data.current.column.isInternal
				) {
					const activeDataColumnIds = columnOrdering
						.getSortedDataColumns(active.data.current.column)
						.map((item) => item.id);
					const overDataColumnIds = columnOrdering
						.getSortedDataColumns(over.data.current.column)
						.map((item) => item.id);

					const previousOrder = columnOrdering.order.filter(
						(itemId) => itemId !== INTERNAL_COLUMN_ID,
					);

					const activeDataColumnMinIndex = previousOrder.indexOf(
						activeDataColumnIds[0],
					);

					const overDataColumnMinIndex = previousOrder.indexOf(
						overDataColumnIds[0],
					);

					let newOrder: string[] = [...previousOrder];

					newOrder.splice(activeDataColumnMinIndex, activeDataColumnIds.length);

					if (
						activeDataColumnMinIndex !== -1 &&
						overDataColumnMinIndex !== -1
					) {
						if (activeDataColumnMinIndex < overDataColumnMinIndex) {
							const overDataColumnMaxIndex = previousOrder.indexOf(
								overDataColumnIds[overDataColumnIds.length - 1],
							);

							const end = previousOrder.slice(
								overDataColumnMaxIndex + 1,
								previousOrder.length,
							);
							newOrder.splice(newOrder.length - end.length, end.length);

							newOrder = [...newOrder, ...activeDataColumnIds, ...end];
						} else {
							const start = previousOrder.slice(0, overDataColumnMinIndex);

							newOrder.splice(0, start.length);

							newOrder = [...start, ...activeDataColumnIds, ...newOrder];
						}

						columnOrdering.setOrder(newOrder);
					}
				}
			}
		}, 300),
		[],
	);

	const headerContent = () => {
		const renderHeaders = (columns: TableColumn<T>[]) => {
			const filteredDataColumns = table.dataColumns.filter(
				(item) => headerOrder.includes(item.id) || item.isInternal,
			);

			const filtered = columns
				.filter((column) => {
					const isDataColumnIncluded = filteredDataColumns.some((item) =>
						item.path.includes(column.id),
					);

					return isDataColumnIncluded;
				})
				.sort((a, b) => {
					return (
						columnOrdering.getColumnOrder(a, headerOrder) -
						columnOrdering.getColumnOrder(b, headerOrder)
					);
				});

			const sortableItemIds = filtered
				.filter((item) => item.id !== INTERNAL_COLUMN_ID)
				.map((item) => item.path);

			return (
				<SortableContext items={sortableItemIds} strategy={sortingStrategy}>
					{filtered.map((column) => {
						if (column.children.length) {
							return (
								<TableHeaderGroup column={column} key={column.id}>
									<TableHeaderCell column={column} />
									<TableSubHeadersContainer>
										{renderHeaders(column.children)}
									</TableSubHeadersContainer>
								</TableHeaderGroup>
							);
						}
						return (
							<TableHeaderGroup column={column} key={column.id}>
								<TableHeaderCell column={column} />
							</TableHeaderGroup>
						);
					})}
				</SortableContext>
			);
		};

		return renderHeaders(table.baseColumns);
	};

	const sensors = useSensors(useSensor(MouseSensor));

	return (
		<DndContext
			sensors={sensors}
			modifiers={[restrictToHorizontalAxis]}
			collisionDetection={collisionDetection}
		>
			<TableHeaderDndMonitor
				onDragStart={handleDragStart}
				onDragEnd={handleDragEnd}
				onDragOver={handleDragOver}
			/>
			<TableHeaderContainer style={columnSizing.dataColumnSize}>
				{headerContent()}
			</TableHeaderContainer>
		</DndContext>
	);
};

export default observer(TableHeader);


export default observer(TableHeader);
TableHeaderGroup
const TableHeaderGroup = <T extends RowData>({
	column,
	children,
}: React.PropsWithChildren<TableHeaderGroupProups<T>>) => {
	const { setNodeRef, attributes, listeners, transform, active } = useSortable({
		id: column.path,
		data: {
			column,
		},
	});

	const style: React.CSSProperties = {
		transform: CSS.Translate.toString(transform),
		zIndex: active?.id === column.path ? 10 : undefined,
	};

	return (
		<TableHeaderGroupContainer
			id={column.id}
			ref={setNodeRef}
			style={style}
			{...attributes}
			{...listeners}
		>
			{children}
		</TableHeaderGroupContainer>
	);
};

export default TableHeaderGroup;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant