Skip to content

Commit 8cd5ecf

Browse files
committed
refactor: drag offset naming and understanding why it's needed
1 parent cc8c9b4 commit 8cd5ecf

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

app/components/card/Card.tsx

+14-7
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,12 @@ export const cardLinks: LinksFunction = () => [
2828

2929
export function Card({ card, index }: { card: CardType; index: number }) {
3030
const [isDragging, setIsDragging] = useState(false);
31-
const [startPosition, setStartPosition] = useState({ x: 0, y: 0 });
31+
32+
// Needed to calculate the distance between the cursor and the card's top-left corner
33+
// Otherwise, the card would jump to the cursor's position when dragging
34+
// This would be a bad user experience
35+
// Hence needed to maintain relative position between the cursor and the card
36+
const [dragStartOffset, setDragStartOffset] = useState({ x: 0, y: 0 });
3237

3338
// Needed to properly move cursor to the end of the contentEditable span
3439
const [content, setContent] = useState(card.html);
@@ -61,8 +66,8 @@ export function Card({ card, index }: { card: CardType; index: number }) {
6166
if (isDragging) {
6267
function handleGlobalMouseMove(event: MouseEvent) {
6368
if (!isDragging) return;
64-
const newX = event.clientX - startPosition.x;
65-
const newY = event.clientY - startPosition.y;
69+
const newX = event.clientX - dragStartOffset.x;
70+
const newY = event.clientY - dragStartOffset.y;
6671
updateCardPosition(card.id, newX, newY);
6772
}
6873

@@ -83,13 +88,15 @@ export function Card({ card, index }: { card: CardType; index: number }) {
8388
}, [
8489
card.id,
8590
isDragging,
86-
startPosition.x,
87-
startPosition.y,
91+
dragStartOffset.x,
92+
dragStartOffset.y,
8893
updateCardPosition,
8994
]);
9095

9196
function handleMouseDown(event: React.MouseEvent<HTMLButtonElement>) {
92-
if (document.activeElement === cardContentRef.current) {
97+
const isUserEditingCardContent =
98+
document.activeElement === cardContentRef.current;
99+
if (isUserEditingCardContent) {
93100
return;
94101
}
95102

@@ -98,7 +105,7 @@ export function Card({ card, index }: { card: CardType; index: number }) {
98105

99106
setIsDragging(true);
100107

101-
setStartPosition({
108+
setDragStartOffset({
102109
x: startX - card.positionX,
103110
y: startY - card.positionY,
104111
});

0 commit comments

Comments
 (0)