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

Feat: Draggable #1730

Merged
merged 10 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 171 additions & 0 deletions src/internal/components/Draggable.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import Draggable from './Draggable';

describe('Draggable', () => {
beforeEach(() => {
vi.clearAllMocks();
});

it('renders children correctly', () => {
render(
<Draggable>
<div>Drag me</div>
</Draggable>,
);
expect(screen.getByTestId('ockDraggable')).toBeInTheDocument();
});

it('starts at the default position if no starting position is provided', () => {
render(
<Draggable>
<div>Drag me</div>
</Draggable>,
);
const draggable = screen.getByTestId('ockDraggable');
expect(draggable).toHaveStyle({ left: '20px', top: '20px' });
});

it('starts at the specified position if starting position is provided', () => {
render(
<Draggable startingPosition={{ x: 100, y: 100 }}>
<div>Drag me</div>
</Draggable>,
);
const draggable = screen.getByTestId('ockDraggable');
expect(draggable).toHaveStyle({ left: '100px', top: '100px' });
});

it('changes cursor style when dragging', () => {
render(
<Draggable>
<div>Drag me</div>
</Draggable>,
);
const draggable = screen.getByTestId('ockDraggable');
expect(draggable).toHaveClass('cursor-grab');

fireEvent.pointerDown(draggable);
expect(draggable).toHaveClass('cursor-grabbing');

fireEvent.pointerUp(draggable);
expect(draggable).toHaveClass('cursor-grab');
});

it('snaps to grid when dragging ends if enableSnapToGrid is true', async () => {
const user = userEvent.setup();
render(
<Draggable gridSize={10} startingPosition={{ x: 0, y: 0 }}>
<div>Drag me</div>
</Draggable>,
);

const draggable = screen.getByTestId('ockDraggable');
await user.pointer([
{ keys: '[MouseLeft>]', target: draggable },
{ coords: { x: 14, y: 16 } },
{ keys: '[/MouseLeft]' },
]);
expect(draggable).toHaveStyle({ left: '10px', top: '20px' });
});

it('does not snap to grid when dragging ends if enableSnapToGrid is false', async () => {
const user = userEvent.setup();
render(
<Draggable
gridSize={10}
startingPosition={{ x: 0, y: 0 }}
enableSnapToGrid={false}
>
<div>Drag me</div>
</Draggable>,
);

const draggable = screen.getByTestId('ockDraggable');
await user.pointer([
{ keys: '[MouseLeft>]', target: draggable },
{ coords: { x: 14, y: 16 } },
{ keys: '[/MouseLeft]' },
]);
expect(draggable).toHaveStyle({ left: '14px', top: '16px' });
});

it('handles touch events', () => {
render(
<Draggable>
<div>Drag me</div>
</Draggable>,
);
const draggable = screen.getByTestId('ockDraggable');

fireEvent.pointerDown(draggable, {
clientX: 0,
clientY: 0,
});
expect(draggable).toHaveClass('cursor-grabbing');

fireEvent.pointerMove(document, {
clientX: 50,
clientY: 50,
});

fireEvent.pointerUp(document);
expect(draggable).toHaveClass('cursor-grab');
});

it('calculates drag offset correctly', async () => {
const user = userEvent.setup();
render(
<Draggable startingPosition={{ x: 50, y: 50 }}>
<div>Drag me</div>
</Draggable>,
);
const draggable = screen.getByTestId('ockDraggable');

await user.pointer([
{ keys: '[MouseLeft>]', target: draggable, coords: { x: 60, y: 70 } },
{ coords: { x: 80, y: 90 } },
{ keys: '[/MouseLeft]' },
]);
expect(draggable).toHaveStyle({ left: '70px', top: '70px' });
});

it('updates position during drag movement', async () => {
const user = userEvent.setup();
render(
<Draggable startingPosition={{ x: 0, y: 0 }}>
<div>Drag me</div>
</Draggable>,
);
const draggable = screen.getByTestId('ockDraggable');

await user.pointer([
{ keys: '[MouseLeft>]', target: draggable, coords: { x: 0, y: 0 } },
{ coords: { x: 50, y: 50 } },
]);
expect(draggable).toHaveStyle({ left: '50px', top: '50px' });

await user.pointer([{ coords: { x: 100, y: 75 } }]);

expect(draggable).toHaveStyle({ left: '100px', top: '75px' });
});

it('cleans up event listeners when unmounted during drag', () => {
const { unmount } = render(
<Draggable>
<div>Drag me</div>
</Draggable>,
);
const draggable = screen.getByTestId('ockDraggable');

const removeSpy = vi.spyOn(document, 'removeEventListener');

fireEvent.pointerDown(draggable, { clientX: 0, clientY: 0 });

unmount();

expect(removeSpy).toHaveBeenCalledWith('pointermove', expect.any(Function));
expect(removeSpy).toHaveBeenCalledWith('pointerup', expect.any(Function));
});
});
85 changes: 85 additions & 0 deletions src/internal/components/Draggable.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { useCallback, useEffect, useState } from 'react';
import { zIndex } from '../../styles/constants';
import { cn } from '../../styles/theme';

type DraggableProps = {
children: React.ReactNode;
gridSize?: number;
startingPosition?: { x: number; y: number };
enableSnapToGrid?: boolean;
};

export default function Draggable({
children,
gridSize = 1,
startingPosition = { x: 20, y: 20 },
enableSnapToGrid = true,
brendan-defi marked this conversation as resolved.
Show resolved Hide resolved
}: DraggableProps) {
const [position, setPosition] = useState(startingPosition);
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
const [isDragging, setIsDragging] = useState(false);

const snapToGrid = useCallback(
(positionValue: number) => {
return Math.round(positionValue / gridSize) * gridSize;
},
[gridSize],
);
brendan-defi marked this conversation as resolved.
Show resolved Hide resolved

const handleDragStart = (e: React.PointerEvent) => {
setIsDragging(true);

setDragOffset({
x: e.clientX - position.x,
y: e.clientY - position.y,
});
};

useEffect(() => {
if (!isDragging) {
return;
}

const handleGlobalMove = (e: PointerEvent) => {
setPosition({
x: e.clientX - dragOffset.x,
y: e.clientY - dragOffset.y,
});
};

const handleGlobalEnd = () => {
setPosition((prev) => ({
x: enableSnapToGrid ? snapToGrid(prev.x) : prev.x,
y: enableSnapToGrid ? snapToGrid(prev.y) : prev.y,
}));
setIsDragging(false);
};

document.addEventListener('pointermove', handleGlobalMove);
document.addEventListener('pointerup', handleGlobalEnd);

return () => {
document.removeEventListener('pointermove', handleGlobalMove);
document.removeEventListener('pointerup', handleGlobalEnd);
};
}, [isDragging, dragOffset, snapToGrid, enableSnapToGrid]);

return (
<div
data-testid="ockDraggable"
className={cn(
'fixed select-none',
zIndex.modal,
isDragging ? 'cursor-grabbing' : 'cursor-grab',
)}
style={{
brendan-defi marked this conversation as resolved.
Show resolved Hide resolved
left: `${position.x}px`,
top: `${position.y}px`,
touchAction: 'none',
brendan-defi marked this conversation as resolved.
Show resolved Hide resolved
}}
onPointerDown={handleDragStart}
>
{children}
</div>
);
}
8 changes: 8 additions & 0 deletions src/styles/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const zIndex = {
base: 0,
navigation: 1,
dropdown: 10,
tooltip: 20,
modal: 40,
notification: 50,
};
Loading