clauderic / clauderic/dnd-kit

Operation.shape is null on first modifier.apply() call

Open
#1,986 2 comments 0 reactions 0 assignees View on GitHub
abstract bug react triage:done
Dominant language
TypeScript
Stars
17.6k
Forks
924
Avg merge
2d 10h
Merged PRs (30d)
2

Description

Hello there,

I am using dnd-kit/react@0.3.2 and trying to create my custom modifier, that will snap topleft corner of the dragged object to the mouse cursor. Here is what I have so far:

```
import {
DragDropManager,
Modifier,
PluginOptions,
} from "@dnd-kit/abstract";
import { Coordinates } from '@dnd-kit/geometry';

export class snapLeftTopToCursor extends Modifier {
constructor(manager: DragDropManager, options?: PluginOptions) {
super(manager, options)
}

public apply(operation: any): Coordinates {
const { transform, activatorEvent, shape } = operation

const rect = shape?.initial
if (this.disabled || !rect) return transform;

const offsetX = activatorEvent?.clientX - rect.left;
const offsetY = activatorEvent?.clientY - rect.top;

return {
...transform,
x: transform.x + offsetX,
y: transform.y + offsetY,
}
}
}
```
The problem is that when the `apply()` is called for the first time, `shape` is `null`, and so I can not calculate new tranform coordinates.

This is just a migration of a modifier that was created for the legacy dnd-kit, and it works as expected:

```
import { Modifier } from "@dnd-kit/core";
import { getEventCoordinates } from '@dnd-kit/utilities';

export const snapLeftTopToCursor: Modifier = ({ transform, activatorEvent, draggingNodeRect }) => {
if (draggingNodeRect && activatorEvent) {
const activatorCoordinates = getEventCoordinates(activatorEvent);

if (!activatorCoordinates) {
return transform;
}

const offsetX = activatorCoordinates.x - draggingNodeRect.left;
const offsetY = activatorCoordinates.y - draggingNodeRect.top;

return {
...transform,
x: transform.x + offsetX,
y: transform.y + offsetY,
};
}

return transform;
}

```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.